diff --git a/JSONStream/JSONStream.d.ts b/JSONStream/JSONStream.d.ts index 029e5b8e9c..a3481906b3 100644 --- a/JSONStream/JSONStream.d.ts +++ b/JSONStream/JSONStream.d.ts @@ -5,18 +5,17 @@ /// -declare module 'JSONStream' { - export interface Options { - recurse: boolean; - } - export function parse(pattern: any): NodeJS.ReadWriteStream; - export function parse(patterns: any[]): NodeJS.ReadWriteStream; - - export function stringify(): NodeJS.ReadWriteStream; - export function stringify(open: string, sep: string, close: string): NodeJS.ReadWriteStream; - - export function stringifyObject(): NodeJS.ReadWriteStream; - export function stringifyObject(open: string, sep: string, close: string): NodeJS.ReadWriteStream; +export interface Options { + recurse: boolean; } + +declare export function parse(pattern: any): NodeJS.ReadWriteStream; +declare export function parse(patterns: any[]): NodeJS.ReadWriteStream; + +declare export function stringify(): NodeJS.ReadWriteStream; +declare export function stringify(open: string, sep: string, close: string): NodeJS.ReadWriteStream; + +declare export function stringifyObject(): NodeJS.ReadWriteStream; +declare export function stringifyObject(open: string, sep: string, close: string): NodeJS.ReadWriteStream; diff --git a/abs/abs.d.ts b/abs/abs.d.ts index 58a5335283..b5182da9e6 100644 --- a/abs/abs.d.ts +++ b/abs/abs.d.ts @@ -3,12 +3,11 @@ // Definitions by: Aya Morisawa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "abs" { - /** - * Compute the absolute path of an input. - * @param input The input path. - */ - function Abs(input: string): string; - export default Abs; -} +/** + * Compute the absolute path of an input. + * @param input The input path. + */ +declare function Abs(input: string): string; + +export default Abs; diff --git a/absolute/absolute.d.ts b/absolute/absolute.d.ts index c0e8e9bd6e..4dc77e5fbe 100644 --- a/absolute/absolute.d.ts +++ b/absolute/absolute.d.ts @@ -3,11 +3,10 @@ // Definitions by: Aya Morisawa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "absolute" { - /** - * Test if a path is absolute - */ - function absolute(path: string): boolean; - export default absolute; -} +/** + * Test if a path is absolute + */ +declare function absolute(path: string): boolean; + +export default absolute; diff --git a/acl/acl.d.ts b/acl/acl.d.ts index 06defa2449..daabcf628f 100644 --- a/acl/acl.d.ts +++ b/acl/acl.d.ts @@ -9,42 +9,42 @@ /// /// -declare module "acl" { - import http = require('http'); - import Promise = require("bluebird"); - type strings = string|string[]; - type Value = string|number; - type Values = Value|Value[]; - type Action = () => any; - type Callback = (err: Error) => any; - type AnyCallback = (err: Error, obj: any) => any; - type AllowedCallback = (err: Error, allowed: boolean) => any; - type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value; +import http = require('http'); +import Promise = require("bluebird"); - interface AclStatic { +type strings = string | string[]; +type Value = string | number; +type Values = Value | Value[]; +type Action = () => any; +type Callback = (err: Error) => any; +type AnyCallback = (err: Error, obj: any) => any; +type AllowedCallback = (err: Error, allowed: boolean) => any; +type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value; + +interface AclStatic { new (backend: Backend, logger: Logger, options: Option): Acl; new (backend: Backend, logger: Logger): Acl; new (backend: Backend): Acl; memoryBackend: MemoryBackendStatic; - } +} - interface Logger { - debug: (msg: string)=>any; - } +interface Logger { + debug: (msg: string) => any; +} - interface Acl { +interface Acl { addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; - userRoles: (userId: Value, cb?: (err: Error, roles: string[])=>any) => Promise; - roleUsers: (role: Value, cb?: (err: Error, users: Values)=>any) => Promise; - hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean)=>any) => Promise; + userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise; + roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise; + hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean) => any) => Promise; addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise; removeRole: (role: string, cb?: Callback) => Promise; removeResource: (resource: string, cb?: Callback) => Promise; allow: { - (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise; - (aclSets: AclSet|AclSet[]): Promise; + (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise; + (aclSets: AclSet | AclSet[]): Promise; } removeAllow: (role: string, resources: strings, permissions: strings, cb?: Callback) => Promise; removePermissions: (role: string, resources: strings, permissions: strings, cb?: Function) => Promise; @@ -53,41 +53,41 @@ declare module "acl" { areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise; whatResources: (roles: strings, permissions: strings, cb?: AnyCallback) => Promise; permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise; - middleware: (numPathComponents: number, userId: Value|GetUserId, actions: strings) => Promise; - } + middleware: (numPathComponents: number, userId: Value | GetUserId, actions: strings) => Promise; +} - interface Option { +interface Option { buckets?: BucketsOption; - } +} - interface BucketsOption { +interface BucketsOption { meta?: string; parents?: string; permissions?: string; resources?: string; roles?: string; users?: string; - } +} - interface AclSet { +interface AclSet { roles: strings; allows: AclAllow[]; - } +} - interface AclAllow { +interface AclAllow { resources: strings; permissions: strings; - } +} - interface MemoryBackend extends Backend { } - interface MemoryBackendStatic { - new(): MemoryBackend; - } +interface MemoryBackend extends Backend { } +interface MemoryBackendStatic { + new (): MemoryBackend; +} - // - // For internal use - // - interface Backend { +// +// For internal use +// +interface Backend { begin: () => T; end: (transaction: T, cb?: Action) => void; clean: (cb?: Action) => void; @@ -101,50 +101,49 @@ declare module "acl" { getAsync: Function; cleanAsync: Function; unionAsync: Function; - } +} - interface Contract { - (args: IArguments): Contract|NoOp; +interface Contract { + (args: IArguments): Contract | NoOp; debug: boolean; fulfilled: boolean; args: any[]; checkedParams: string[]; - params: (...types: string[]) => Contract|NoOp; + params: (...types: string[]) => Contract | NoOp; end: () => void; - } +} - interface NoOp { +interface NoOp { params: (...types: string[]) => NoOp; end: () => void; - } - - // for redis backend - import redis = require('redis'); - - interface AclStatic { - redisBackend: RedisBackendStatic; - } - - interface RedisBackend extends Backend { } - interface RedisBackendStatic { - new(redis: redis.RedisClient, prefix: string): RedisBackend; - new(redis: redis.RedisClient): RedisBackend; - } - - // for mongodb backend - import mongo = require('mongodb'); - - interface AclStatic { - mongodbBackend: MongodbBackendStatic; - } - - interface MongodbBackend extends Backend { } - interface MongodbBackendStatic { - new(db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend; - new(db: mongo.Db, prefix: string): MongodbBackend; - new(db: mongo.Db): MongodbBackend; - } - - var _: AclStatic; - export = _; } + +// for redis backend +import redis = require('redis'); + +interface AclStatic { + redisBackend: RedisBackendStatic; +} + +interface RedisBackend extends Backend { } +interface RedisBackendStatic { + new (redis: redis.RedisClient, prefix: string): RedisBackend; + new (redis: redis.RedisClient): RedisBackend; +} + +// for mongodb backend +import mongo = require('mongodb'); + +interface AclStatic { + mongodbBackend: MongodbBackendStatic; +} + +interface MongodbBackend extends Backend { } +interface MongodbBackendStatic { + new (db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend; + new (db: mongo.Db, prefix: string): MongodbBackend; + new (db: mongo.Db): MongodbBackend; +} + +declare var _: AclStatic; +export = _; diff --git a/adm-zip/adm-zip.d.ts b/adm-zip/adm-zip.d.ts index 19298149c3..06e1181694 100644 --- a/adm-zip/adm-zip.d.ts +++ b/adm-zip/adm-zip.d.ts @@ -5,303 +5,302 @@ /// -declare module "adm-zip" { - class AdmZip { - /** - * Create a new, empty archive. - */ - constructor(); - /** - * Read an existing archive. - */ - constructor(fileName: string); - /** - * Extracts the given entry from the archive and returns the content as a - * Buffer object. - * @param entry String with the full path of the entry - * @return Buffer or Null in case of error - */ - readFile(entry: string): Buffer; - /** - * Extracts the given entry from the archive and returns the content as a - * Buffer object. - * @param entry ZipEntry object - * @return Buffer or Null in case of error - */ - readFile(entry: AdmZip.IZipEntry): Buffer; - /** - * Asynchronous readFile - * @param entry String with the full path of the entry - * @param callback Called with a Buffer or Null in case of error - */ - readFileAsync(entry: string, callback: (data: Buffer, err: string) => any): void; - /** - * Asynchronous readFile - * @param entry ZipEntry object - * @param callback Called with a Buffer or Null in case of error - * @return Buffer or Null in case of error - */ - readFileAsync(entry: AdmZip.IZipEntry, callback: (data: Buffer, err: string) => any): void; - /** - * Extracts the given entry from the archive and returns the content as - * plain text in the given encoding - * @param entry String with the full path of the entry - * @param encoding Optional. If no encoding is specified utf8 is used - * @return String - */ - readAsText(fileName: string, encoding?: string): string; - /** - * Extracts the given entry from the archive and returns the content as - * plain text in the given encoding - * @param entry ZipEntry object - * @param encoding Optional. If no encoding is specified utf8 is used - * @return String - */ - readAsText(fileName: AdmZip.IZipEntry, encoding?: string): string; - /** - * Asynchronous readAsText - * @param entry String with the full path of the entry - * @param callback Called with the resulting string. - * @param encoding Optional. If no encoding is specified utf8 is used - */ - readAsTextAsync(fileName: string, callback: (data: string) => any, encoding?: string): void; - /** - * Asynchronous readAsText - * @param entry ZipEntry object - * @param callback Called with the resulting string. - * @param encoding Optional. If no encoding is specified utf8 is used - */ - readAsTextAsync(fileName: AdmZip.IZipEntry, callback: (data: string) => any, encoding?: string): void; - /** - * Remove the entry from the file or the entry and all its nested directories - * and files if the given entry is a directory - * @param entry String with the full path of the entry - */ - deleteFile(entry: string): void; - /** - * Remove the entry from the file or the entry and all its nested directories - * and files if the given entry is a directory - * @param entry A ZipEntry object. - */ - deleteFile(entry: AdmZip.IZipEntry): void; - /** - * Adds a comment to the zip. The zip must be rewritten after - * adding the comment. - * @param comment Content of the comment. - */ - addZipComment(comment: string): void; - /** - * Returns the zip comment - * @return The zip comment. - */ - getZipComment(): string; - /** - * Adds a comment to a specified zipEntry. The zip must be rewritten after - * adding the comment. - * The comment cannot exceed 65535 characters in length. - * @param entry String with the full path of the entry - * @param comment The comment to add to the entry. - */ - addZipEntryComment(entry: string, comment: string): void; - /** - * Adds a comment to a specified zipEntry. The zip must be rewritten after - * adding the comment. - * The comment cannot exceed 65535 characters in length. - * @param entry ZipEntry object. - * @param comment The comment to add to the entry. - */ - addZipEntryComment(entry: AdmZip.IZipEntry, comment: string): void; - /** - * Returns the comment of the specified entry. - * @param entry String with the full path of the entry. - * @return String The comment of the specified entry. - */ - getZipEntryComment(entry: string): string; - /** - * Returns the comment of the specified entry - * @param entry ZipEntry object. - * @return String The comment of the specified entry. - */ - getZipEntryComment(entry: AdmZip.IZipEntry): string; - /** - * Updates the content of an existing entry inside the archive. The zip - * must be rewritten after updating the content - * @param entry String with the full path of the entry. - * @param content The entry's new contents. - */ - updateFile(entry: string, content: Buffer): void; - /** - * Updates the content of an existing entry inside the archive. The zip - * must be rewritten after updating the content - * @param entry ZipEntry object. - * @param content The entry's new contents. - */ - updateFile(entry: AdmZip.IZipEntry, content: Buffer): void; - /** - * Adds a file from the disk to the archive. - * @param localPath Path to a file on disk. - * @param zipPath Path to a directory in the archive. Defaults to the empty - * string. - */ - addLocalFile(localPath: string, zipPath?: string): void; - /** - * Adds a local directory and all its nested files and directories to the - * archive. - * @param localPath Path to a folder on disk. - * @param zipPath Path to a folder in the archive. Defaults to an empty - * string. - */ - addLocalFolder(localPath: string, zipPath?: string): void; - /** - * Allows you to create a entry (file or directory) in the zip file. - * If you want to create a directory the entryName must end in / and a null - * buffer should be provided. - * @param entryName Entry path - * @param content Content to add to the entry; must be a 0-length buffer - * for a directory. - * @param comment Comment to add to the entry. - * @param attr Attribute to add to the entry. - */ - addFile(entryName: string, data: Buffer, comment?: string, attr?: number): void; - /** - * Returns an array of ZipEntry objects representing the files and folders - * inside the archive - */ - getEntries(): AdmZip.IZipEntry[]; - /** - * Returns a ZipEntry object representing the file or folder specified by - * ``name``. - * @param name Name of the file or folder to retrieve. - * @return ZipEntry The entry corresponding to the name. - */ - getEntry(name: string): AdmZip.IZipEntry; - /** - * Extracts the given entry to the given targetPath. - * If the entry is a directory inside the archive, the entire directory and - * its subdirectories will be extracted. - * @param entry String with the full path of the entry - * @param targetPath Target folder where to write the file - * @param maintainEntryPath If maintainEntryPath is true and the entry is - * inside a folder, the entry folder will be created in targetPath as - * well. Default is TRUE - * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE - * - * @return Boolean - */ - extractEntryTo(entryPath: string, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean; - /** - * Extracts the given entry to the given targetPath. - * If the entry is a directory inside the archive, the entire directory and - * its subdirectories will be extracted. - * @param entry ZipEntry object - * @param targetPath Target folder where to write the file - * @param maintainEntryPath If maintainEntryPath is true and the entry is - * inside a folder, the entry folder will be created in targetPath as - * well. Default is TRUE - * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE - * @return Boolean - */ - extractEntryTo(entryPath: AdmZip.IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean; - /** - * Extracts the entire archive to the given location - * @param targetPath Target location - * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE - */ - extractAllTo(targetPath: string, overwrite?: boolean): void; - /** - * Extracts the entire archive to the given location - * @param targetPath Target location - * @param overwrite If the file already exists at the target path, the file - * will be overwriten if this is true. Default is FALSE - * @param callback The callback function will be called afeter extraction - */ - extractAllToAsync(targetPath: string, overwrite: boolean, callback: (error: Error) => void): void; - /** - * Writes the newly created zip file to disk at the specified location or - * if a zip was opened and no ``targetFileName`` is provided, it will - * overwrite the opened zip - * @param targetFileName - */ - writeZip(targetPath?: string): void; - /** - * Returns the content of the entire zip file as a Buffer object - * @return Buffer - */ - toBuffer(): Buffer; - } - namespace AdmZip { - /** - * The ZipEntry is more than a structure representing the entry inside the - * zip file. Beside the normal attributes and headers a entry can have, the - * class contains a reference to the part of the file where the compressed - * data resides and decompresses it when requested. It also compresses the - * data and creates the headers required to write in the zip file. - */ - interface IZipEntry { - /** - * Represents the full name and path of the file - */ - entryName: string; - rawEntryName: Buffer; - /** - * Extra data associated with this entry. - */ - extra: Buffer; - /** - * Entry comment. - */ - comment: string; - name: string; - /** - * Read-Only property that indicates the type of the entry. - */ - isDirectory: boolean; - /** - * Get the header associated with this ZipEntry. - */ - header: Buffer; - /** - * Retrieve the compressed data for this entry. Note that this may trigger - * compression if any properties were modified. - */ - getCompressedData(): Buffer; - /** - * Asynchronously retrieve the compressed data for this entry. Note that - * this may trigger compression if any properties were modified. - */ - getCompressedDataAsync(callback: (data: Buffer) => void): void; - /** - * Set the (uncompressed) data to be associated with this entry. - */ - setData(value: string): void; - /** - * Set the (uncompressed) data to be associated with this entry. - */ - setData(value: Buffer): void; - /** - * Get the decompressed data associated with this entry. - */ - getData(): Buffer; - /** - * Asynchronously get the decompressed data associated with this entry. - */ - getDataAsync(callback: (data: Buffer) => void): void; - /** - * Returns the CEN Entry Header to be written to the output zip file, plus - * the extra data and the entry comment. - */ - packHeader(): Buffer; - /** - * Returns a nicely formatted string with the most important properties of - * the ZipEntry. - */ - toString(): string; - } - } - - export = AdmZip; +declare class AdmZip { + /** + * Create a new, empty archive. + */ + constructor(); + /** + * Read an existing archive. + */ + constructor(fileName: string); + /** + * Extracts the given entry from the archive and returns the content as a + * Buffer object. + * @param entry String with the full path of the entry + * @return Buffer or Null in case of error + */ + readFile(entry: string): Buffer; + /** + * Extracts the given entry from the archive and returns the content as a + * Buffer object. + * @param entry ZipEntry object + * @return Buffer or Null in case of error + */ + readFile(entry: AdmZip.IZipEntry): Buffer; + /** + * Asynchronous readFile + * @param entry String with the full path of the entry + * @param callback Called with a Buffer or Null in case of error + */ + readFileAsync(entry: string, callback: (data: Buffer, err: string) => any): void; + /** + * Asynchronous readFile + * @param entry ZipEntry object + * @param callback Called with a Buffer or Null in case of error + * @return Buffer or Null in case of error + */ + readFileAsync(entry: AdmZip.IZipEntry, callback: (data: Buffer, err: string) => any): void; + /** + * Extracts the given entry from the archive and returns the content as + * plain text in the given encoding + * @param entry String with the full path of the entry + * @param encoding Optional. If no encoding is specified utf8 is used + * @return String + */ + readAsText(fileName: string, encoding?: string): string; + /** + * Extracts the given entry from the archive and returns the content as + * plain text in the given encoding + * @param entry ZipEntry object + * @param encoding Optional. If no encoding is specified utf8 is used + * @return String + */ + readAsText(fileName: AdmZip.IZipEntry, encoding?: string): string; + /** + * Asynchronous readAsText + * @param entry String with the full path of the entry + * @param callback Called with the resulting string. + * @param encoding Optional. If no encoding is specified utf8 is used + */ + readAsTextAsync(fileName: string, callback: (data: string) => any, encoding?: string): void; + /** + * Asynchronous readAsText + * @param entry ZipEntry object + * @param callback Called with the resulting string. + * @param encoding Optional. If no encoding is specified utf8 is used + */ + readAsTextAsync(fileName: AdmZip.IZipEntry, callback: (data: string) => any, encoding?: string): void; + /** + * Remove the entry from the file or the entry and all its nested directories + * and files if the given entry is a directory + * @param entry String with the full path of the entry + */ + deleteFile(entry: string): void; + /** + * Remove the entry from the file or the entry and all its nested directories + * and files if the given entry is a directory + * @param entry A ZipEntry object. + */ + deleteFile(entry: AdmZip.IZipEntry): void; + /** + * Adds a comment to the zip. The zip must be rewritten after + * adding the comment. + * @param comment Content of the comment. + */ + addZipComment(comment: string): void; + /** + * Returns the zip comment + * @return The zip comment. + */ + getZipComment(): string; + /** + * Adds a comment to a specified zipEntry. The zip must be rewritten after + * adding the comment. + * The comment cannot exceed 65535 characters in length. + * @param entry String with the full path of the entry + * @param comment The comment to add to the entry. + */ + addZipEntryComment(entry: string, comment: string): void; + /** + * Adds a comment to a specified zipEntry. The zip must be rewritten after + * adding the comment. + * The comment cannot exceed 65535 characters in length. + * @param entry ZipEntry object. + * @param comment The comment to add to the entry. + */ + addZipEntryComment(entry: AdmZip.IZipEntry, comment: string): void; + /** + * Returns the comment of the specified entry. + * @param entry String with the full path of the entry. + * @return String The comment of the specified entry. + */ + getZipEntryComment(entry: string): string; + /** + * Returns the comment of the specified entry + * @param entry ZipEntry object. + * @return String The comment of the specified entry. + */ + getZipEntryComment(entry: AdmZip.IZipEntry): string; + /** + * Updates the content of an existing entry inside the archive. The zip + * must be rewritten after updating the content + * @param entry String with the full path of the entry. + * @param content The entry's new contents. + */ + updateFile(entry: string, content: Buffer): void; + /** + * Updates the content of an existing entry inside the archive. The zip + * must be rewritten after updating the content + * @param entry ZipEntry object. + * @param content The entry's new contents. + */ + updateFile(entry: AdmZip.IZipEntry, content: Buffer): void; + /** + * Adds a file from the disk to the archive. + * @param localPath Path to a file on disk. + * @param zipPath Path to a directory in the archive. Defaults to the empty + * string. + */ + addLocalFile(localPath: string, zipPath?: string): void; + /** + * Adds a local directory and all its nested files and directories to the + * archive. + * @param localPath Path to a folder on disk. + * @param zipPath Path to a folder in the archive. Defaults to an empty + * string. + */ + addLocalFolder(localPath: string, zipPath?: string): void; + /** + * Allows you to create a entry (file or directory) in the zip file. + * If you want to create a directory the entryName must end in / and a null + * buffer should be provided. + * @param entryName Entry path + * @param content Content to add to the entry; must be a 0-length buffer + * for a directory. + * @param comment Comment to add to the entry. + * @param attr Attribute to add to the entry. + */ + addFile(entryName: string, data: Buffer, comment?: string, attr?: number): void; + /** + * Returns an array of ZipEntry objects representing the files and folders + * inside the archive + */ + getEntries(): AdmZip.IZipEntry[]; + /** + * Returns a ZipEntry object representing the file or folder specified by + * ``name``. + * @param name Name of the file or folder to retrieve. + * @return ZipEntry The entry corresponding to the name. + */ + getEntry(name: string): AdmZip.IZipEntry; + /** + * Extracts the given entry to the given targetPath. + * If the entry is a directory inside the archive, the entire directory and + * its subdirectories will be extracted. + * @param entry String with the full path of the entry + * @param targetPath Target folder where to write the file + * @param maintainEntryPath If maintainEntryPath is true and the entry is + * inside a folder, the entry folder will be created in targetPath as + * well. Default is TRUE + * @param overwrite If the file already exists at the target path, the file + * will be overwriten if this is true. Default is FALSE + * + * @return Boolean + */ + extractEntryTo(entryPath: string, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean; + /** + * Extracts the given entry to the given targetPath. + * If the entry is a directory inside the archive, the entire directory and + * its subdirectories will be extracted. + * @param entry ZipEntry object + * @param targetPath Target folder where to write the file + * @param maintainEntryPath If maintainEntryPath is true and the entry is + * inside a folder, the entry folder will be created in targetPath as + * well. Default is TRUE + * @param overwrite If the file already exists at the target path, the file + * will be overwriten if this is true. Default is FALSE + * @return Boolean + */ + extractEntryTo(entryPath: AdmZip.IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean; + /** + * Extracts the entire archive to the given location + * @param targetPath Target location + * @param overwrite If the file already exists at the target path, the file + * will be overwriten if this is true. Default is FALSE + */ + extractAllTo(targetPath: string, overwrite?: boolean): void; + /** + * Extracts the entire archive to the given location + * @param targetPath Target location + * @param overwrite If the file already exists at the target path, the file + * will be overwriten if this is true. Default is FALSE + * @param callback The callback function will be called afeter extraction + */ + extractAllToAsync(targetPath: string, overwrite: boolean, callback: (error: Error) => void): void; + /** + * Writes the newly created zip file to disk at the specified location or + * if a zip was opened and no ``targetFileName`` is provided, it will + * overwrite the opened zip + * @param targetFileName + */ + writeZip(targetPath?: string): void; + /** + * Returns the content of the entire zip file as a Buffer object + * @return Buffer + */ + toBuffer(): Buffer; } + +declare namespace AdmZip { + /** + * The ZipEntry is more than a structure representing the entry inside the + * zip file. Beside the normal attributes and headers a entry can have, the + * class contains a reference to the part of the file where the compressed + * data resides and decompresses it when requested. It also compresses the + * data and creates the headers required to write in the zip file. + */ + interface IZipEntry { + /** + * Represents the full name and path of the file + */ + entryName: string; + rawEntryName: Buffer; + /** + * Extra data associated with this entry. + */ + extra: Buffer; + /** + * Entry comment. + */ + comment: string; + name: string; + /** + * Read-Only property that indicates the type of the entry. + */ + isDirectory: boolean; + /** + * Get the header associated with this ZipEntry. + */ + header: Buffer; + /** + * Retrieve the compressed data for this entry. Note that this may trigger + * compression if any properties were modified. + */ + getCompressedData(): Buffer; + /** + * Asynchronously retrieve the compressed data for this entry. Note that + * this may trigger compression if any properties were modified. + */ + getCompressedDataAsync(callback: (data: Buffer) => void): void; + /** + * Set the (uncompressed) data to be associated with this entry. + */ + setData(value: string): void; + /** + * Set the (uncompressed) data to be associated with this entry. + */ + setData(value: Buffer): void; + /** + * Get the decompressed data associated with this entry. + */ + getData(): Buffer; + /** + * Asynchronously get the decompressed data associated with this entry. + */ + getDataAsync(callback: (data: Buffer) => void): void; + /** + * Returns the CEN Entry Header to be written to the output zip file, plus + * the extra data and the entry comment. + */ + packHeader(): Buffer; + /** + * Returns a nicely formatted string with the most important properties of + * the ZipEntry. + */ + toString(): string; + } +} + +export = AdmZip; diff --git a/agenda/agenda.d.ts b/agenda/agenda.d.ts index 011676bc86..b6e2dc08d1 100644 --- a/agenda/agenda.d.ts +++ b/agenda/agenda.d.ts @@ -6,438 +6,437 @@ /// /// -declare module "agenda" { - import {EventEmitter} from "events"; - import {Db, Collection, ObjectID} from "mongodb"; - interface Callback { - (err?: Error): void; - } +import {EventEmitter} from "events"; +import {Db, Collection, ObjectID} from "mongodb"; - interface ResultCallback { - (err?: Error, result?: T): void; - } - - /** - * Agenda Configuration. - */ - interface AgendaConfiguration { - - /** - * Sets the interval with which the queue is checked. A number in milliseconds or a frequency string. - */ - processEvery?: string | number; - - /** - * Takes a number which specifies the default number of a specific job that can be running at any given moment. - * By default it is 5. - */ - defaultConcurrency?: number; - - /** - * Takes a number which specifies the max number of jobs that can be running at any given moment. By default it - * is 20. - */ - maxConcurrency?: number; - - /** - * Takes a number which specifies the default number of a specific job that can be locked at any given moment. - * By default it is 0 for no max. - */ - defaultLockLimit?: number; - - /** - * Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is - * 0 for no max. - */ - lockLimit?: number; - - /** - * Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This - * can be overridden by specifying the lockLifetime option to a defined job. - */ - defaultLockLifetime?: number; - - /** - * Specifies that Agenda should be initialized using and existing MongoDB connection. - */ - mongo?: { - /** - * The MongoDB database connection to use. - */ - db: Db; - - /** - * The name of the collection to use. - */ - collection?: string; - } - - /** - * Specifies that Agenda should connect to MongoDB. - */ - db?: { - /** - * The connection URL. - */ - address: string; - - /** - * The name of the collection to use. - */ - collection?: string; - - /** - * Connection options to pass to MongoDB. - */ - options?: any; - } - } - - /** - * The database record associated with a job. - */ - interface JobAttributes { - /** - * The record identity. - */ - _id: ObjectID; - - /** - * The name of the job. - */ - name: string; - - /** - * The type of the job (single|normal). - */ - type: string; - - /** - * The job details. - */ - data: { [name: string]: any }; - - /** - * The priority of the job. - */ - priority: number; - - /** - * How often the job is repeated using a human-readable or cron format. - */ - repeatInterval: string | number; - - /** - * The timezone that conforms to [moment-timezone](http://momentjs.com/timezone/). - */ - repeatTimezone: string; - - /** - * Date/time the job was las modified. - */ - lastModifiedBy: string; - - /** - * Date/time the job will run next. - */ - nextRunAt: Date; - - /** - * Date/time the job was locked. - */ - lockedAt: Date; - - /** - * Date/time the job was last run. - */ - lastRunAt: Date; - - /** - * Date/time the job last finished running. - */ - lastFinishedAt: Date; - - /** - * The reason the job failed. - */ - failReason: string; - - /** - * The number of times the job has failed. - */ - failCount: number; - - /** - * The date/time the job last failed. - */ - failedAt: Date; - } - - /** - * A scheduled job. - */ - interface Job { - - /** - * The database record associated with the job. - */ - attrs: JobAttributes; - - /** - * Specifies an interval on which the job should repeat. - * @param interval A human-readable format String, a cron format String, or a Number. - * @param options An optional argument that can include a timezone field. The timezone should be a string as - * accepted by moment-timezone and is considered when using an interval in the cron string format. - */ - repeatEvery(interval: string | number, options?: { timezone?: string }): Job - - /** - * Specifies a time when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples). - * @param time - */ - repeatAt(time: string): Job - - /** - * Disables the job. - */ - disable(): Job; - - /** - * Enables the job. - */ - enable(): Job; - - /** - * Ensure that only one instance of this job exists with the specified properties - * @param value The properties associated with the job that must be unqiue. - * @param opts - */ - unique(value: any, opts?: { insertOnly?: boolean }): Job; - - /** - * Specifies the next time at which the job should run. - * @param time The next time at which the job should run. - */ - schedule(time: string | Date): Job; - - /** - * Specifies the priority weighting of the job. - * @param value The priority of the job (lowest|low|normal|high|highest|number). - */ - priority(value: string | number): Job; - - /** - * Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason. - * @param reason A message or Error object that indicates why the job failed. - */ - fail(reason: string | Error): Job; - - /** - * Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually - * @param cb Called when the job is completed. - */ - run(cb?: ResultCallback): Job; - - /** - * Returns true if the job is running; otherwise, returns false. - */ - isRunning(): boolean; - - /** - * Saves the job into the database. - * @param cb Called when the job is saved. - */ - save(cb?: ResultCallback): Job; - - /** - * Removes the job from the database and cancels the job. - * @param cb Called after the job has beeb removed from the database. - */ - remove(cb?: Callback): void; - - /** - * Resets the lock on the job. Useful to indicate that the job hasn't timed out when you have very long running - * jobs. - * @param cb Called after the job has been saved to the database. - */ - touch(cb?: Callback): void; - } - - interface JobOptions { - - /** - * Maximum number of that job that can be running at once (per instance of agenda) - */ - concurrency?: number; - - /** - * Maximum number of that job that can be locked at once (per instance of agenda) - */ - lockLimit?: number; - - /** - * Interval in ms of how long the job stays locked for (see multiple job processors for more info). A job will - * automatically unlock if done() is called. - */ - lockLifetime?: number; - - /** - * (lowest|low|normal|high|highest|number) specifies the priority of the job. Higher priority jobs will run - * first. - */ - priority?: string | number; - } - - class Agenda extends EventEmitter { - - /** - * Constructs a new Agenda object. - * @param config Optional configuration to initialize the Agenda. - * @param cb Optional callback called with the MongoDB colleciton. - */ - constructor(config?: AgendaConfiguration, cb?: ResultCallback); - - /** - * Connect to the specified MongoDB server and database. - */ - database(url: string, collection?: string, options?: any, cb?: ResultCallback): Agenda; - - /** - * Initialize agenda with an existing MongoDB connection. - */ - mongo(db: Db, collection?: string, cb?: ResultCallback): Agenda; - - /** - * Sets the agenda name. - */ - name(value: string): Agenda; - - /** - * Sets the interval with which the queue is checked. A number in milliseconds or a frequency string. - */ - processEvery(interval: string | number): Agenda; - - /** - * Takes a number which specifies the max number of jobs that can be running at any given moment. By default it - * is 20. - * @param value The value to set. - */ - maxConcurrency(value: number): Agenda; - - /** - * Takes a number which specifies the default number of a specific job that can be running at any given moment. - * By default it is 5. - * @param value The value to set. - */ - defaultConcurrency(value: number): Agenda; - - /** - * Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is - * 0 for no max. - * @param value The value to set. - */ - lockLimit(value: number): Agenda; - - /** - * Takes a number which specifies the default number of a specific job that can be locked at any given moment. - * By default it is 0 for no max. - * @param value The value to set. - */ - defaultLockLimit(value: number): Agenda; - - /** - * Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This - * can be overridden by specifying the lockLifetime option to a defined job. - * @param value The value to set. - */ - defaultLockLifetime(value: number): Agenda; - - /** - * Returns an instance of a jobName with data. This does NOT save the job in the database. See below to learn - * how to manually work with jobs. - * @param name The name of the job. - * @param data Data to associated with the job. - */ - create(name: string, data?: any): Job; - - /** - * Find all Jobs matching `query` and pass same back in cb(). - * @param query - * @param cb - */ - jobs(query: any, cb: ResultCallback): void; - - /** - * Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want - * to remove old jobs. - * @param cb Called with the number of jobs removed. - */ - purge(cb?: ResultCallback): void; - - /** - * Defines a job with the name of jobName. When a job of job name gets run, it will be passed to fn(job, done). - * To maintain asynchronous behavior, you must call done() when you are processing the job. If your function is - * synchronous, you may omit done from the signature. - * @param name The name of the jobs. - * @param options The options for the job. - * @param handler The handler to execute. - */ - define(name: string, handler: (job?: Job, done?: (err?: Error) => void) => void): void; - define(name: string, options: JobOptions, handler: (job?: Job, done?: (err?: Error) => void) => void): void; - - /** - * Runs job name at the given interval. Optionally, data and options can be passed in. - * @param interval Can be a human-readable format String, a cron format String, or a Number. - * @param names The name or names of the job(s) to run. - * @param data An optional argument that will be passed to the processing function under job.attrs.data. - * @param options An optional argument that will be passed to job.repeatEvery. - * @param cb An optional callback function which will be called when the job has been persisted in the database. - */ - every(interval: number | string, names: string, data?: any, options?: any, cb?: ResultCallback): Job; - every(interval: number | string, names: string[], data?: any, options?: any, cb?: ResultCallback): Job[]; - - /** - * Schedules a job to run name once at a given time. - * @param when A Date or a String such as tomorrow at 5pm. - * @param names The name or names of the job(s) to run. - * @param data An optional argument that will be passed to the processing function under job.attrs.data. - * @param cb An optional callback function which will be called when the job has been persisted in the database. - */ - schedule(when: Date | string, names: string, data?: any, cb?: ResultCallback): Job; - schedule(when: Date | string, names: string[], data?: any, cb?: ResultCallback): Job[]; - - /** - * Schedules a job to run name once immediately. - * @param name The name of the job to run. - * @param data An optional argument that will be passed to the processing function under job.attrs.data. - * @param cb An optional callback function which will be called when the job has been persisted in the database. - */ - now(name: string, data?: any, cb?: ResultCallback): Job; - - /** - * Cancels any jobs matching the passed mongodb-native query, and removes them from the database. - * @param query Mongodb native query. - * @param cb Called with the number of jobs removed. - */ - cancel(query: any, cb?: ResultCallback): void; - - /** - * Starts the job queue processing, checking processEvery time to see if there are new jobs. - */ - start(): void; - - /** - * Stops the job queue processing. Unlocks currently running jobs. - * @param cb Called after the job processing queue shuts down and unlocks all jobs. - */ - stop(cb: Callback): void; - } - - namespace Agenda { - - } - - export = Agenda; +interface Callback { + (err?: Error): void; } + +interface ResultCallback { + (err?: Error, result?: T): void; +} + +/** + * Agenda Configuration. + */ +interface AgendaConfiguration { + + /** + * Sets the interval with which the queue is checked. A number in milliseconds or a frequency string. + */ + processEvery?: string | number; + + /** + * Takes a number which specifies the default number of a specific job that can be running at any given moment. + * By default it is 5. + */ + defaultConcurrency?: number; + + /** + * Takes a number which specifies the max number of jobs that can be running at any given moment. By default it + * is 20. + */ + maxConcurrency?: number; + + /** + * Takes a number which specifies the default number of a specific job that can be locked at any given moment. + * By default it is 0 for no max. + */ + defaultLockLimit?: number; + + /** + * Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is + * 0 for no max. + */ + lockLimit?: number; + + /** + * Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This + * can be overridden by specifying the lockLifetime option to a defined job. + */ + defaultLockLifetime?: number; + + /** + * Specifies that Agenda should be initialized using and existing MongoDB connection. + */ + mongo?: { + /** + * The MongoDB database connection to use. + */ + db: Db; + + /** + * The name of the collection to use. + */ + collection?: string; + } + + /** + * Specifies that Agenda should connect to MongoDB. + */ + db?: { + /** + * The connection URL. + */ + address: string; + + /** + * The name of the collection to use. + */ + collection?: string; + + /** + * Connection options to pass to MongoDB. + */ + options?: any; + } +} + +/** + * The database record associated with a job. + */ +interface JobAttributes { + /** + * The record identity. + */ + _id: ObjectID; + + /** + * The name of the job. + */ + name: string; + + /** + * The type of the job (single|normal). + */ + type: string; + + /** + * The job details. + */ + data: { [name: string]: any }; + + /** + * The priority of the job. + */ + priority: number; + + /** + * How often the job is repeated using a human-readable or cron format. + */ + repeatInterval: string | number; + + /** + * The timezone that conforms to [moment-timezone](http://momentjs.com/timezone/). + */ + repeatTimezone: string; + + /** + * Date/time the job was las modified. + */ + lastModifiedBy: string; + + /** + * Date/time the job will run next. + */ + nextRunAt: Date; + + /** + * Date/time the job was locked. + */ + lockedAt: Date; + + /** + * Date/time the job was last run. + */ + lastRunAt: Date; + + /** + * Date/time the job last finished running. + */ + lastFinishedAt: Date; + + /** + * The reason the job failed. + */ + failReason: string; + + /** + * The number of times the job has failed. + */ + failCount: number; + + /** + * The date/time the job last failed. + */ + failedAt: Date; +} + +/** + * A scheduled job. + */ +interface Job { + + /** + * The database record associated with the job. + */ + attrs: JobAttributes; + + /** + * Specifies an interval on which the job should repeat. + * @param interval A human-readable format String, a cron format String, or a Number. + * @param options An optional argument that can include a timezone field. The timezone should be a string as + * accepted by moment-timezone and is considered when using an interval in the cron string format. + */ + repeatEvery(interval: string | number, options?: { timezone?: string }): Job + + /** + * Specifies a time when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples). + * @param time + */ + repeatAt(time: string): Job + + /** + * Disables the job. + */ + disable(): Job; + + /** + * Enables the job. + */ + enable(): Job; + + /** + * Ensure that only one instance of this job exists with the specified properties + * @param value The properties associated with the job that must be unqiue. + * @param opts + */ + unique(value: any, opts?: { insertOnly?: boolean }): Job; + + /** + * Specifies the next time at which the job should run. + * @param time The next time at which the job should run. + */ + schedule(time: string | Date): Job; + + /** + * Specifies the priority weighting of the job. + * @param value The priority of the job (lowest|low|normal|high|highest|number). + */ + priority(value: string | number): Job; + + /** + * Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason. + * @param reason A message or Error object that indicates why the job failed. + */ + fail(reason: string | Error): Job; + + /** + * Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually + * @param cb Called when the job is completed. + */ + run(cb?: ResultCallback): Job; + + /** + * Returns true if the job is running; otherwise, returns false. + */ + isRunning(): boolean; + + /** + * Saves the job into the database. + * @param cb Called when the job is saved. + */ + save(cb?: ResultCallback): Job; + + /** + * Removes the job from the database and cancels the job. + * @param cb Called after the job has beeb removed from the database. + */ + remove(cb?: Callback): void; + + /** + * Resets the lock on the job. Useful to indicate that the job hasn't timed out when you have very long running + * jobs. + * @param cb Called after the job has been saved to the database. + */ + touch(cb?: Callback): void; +} + +interface JobOptions { + + /** + * Maximum number of that job that can be running at once (per instance of agenda) + */ + concurrency?: number; + + /** + * Maximum number of that job that can be locked at once (per instance of agenda) + */ + lockLimit?: number; + + /** + * Interval in ms of how long the job stays locked for (see multiple job processors for more info). A job will + * automatically unlock if done() is called. + */ + lockLifetime?: number; + + /** + * (lowest|low|normal|high|highest|number) specifies the priority of the job. Higher priority jobs will run + * first. + */ + priority?: string | number; +} + +declare class Agenda extends EventEmitter { + + /** + * Constructs a new Agenda object. + * @param config Optional configuration to initialize the Agenda. + * @param cb Optional callback called with the MongoDB colleciton. + */ + constructor(config?: AgendaConfiguration, cb?: ResultCallback); + + /** + * Connect to the specified MongoDB server and database. + */ + database(url: string, collection?: string, options?: any, cb?: ResultCallback): Agenda; + + /** + * Initialize agenda with an existing MongoDB connection. + */ + mongo(db: Db, collection?: string, cb?: ResultCallback): Agenda; + + /** + * Sets the agenda name. + */ + name(value: string): Agenda; + + /** + * Sets the interval with which the queue is checked. A number in milliseconds or a frequency string. + */ + processEvery(interval: string | number): Agenda; + + /** + * Takes a number which specifies the max number of jobs that can be running at any given moment. By default it + * is 20. + * @param value The value to set. + */ + maxConcurrency(value: number): Agenda; + + /** + * Takes a number which specifies the default number of a specific job that can be running at any given moment. + * By default it is 5. + * @param value The value to set. + */ + defaultConcurrency(value: number): Agenda; + + /** + * Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is + * 0 for no max. + * @param value The value to set. + */ + lockLimit(value: number): Agenda; + + /** + * Takes a number which specifies the default number of a specific job that can be locked at any given moment. + * By default it is 0 for no max. + * @param value The value to set. + */ + defaultLockLimit(value: number): Agenda; + + /** + * Takes a number which specifies the default lock lifetime in milliseconds. By default it is 10 minutes. This + * can be overridden by specifying the lockLifetime option to a defined job. + * @param value The value to set. + */ + defaultLockLifetime(value: number): Agenda; + + /** + * Returns an instance of a jobName with data. This does NOT save the job in the database. See below to learn + * how to manually work with jobs. + * @param name The name of the job. + * @param data Data to associated with the job. + */ + create(name: string, data?: any): Job; + + /** + * Find all Jobs matching `query` and pass same back in cb(). + * @param query + * @param cb + */ + jobs(query: any, cb: ResultCallback): void; + + /** + * Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want + * to remove old jobs. + * @param cb Called with the number of jobs removed. + */ + purge(cb?: ResultCallback): void; + + /** + * Defines a job with the name of jobName. When a job of job name gets run, it will be passed to fn(job, done). + * To maintain asynchronous behavior, you must call done() when you are processing the job. If your function is + * synchronous, you may omit done from the signature. + * @param name The name of the jobs. + * @param options The options for the job. + * @param handler The handler to execute. + */ + define(name: string, handler: (job?: Job, done?: (err?: Error) => void) => void): void; + define(name: string, options: JobOptions, handler: (job?: Job, done?: (err?: Error) => void) => void): void; + + /** + * Runs job name at the given interval. Optionally, data and options can be passed in. + * @param interval Can be a human-readable format String, a cron format String, or a Number. + * @param names The name or names of the job(s) to run. + * @param data An optional argument that will be passed to the processing function under job.attrs.data. + * @param options An optional argument that will be passed to job.repeatEvery. + * @param cb An optional callback function which will be called when the job has been persisted in the database. + */ + every(interval: number | string, names: string, data?: any, options?: any, cb?: ResultCallback): Job; + every(interval: number | string, names: string[], data?: any, options?: any, cb?: ResultCallback): Job[]; + + /** + * Schedules a job to run name once at a given time. + * @param when A Date or a String such as tomorrow at 5pm. + * @param names The name or names of the job(s) to run. + * @param data An optional argument that will be passed to the processing function under job.attrs.data. + * @param cb An optional callback function which will be called when the job has been persisted in the database. + */ + schedule(when: Date | string, names: string, data?: any, cb?: ResultCallback): Job; + schedule(when: Date | string, names: string[], data?: any, cb?: ResultCallback): Job[]; + + /** + * Schedules a job to run name once immediately. + * @param name The name of the job to run. + * @param data An optional argument that will be passed to the processing function under job.attrs.data. + * @param cb An optional callback function which will be called when the job has been persisted in the database. + */ + now(name: string, data?: any, cb?: ResultCallback): Job; + + /** + * Cancels any jobs matching the passed mongodb-native query, and removes them from the database. + * @param query Mongodb native query. + * @param cb Called with the number of jobs removed. + */ + cancel(query: any, cb?: ResultCallback): void; + + /** + * Starts the job queue processing, checking processEvery time to see if there are new jobs. + */ + start(): void; + + /** + * Stops the job queue processing. Unlocks currently running jobs. + * @param cb Called after the job processing queue shuts down and unlocks all jobs. + */ + stop(cb: Callback): void; +} + +declare namespace Agenda { + +} + +export = Agenda; diff --git a/amazon-product-api/amazon-product-api.d.ts b/amazon-product-api/amazon-product-api.d.ts index f7ccf905e5..9b5604ff5b 100644 --- a/amazon-product-api/amazon-product-api.d.ts +++ b/amazon-product-api/amazon-product-api.d.ts @@ -3,23 +3,22 @@ // Definitions by: Matti Lehtinen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "amazon-product-api" { - interface ICredentials { - awsId: string, - awsSecret: string, - awsTag: string - } - interface IAmazonProductQueryCallback { - (err: string, results: Object[]): void; - } - - interface IAmazonProductClient { - itemSearch(query: any, callback?: IAmazonProductQueryCallback) : Promise; - itemLookup(query: any, callback?: IAmazonProductQueryCallback) : Promise; - browseNodeLookup(query: any, callback?: IAmazonProductQueryCallback) : Promise; - } - - export function createClient(credentials:ICredentials) : IAmazonProductClient; +interface ICredentials { + awsId: string, + awsSecret: string, + awsTag: string } + +interface IAmazonProductQueryCallback { + (err: string, results: Object[]): void; +} + +interface IAmazonProductClient { + itemSearch(query: any, callback?: IAmazonProductQueryCallback): Promise; + itemLookup(query: any, callback?: IAmazonProductQueryCallback): Promise; + browseNodeLookup(query: any, callback?: IAmazonProductQueryCallback): Promise; +} + +declare export function createClient(credentials: ICredentials): IAmazonProductClient; diff --git a/amqp-rpc/amqp-rpc.d.ts b/amqp-rpc/amqp-rpc.d.ts index b2eee1d2ca..49760498f0 100644 --- a/amqp-rpc/amqp-rpc.d.ts +++ b/amqp-rpc/amqp-rpc.d.ts @@ -5,60 +5,60 @@ /// -declare module "amqp-rpc" { - export interface Options { + +export interface Options { connection?: any; url?: string; exchangeInstance?: any; exchange?: string; exchange_options?: { - exclusive?: boolean; - autoDelete?: boolean; + exclusive?: boolean; + autoDelete?: boolean; }; ipml_options?: { - defaultExchangeName?: string; + defaultExchangeName?: string; } conn_options?: any; - } +} - export interface CallOptions { +export interface CallOptions { correlationId?: string; autoDeleteCallback?: any; - } +} - export interface HandlerOptions { +export interface HandlerOptions { queueName?: string; durable?: boolean; exclusive?: boolean; autoDelete?: boolean; - } +} - export interface BroadcastOptions { +export interface BroadcastOptions { ttl?: number; onResponse?: any; context?: any; onComplete?: any; - } +} - export interface CommandInfo { +export interface CommandInfo { cmd?: string; exchange?: string; contentType?: string; size?: number; - } +} - export interface Callback { +export interface Callback { (...args: any[]): void; - } +} - export interface CallbackWithError { +export interface CallbackWithError { (err: any, ...args: any[]): void; - } +} - export function factory(opt?: Options): amqpRPC; +declare export function factory(opt?: Options): amqpRPC; - export class amqpRPC { +declare export class amqpRPC { constructor(opt?: Options); generateQueueName(type: string): string; disconnect(): void; @@ -68,5 +68,4 @@ declare module "amqp-rpc" { callBroadcast(cmd: string, params: T, options?: BroadcastOptions): void; onBroadcast(cmd: string, cb?: (params?: T, cb?: CallbackWithError) => void, context?: any, options?: any): boolean; offBroadcast(cmd: string): boolean; - } } diff --git a/ansi-styles/ansi-styles.d.ts b/ansi-styles/ansi-styles.d.ts index e5c01c6a5a..2d853a0c49 100644 --- a/ansi-styles/ansi-styles.d.ts +++ b/ansi-styles/ansi-styles.d.ts @@ -4,39 +4,37 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "ansi-styles" -{ - export interface EscapeCodePair { - open: string; - close: string; - } - export var reset: EscapeCodePair; +export interface EscapeCodePair { + open: string; + close: string; +} - export var bold: EscapeCodePair; - export var dim: EscapeCodePair; - export var italic: EscapeCodePair; - export var underline: EscapeCodePair; - export var inverse: EscapeCodePair; - export var hidden: EscapeCodePair; - export var strikethrough: EscapeCodePair; +declare export var reset: EscapeCodePair; - export var black: EscapeCodePair; - export var red: EscapeCodePair; - export var green: EscapeCodePair; - export var yellow: EscapeCodePair; - export var blue: EscapeCodePair; - export var magenta: EscapeCodePair; - export var cyan: EscapeCodePair; - export var white: EscapeCodePair; - export var gray: EscapeCodePair; +declare export var bold: EscapeCodePair; +declare export var dim: EscapeCodePair; +declare export var italic: EscapeCodePair; +declare export var underline: EscapeCodePair; +declare export var inverse: EscapeCodePair; +declare export var hidden: EscapeCodePair; +declare export var strikethrough: EscapeCodePair; - export var bgBlack: EscapeCodePair; - export var bgRed: EscapeCodePair; - export var bgGreen: EscapeCodePair; - export var bgYellow: EscapeCodePair; - export var bgBlue: EscapeCodePair; - export var bgMagenta: EscapeCodePair; - export var bgCyan: EscapeCodePair; - export var bgWhite: EscapeCodePair; -} \ No newline at end of file +declare export var black: EscapeCodePair; +declare export var red: EscapeCodePair; +declare export var green: EscapeCodePair; +declare export var yellow: EscapeCodePair; +declare export var blue: EscapeCodePair; +declare export var magenta: EscapeCodePair; +declare export var cyan: EscapeCodePair; +declare export var white: EscapeCodePair; +declare export var gray: EscapeCodePair; + +declare export var bgBlack: EscapeCodePair; +declare export var bgRed: EscapeCodePair; +declare export var bgGreen: EscapeCodePair; +declare export var bgYellow: EscapeCodePair; +declare export var bgBlue: EscapeCodePair; +declare export var bgMagenta: EscapeCodePair; +declare export var bgCyan: EscapeCodePair; +declare export var bgWhite: EscapeCodePair; diff --git a/ansicolors/ansicolors.d.ts b/ansicolors/ansicolors.d.ts index 2bbfcafc6e..6750283895 100644 --- a/ansicolors/ansicolors.d.ts +++ b/ansicolors/ansicolors.d.ts @@ -3,7 +3,6 @@ // Definitions by: rogierschouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "ansicolors" { - var colors: {[index: string]: (s: string) => string;}; - export = colors; -} + +declare var colors: { [index: string]: (s: string) => string; }; +export = colors; diff --git a/any-db-transaction/any-db-transaction.d.ts b/any-db-transaction/any-db-transaction.d.ts index 675f18e9cc..0a94e7a634 100644 --- a/any-db-transaction/any-db-transaction.d.ts +++ b/any-db-transaction/any-db-transaction.d.ts @@ -6,89 +6,85 @@ /// /// -declare module "any-db-transaction" { - import anyDB = require("any-db"); - namespace begin { - /** - * Transaction objects are are simple wrappers around a Connection that also implement the Queryable API, - * but guarantee that all queries take place within a single database transaction or not at all. Note that - * begin also understands how to acquire (and release) a connection from a ConnectionPool as well, so you - * can simply pass a pool to it: var tx = begin(pool) - * - * By default, any queries that error during a transaction will cause an automatic rollback. If a query has - * no callback, the transaction will also handle (and re-emit) 'error' events for the Query instance. - * This enables handling errors for an entire transaction in a single place. - * - * Transactions may also be nested by passing a Transaction to begin and these nested transactions can - * safely error and rollback without rolling back their parent transaction - * - * Transaction events: - * 'query', query - emitted immediately after .query is called on a connection via tx.query. The argument is a query object. - * 'commit:start' - Emitted when .commit() is called. - * 'commit:complete' - Emitted after the transaction has committed. - * 'rollback:start' - Emitted when .rollback() is called. - * 'rollback:complete' - Emitted after the transaction has rolled back. - * 'close' - Emitted after rollback or commit completes. - * 'error', err - Emitted under three conditions: - * There was an error acquiring a connection. - * Any query performed in this transaction emits an error that would otherwise go unhandled. - * Any of query, begin, commit, or rollback are called after the connection has already been committed or rolled back. - * Note that the 'error' event may be emitted multiple times! depending on the callback you are registering, you way want to wrap it using [once][]. - */ - interface Transaction extends anyDB.Queryable { +import anyDB = require("any-db"); - /** - * Issue a COMMIT (or RELEASE ... in the case of nested transactions) statement to the database. - * If a continuation is provided it will be called (possibly with an error) after the COMMIT - * statement completes. The transaction object itself will be unusable after calling commit(). - */ - commit(callback?: (error: Error) => void): void; +declare namespace begin { + /** + * Transaction objects are are simple wrappers around a Connection that also implement the Queryable API, + * but guarantee that all queries take place within a single database transaction or not at all. Note that + * begin also understands how to acquire (and release) a connection from a ConnectionPool as well, so you + * can simply pass a pool to it: var tx = begin(pool) + * + * By default, any queries that error during a transaction will cause an automatic rollback. If a query has + * no callback, the transaction will also handle (and re-emit) 'error' events for the Query instance. + * This enables handling errors for an entire transaction in a single place. + * + * Transactions may also be nested by passing a Transaction to begin and these nested transactions can + * safely error and rollback without rolling back their parent transaction + * + * Transaction events: + * 'query', query - emitted immediately after .query is called on a connection via tx.query. The argument is a query object. + * 'commit:start' - Emitted when .commit() is called. + * 'commit:complete' - Emitted after the transaction has committed. + * 'rollback:start' - Emitted when .rollback() is called. + * 'rollback:complete' - Emitted after the transaction has rolled back. + * 'close' - Emitted after rollback or commit completes. + * 'error', err - Emitted under three conditions: + * There was an error acquiring a connection. + * Any query performed in this transaction emits an error that would otherwise go unhandled. + * Any of query, begin, commit, or rollback are called after the connection has already been committed or rolled back. + * Note that the 'error' event may be emitted multiple times! depending on the callback you are registering, you way want to wrap it using [once][]. + */ + interface Transaction extends anyDB.Queryable { - /** - * The same as Transaction.commit but issues a ROLLBACK. Again, the transaction will be unusable after calling this method. - */ - rollback(callback?: (error: Error) => void): void; - } + /** + * Issue a COMMIT (or RELEASE ... in the case of nested transactions) statement to the database. + * If a continuation is provided it will be called (possibly with an error) after the COMMIT + * statement completes. The transaction object itself will be unusable after calling commit(). + */ + commit(callback?: (error: Error) => void): void; - interface TransactionOptions { - /** - * Adapter name e.g. 'mysql' - */ - adapter?: anyDB.Adapter; - /** - * SQL statement for beginning a transaction, default 'BEGIN' - */ - begin?: string; - /** - * SQL statement for committing a transaction, default 'COMMIT' - */ - commit?: string; - /** - * SQL statement for rolling back a transaction, default 'ROLLBACK' - */ - rollback?: string; - /** - * Callback for transaction - */ - callback?: (error: Error, transaction: Transaction) => void; - /** - * Rollback automatically on error, default true - */ - autoRollback?: boolean; - } - } + /** + * The same as Transaction.commit but issues a ROLLBACK. Again, the transaction will be unusable after calling this method. + */ + rollback(callback?: (error: Error) => void): void; + } - /** - * Start a transaction - */ - function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - function begin(q: anyDB.Queryable, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - function begin(q: anyDB.Queryable, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - - export = begin; + interface TransactionOptions { + /** + * Adapter name e.g. 'mysql' + */ + adapter?: anyDB.Adapter; + /** + * SQL statement for beginning a transaction, default 'BEGIN' + */ + begin?: string; + /** + * SQL statement for committing a transaction, default 'COMMIT' + */ + commit?: string; + /** + * SQL statement for rolling back a transaction, default 'ROLLBACK' + */ + rollback?: string; + /** + * Callback for transaction + */ + callback?: (error: Error, transaction: Transaction) => void; + /** + * Rollback automatically on error, default true + */ + autoRollback?: boolean; + } } +/** + * Start a transaction + */ +declare function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; +declare function begin(q: anyDB.Queryable, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; +declare function begin(q: anyDB.Queryable, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; +declare function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction; - +export = begin; diff --git a/any-db/any-db.d.ts b/any-db/any-db.d.ts index 8a64b6f323..5d6f665f57 100644 --- a/any-db/any-db.d.ts +++ b/any-db/any-db.d.ts @@ -5,299 +5,297 @@ /// -declare module "any-db" { - import events = require("events"); - import stream = require("stream"); - export interface ConnectOpts { - adapter: string; - } - - export interface Adapter { - name: string; - /** - * Create a new connection object. In common usage, config will be created by parse-db-url and passed to the adapter by any-db. - * If a continuation is given, it must be called, either with an error or the established connection. - */ - createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection; - - /** - * Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code, - * it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract - * by synchronously returning a Query stream - */ - createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query; - createQuery(query: Query): Query; - } - /** - * Other properties are driver specific - */ - export interface Field { - name: string; - } - - /** - * ResultSet objects are just plain data that collect results of a query when a continuation - * is provided to Queryable.query. The lastInsertId is optional, and currently supported by - * sqlite3 and mysql but not postgres, because it is not supported by Postgres itself. - */ - export interface ResultSet { - /** - * Affected rows. Note e.g. for INSERT queries the rows property is not filled even - * though rowCount is non-zero. - */ - rowCount: number; - /** - * Result rows - */ - rows: any[]; - /** - * Result field descriptions - */ - fields: Field[]; - - /** - * Not supported by all drivers. - */ - fieldCount?: number; - /** - * Not supported by all drivers. - */ - lastInsertId?: any; - /** - * Not supported by all drivers. - */ - affectedRows?: number; - /** - * Not supported by all drivers. - */ - changedRows?: number; - } - - /** - * Query objects are returned by the Queryable.query method, available on connections, - * pools, and transactions. Queries are instances of Readable, and as such can be piped - * through transforms and support backpressure for more efficient memory-usage on very - * large results sets. (Note: at this time the sqlite3 driver does not support backpressure) - * - * Internally, Query instances are created by a database Adapter and may have more methods, - * properties, and events than are described here. Consult the documentation for your - * specific adapter to find out about any extensions. - * - * Events: - * - * Error event - * The 'error' event is emitted at most once per query. Note that this event will be - * emitted for errors even if a callback was provided, the callback will - * simply be subscribed to the 'error' event. - * One argument is passed to event listeners: - * error - the error object. - * - * Fields event - * A 'fields' event is emmitted before any 'data' events. - * One argument is passed to event listeners: - * fields - an array of [Field][ResultSet] objects. - * - * The following events are part of the stream.Readable interface which is implemented by Query: - * - * Data event - * A 'data' event is emitted for each row in the query result set. - * One argument is passed to event listeners: - * row contains the contents of a single row in the query result - * - * Close event - * A 'close' event is emitted when the query completes. - * No arguments are passed to event listeners. - * - * End event - * An 'end' event is emitted after all query results have been consumed. - * No arguments are passed to event listeners. - */ - export interface Query extends stream.Readable { - /** - * The SQL query as a string. If you are using MySQL this will contain - * interpolated values after the query has been enqueued by a connection. - */ - text: string; - - /** - * The array of parameter values. - */ - values: any[]; - - /** - * The callback (if any) that was provided to Queryable.query. Note that - * Query objects must not use a closed over reference to their callback, - * as other any-db libraries may rely on modifying the callback property - * of a Query they did not create. - */ - callback: (error: Error, results: ResultSet) => void; - } - - /** - * Events: - * The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers: - * - query: a Query object - */ - export interface Queryable extends events.EventEmitter { - /** - * The Adapter instance that will be used by this Queryable for creating Query instances and/or connections. - */ - adapter: Adapter; - - /** - * Execute a SQL statement using bound parameters (if they are provided) and return a Query object - * that is a Readable stream of the resulting rows. If a Continuation is provided the rows - * returned by the database will be aggregated into a [ResultSet][] which will be passed to the - * continuation after the query has completed. - * The second form is not needed for normal use, but must be implemented by adapters to work correctly - * with ConnectionPool and Transaction. See Adapter.createQuery for more details. - */ - query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query - - /** - * The second form is not needed for normal use, but must be implemented by adapters to work correctly - * with ConnectionPool and Transaction. See Adapter.createQuery for more details. - */ - // query(query: Query): Query; - } - - /** - * Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire, - * both of which delegate to the createConnection implementation of the specified adapter. - * While all Connection objects implement the Queryable interface, the implementations in - * each adapter may add additional methods or emit additional events. If you need to access a - * feature of your database that is not described here (such as Postgres' server-side prepared - * statements), consult the documentation for your adapter. - * - * Events: - * Error event - * The 'error' event is emitted when there is a connection-level error. - * No arguments are passed to event listeners. - * - * Open event - * The 'open' event is emitted when the connection has been established and is ready to query. - * No arguments are passed to event listeners. - * - * Close event - * The 'close' event is emitted when the connection has been closed. - * No arguments are passed to event listeners. - */ - export interface Connection extends Queryable { - /** - * Close the database connection. If a continuation is provided it - * will be called after the connection has closed. - */ - end(callback?: (error: Error) => void): void; - } - - export interface ConnectionStatic { - new(): Connection; - - name: string; - createConnection(): void; - createPool(): void; - } - - /** - * ConnectionPool events - * 'acquire' - emitted whenever pool.acquire is called - * 'release' - emitted whenever pool.release is called - * 'query', query - emitted immediately after .query is called on a - * connection via pool.query. The argument is a Query object. - * 'close' - emitted when the connection pool has closed all of it - * connections after a call to close(). - */ - export interface ConnectionPool extends Queryable { - /** - * Implements Queryable.query by automatically acquiring a connection - * and releasing it when the query completes. - */ - query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query; - - /** - * Remove a connection from the pool. If you use this method you must - * return the connection back to the pool using ConnectionPool.release - */ - acquire(callback: (error: Error, result: Connection) => void): void; - - /** - * Return a connection to the pool. This should only be called with connections - * you've manually acquired. You must not continue to use the connection after releasing it. - */ - release(connection: Connection): void; - - /** - * Stop giving out new connections, and close all existing database connections as they - * are returned to the pool. - */ - close(callback?: (error: Error) => void): void; - } - - /** - * A PoolConfig is generally a plain object with any of the following properties (they are all optional): - */ - export interface PoolConfig { - /** - * min (default 0) The minimum number of connections to keep open in the pool. - */ - min?: number; - /** - * max (default 10) The maximum number of connections to keep open in the pool. - * When this limit is reached further requests for connections will queue waiting - * for an existing connection to be released back into the pool. - */ - max?: number; - /** - * (default 30000) The maximum amount of time a connection can sit idle in the pool before being reaped - */ - idleTimeout?: number; - /** - * (default 1000) How frequently the pool should check for connections that are old enough to be reaped. - */ - reapInterval?: number; - /** - * (default true) When this is true, the pool will reap connections that - * have been idle for more than idleTimeout milliseconds. - */ - refreshIdle?: boolean; - /** - * Called immediately after a connection is first established. Use this to do one-time setup of new connections. - * The supplied Connection will not be added to the pool until you pass it to the done continuation. - */ - onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void; - /** - * Called each time a connection is returned to the pool. Use this to restore a connection to - * it's original state (e.g. rollback transactions, set the database session vars). If reset - * fails to call the done continuation the connection will be lost in limbo. - */ - reset?: (connection: Connection, done: (error: Error) => void) => void; - /** - * (default function (err) { return true }) - Called when an error is encountered - * by pool.query or emitted by an idle connection. If shouldDestroyConnection(error) - * is truthy the connection will be destroyed, otherwise it will be reset. - */ - shouldDestroyConnection?: (error: Error) => boolean; - } - - /** - * Create a database connection. - * @param url String of the form adapter://user:password@host/database - * @param callback - * @returns Connection object. - */ - export function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection; - - /** - * Create a database connection. - * @param opts Object with adapter name and any properties that the given adapter requires - * @param callback - * @returns Connection object. - */ - export function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection; - - - export function createPool(url: string, config: PoolConfig): ConnectionPool; - export function createPool(opts: ConnectOpts, config: PoolConfig): ConnectionPool; +import events = require("events"); +import stream = require("stream"); +export interface ConnectOpts { + adapter: string; } + +export interface Adapter { + name: string; + /** + * Create a new connection object. In common usage, config will be created by parse-db-url and passed to the adapter by any-db. + * If a continuation is given, it must be called, either with an error or the established connection. + */ + createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection; + + /** + * Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code, + * it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract + * by synchronously returning a Query stream + */ + createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query; + createQuery(query: Query): Query; +} +/** + * Other properties are driver specific + */ +export interface Field { + name: string; +} + +/** + * ResultSet objects are just plain data that collect results of a query when a continuation + * is provided to Queryable.query. The lastInsertId is optional, and currently supported by + * sqlite3 and mysql but not postgres, because it is not supported by Postgres itself. + */ +export interface ResultSet { + /** + * Affected rows. Note e.g. for INSERT queries the rows property is not filled even + * though rowCount is non-zero. + */ + rowCount: number; + /** + * Result rows + */ + rows: any[]; + /** + * Result field descriptions + */ + fields: Field[]; + + /** + * Not supported by all drivers. + */ + fieldCount?: number; + /** + * Not supported by all drivers. + */ + lastInsertId?: any; + /** + * Not supported by all drivers. + */ + affectedRows?: number; + /** + * Not supported by all drivers. + */ + changedRows?: number; +} + +/** + * Query objects are returned by the Queryable.query method, available on connections, + * pools, and transactions. Queries are instances of Readable, and as such can be piped + * through transforms and support backpressure for more efficient memory-usage on very + * large results sets. (Note: at this time the sqlite3 driver does not support backpressure) + * + * Internally, Query instances are created by a database Adapter and may have more methods, + * properties, and events than are described here. Consult the documentation for your + * specific adapter to find out about any extensions. + * + * Events: + * + * Error event + * The 'error' event is emitted at most once per query. Note that this event will be + * emitted for errors even if a callback was provided, the callback will + * simply be subscribed to the 'error' event. + * One argument is passed to event listeners: + * error - the error object. + * + * Fields event + * A 'fields' event is emmitted before any 'data' events. + * One argument is passed to event listeners: + * fields - an array of [Field][ResultSet] objects. + * + * The following events are part of the stream.Readable interface which is implemented by Query: + * + * Data event + * A 'data' event is emitted for each row in the query result set. + * One argument is passed to event listeners: + * row contains the contents of a single row in the query result + * + * Close event + * A 'close' event is emitted when the query completes. + * No arguments are passed to event listeners. + * + * End event + * An 'end' event is emitted after all query results have been consumed. + * No arguments are passed to event listeners. + */ +export interface Query extends stream.Readable { + /** + * The SQL query as a string. If you are using MySQL this will contain + * interpolated values after the query has been enqueued by a connection. + */ + text: string; + + /** + * The array of parameter values. + */ + values: any[]; + + /** + * The callback (if any) that was provided to Queryable.query. Note that + * Query objects must not use a closed over reference to their callback, + * as other any-db libraries may rely on modifying the callback property + * of a Query they did not create. + */ + callback: (error: Error, results: ResultSet) => void; +} + +/** + * Events: + * The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers: + * - query: a Query object + */ +export interface Queryable extends events.EventEmitter { + /** + * The Adapter instance that will be used by this Queryable for creating Query instances and/or connections. + */ + adapter: Adapter; + + /** + * Execute a SQL statement using bound parameters (if they are provided) and return a Query object + * that is a Readable stream of the resulting rows. If a Continuation is provided the rows + * returned by the database will be aggregated into a [ResultSet][] which will be passed to the + * continuation after the query has completed. + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + */ + query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query + + /** + * The second form is not needed for normal use, but must be implemented by adapters to work correctly + * with ConnectionPool and Transaction. See Adapter.createQuery for more details. + */ + // query(query: Query): Query; +} + +/** + * Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire, + * both of which delegate to the createConnection implementation of the specified adapter. + * While all Connection objects implement the Queryable interface, the implementations in + * each adapter may add additional methods or emit additional events. If you need to access a + * feature of your database that is not described here (such as Postgres' server-side prepared + * statements), consult the documentation for your adapter. + * + * Events: + * Error event + * The 'error' event is emitted when there is a connection-level error. + * No arguments are passed to event listeners. + * + * Open event + * The 'open' event is emitted when the connection has been established and is ready to query. + * No arguments are passed to event listeners. + * + * Close event + * The 'close' event is emitted when the connection has been closed. + * No arguments are passed to event listeners. + */ +export interface Connection extends Queryable { + /** + * Close the database connection. If a continuation is provided it + * will be called after the connection has closed. + */ + end(callback?: (error: Error) => void): void; +} + +export interface ConnectionStatic { + new (): Connection; + + name: string; + createConnection(): void; + createPool(): void; +} + +/** + * ConnectionPool events + * 'acquire' - emitted whenever pool.acquire is called + * 'release' - emitted whenever pool.release is called + * 'query', query - emitted immediately after .query is called on a + * connection via pool.query. The argument is a Query object. + * 'close' - emitted when the connection pool has closed all of it + * connections after a call to close(). + */ +export interface ConnectionPool extends Queryable { + /** + * Implements Queryable.query by automatically acquiring a connection + * and releasing it when the query completes. + */ + query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query; + + /** + * Remove a connection from the pool. If you use this method you must + * return the connection back to the pool using ConnectionPool.release + */ + acquire(callback: (error: Error, result: Connection) => void): void; + + /** + * Return a connection to the pool. This should only be called with connections + * you've manually acquired. You must not continue to use the connection after releasing it. + */ + release(connection: Connection): void; + + /** + * Stop giving out new connections, and close all existing database connections as they + * are returned to the pool. + */ + close(callback?: (error: Error) => void): void; +} + +/** + * A PoolConfig is generally a plain object with any of the following properties (they are all optional): + */ +export interface PoolConfig { + /** + * min (default 0) The minimum number of connections to keep open in the pool. + */ + min?: number; + /** + * max (default 10) The maximum number of connections to keep open in the pool. + * When this limit is reached further requests for connections will queue waiting + * for an existing connection to be released back into the pool. + */ + max?: number; + /** + * (default 30000) The maximum amount of time a connection can sit idle in the pool before being reaped + */ + idleTimeout?: number; + /** + * (default 1000) How frequently the pool should check for connections that are old enough to be reaped. + */ + reapInterval?: number; + /** + * (default true) When this is true, the pool will reap connections that + * have been idle for more than idleTimeout milliseconds. + */ + refreshIdle?: boolean; + /** + * Called immediately after a connection is first established. Use this to do one-time setup of new connections. + * The supplied Connection will not be added to the pool until you pass it to the done continuation. + */ + onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void; + /** + * Called each time a connection is returned to the pool. Use this to restore a connection to + * it's original state (e.g. rollback transactions, set the database session vars). If reset + * fails to call the done continuation the connection will be lost in limbo. + */ + reset?: (connection: Connection, done: (error: Error) => void) => void; + /** + * (default function (err) { return true }) - Called when an error is encountered + * by pool.query or emitted by an idle connection. If shouldDestroyConnection(error) + * is truthy the connection will be destroyed, otherwise it will be reset. + */ + shouldDestroyConnection?: (error: Error) => boolean; +} + +/** + * Create a database connection. + * @param url String of the form adapter://user:password@host/database + * @param callback + * @returns Connection object. + */ +declare export function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection; + +/** + * Create a database connection. + * @param opts Object with adapter name and any properties that the given adapter requires + * @param callback + * @returns Connection object. + */ +declare export function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection; + + +declare export function createPool(url: string, config: PoolConfig): ConnectionPool; +declare export function createPool(opts: ConnectOpts, config: PoolConfig): ConnectionPool; diff --git a/anydb-sql-migrations/anydb-sql-migrations.d.ts b/anydb-sql-migrations/anydb-sql-migrations.d.ts index 9ab421c3ac..a6f3f36be0 100644 --- a/anydb-sql-migrations/anydb-sql-migrations.d.ts +++ b/anydb-sql-migrations/anydb-sql-migrations.d.ts @@ -6,29 +6,28 @@ /// /// -declare module "anydb-sql-migrations" { - import Promise = require('bluebird'); - import { Column, Table, Transaction, AnydbSql } from 'anydb-sql'; - export interface Migration { - version: string; - } - export interface MigrationsTable extends Table { - version: Column; - } - export interface MigFn { - (tx: Transaction): Promise; - } - export interface MigrationTask { - up: MigFn; - down: MigFn; - name: string; - } - export function create(db: AnydbSql, tasks: any): { - run: () => Promise; - migrateTo: (target?: string) => Promise; - check: (f: (m: { - type: string; - items: MigrationTask[]; - }) => any) => Promise; - }; -} \ No newline at end of file + +import Promise = require('bluebird'); +import { Column, Table, Transaction, AnydbSql } from 'anydb-sql'; +export interface Migration { + version: string; +} +export interface MigrationsTable extends Table { + version: Column; +} +export interface MigFn { + (tx: Transaction): Promise; +} +export interface MigrationTask { + up: MigFn; + down: MigFn; + name: string; +} +declare export function create(db: AnydbSql, tasks: any): { + run: () => Promise; + migrateTo: (target?: string) => Promise; + check: (f: (m: { + type: string; + items: MigrationTask[]; + }) => any) => Promise; +}; diff --git a/anydb-sql/anydb-sql.d.ts b/anydb-sql/anydb-sql.d.ts index 6b5f0b2cd6..367ade6ff9 100644 --- a/anydb-sql/anydb-sql.d.ts +++ b/anydb-sql/anydb-sql.d.ts @@ -3,188 +3,191 @@ // Definitions by: Gorgi Kosev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "anydb-sql" { - interface AnyDBPool extends anydbSQL.DatabaseConnection { - query:(text:string, values:any[], callback:(err:Error, result:any)=>void)=>void - begin:()=>anydbSQL.Transaction - close:(err:Error)=>void - } - interface Dictionary { [key:string]:T; } - - namespace anydbSQL { - export interface OrderByValueNode {} - export interface ColumnDefinition { - primaryKey?:boolean; - dataType?:string; - references?: {table:string; column: string} - notNull?:boolean - } - - export interface TableDefinition { - name:string - columns:Dictionary - has?:Dictionary<{from:string; many?:boolean}> - } - - - export interface QueryLike { - query:string; - values: any[] - text:string - } - export interface DatabaseConnection { - queryAsync(query:string, ...params:any[]):Promise<{rowCount:number;rows:T[]}> - queryAsync(query:QueryLike):Promise<{rowCount:number;rows:T[]}> - } - - export interface Transaction extends DatabaseConnection { - rollback():void - commitAsync():Promise - } - - export interface SubQuery { - select(node:Column):SubQuery - where(...nodes:any[]):SubQuery - from(table:TableNode):SubQuery - group(...nodes:any[]):SubQuery - order(criteria:OrderByValueNode):SubQuery - notExists(subQuery:SubQuery):SubQuery - } - - interface Executable { - get():Promise - getWithin(tx:DatabaseConnection):Promise - exec():Promise - all():Promise - execWithin(tx:DatabaseConnection):Promise - allWithin(tx:DatabaseConnection):Promise - toQuery():QueryLike; - } - - interface Queryable { - where(...nodes:any[]):Query - delete():ModifyingQuery - select(...nodes:any[]):Query - selectDeep(table: Table): Query - selectDeep(...nodesOrTables:any[]):Query - } - - export interface Query extends Executable, Queryable { - from(table:TableNode):Query - update(o:Dictionary):ModifyingQuery - update(o:{}):ModifyingQuery - group(...nodes:any[]):Query - order(...criteria:OrderByValueNode[]):Query - limit(l:number):Query - offset(o:number):Query - } - - export interface ModifyingQuery extends Executable { - returning(...nodes:any[]):Query - where(...nodes:any[]):ModifyingQuery - } - - export interface TableNode { - join(table:TableNode):JoinTableNode - leftJoin(table:TableNode):JoinTableNode - } - - export interface JoinTableNode extends TableNode { - on(filter:BinaryNode):TableNode - on(filter:string):TableNode - } - - interface CreateQuery extends Executable { - ifNotExists():Executable - } - interface DropQuery extends Executable { - ifExists():Executable - } - export interface Table extends TableNode, Queryable { - create():CreateQuery - drop():DropQuery - as(name:string):Table - update(o:any):ModifyingQuery - insert(row:T):ModifyingQuery - insert(rows:T[]):ModifyingQuery - select():Query - select(...nodes:any[]):Query - from(table:TableNode):Query - star():Column - subQuery():SubQuery - eventEmitter:{emit:(type:string, ...args:any[])=>void - on:(eventName:string, handler:Function)=>void} - columns:Column[] - sql: SQL; - alter():AlterQuery - } - export interface AlterQuery extends Executable { - addColumn(column:Column): AlterQuery; - addColumn(name: string, options:string): AlterQuery; - dropColumn(column: Column): AlterQuery; - renameColumn(column: Column, newColumn: Column):AlterQuery; - renameColumn(column: Column, newName: string):AlterQuery; - renameColumn(name: string, newName: string):AlterQuery; - rename(newName: string): AlterQuery - } - - export interface SQL { - functions: { - LOWER(c:Column):Column - } - } - - export interface BinaryNode { - and(node:BinaryNode):BinaryNode - or(node:BinaryNode):BinaryNode - } - - export interface Column { - in(arr:T[]):BinaryNode - in(subQuery:SubQuery):BinaryNode - notIn(arr:T[]):BinaryNode - equals(node:any):BinaryNode - notEquals(node:any):BinaryNode - gte(node:any):BinaryNode - lte(node:any):BinaryNode - gt(node:any):BinaryNode - lt(node:any):BinaryNode - like(str:string):BinaryNode - multiply:{ - (node:Column):Column - (n:number):Column - } - isNull():BinaryNode - isNotNull():BinaryNode - sum():Column - count():Column - count(name:string):Column - distinct():Column - as(name:string):Column - ascending:OrderByValueNode - descending:OrderByValueNode - asc:OrderByValueNode - desc:OrderByValueNode - } - - export interface AnydbSql extends DatabaseConnection { - define(map:TableDefinition):Table; - transaction(fn:(tx:Transaction)=>Promise):Promise - allOf(...tables:Table[]):any - models:Dictionary> - functions:{LOWER:(name:Column)=>Column - RTRIM:(name:Column)=>Column} - makeFunction(name:string):Function - begin():Transaction - open():void; - close():void; - getPool():AnyDBPool; - dialect():string; - } - } - - function anydbSQL(config:Object):anydbSQL.AnydbSql; - - export = anydbSQL; +interface AnyDBPool extends anydbSQL.DatabaseConnection { + query: (text: string, values: any[], callback: (err: Error, result: any) => void) => void + begin: () => anydbSQL.Transaction + close: (err: Error) => void } + +interface Dictionary { [key: string]: T; } + +declare namespace anydbSQL { + export interface OrderByValueNode { } + export interface ColumnDefinition { + primaryKey?: boolean; + dataType?: string; + references?: { table: string; column: string } + notNull?: boolean + } + + export interface TableDefinition { + name: string + columns: Dictionary + has?: Dictionary<{ from: string; many?: boolean }> + } + + + export interface QueryLike { + query: string; + values: any[] + text: string + } + export interface DatabaseConnection { + queryAsync(query: string, ...params: any[]): Promise<{ rowCount: number; rows: T[] }> + queryAsync(query: QueryLike): Promise<{ rowCount: number; rows: T[] }> + } + + export interface Transaction extends DatabaseConnection { + rollback(): void + commitAsync(): Promise + } + + export interface SubQuery { + select(node: Column): SubQuery + where(...nodes: any[]): SubQuery + from(table: TableNode): SubQuery + group(...nodes: any[]): SubQuery + order(criteria: OrderByValueNode): SubQuery + notExists(subQuery: SubQuery): SubQuery + } + + interface Executable { + get(): Promise + getWithin(tx: DatabaseConnection): Promise + exec(): Promise + all(): Promise + execWithin(tx: DatabaseConnection): Promise + allWithin(tx: DatabaseConnection): Promise + toQuery(): QueryLike; + } + + interface Queryable { + where(...nodes: any[]): Query + delete(): ModifyingQuery + select(...nodes: any[]): Query + selectDeep(table: Table): Query + selectDeep(...nodesOrTables: any[]): Query + } + + export interface Query extends Executable, Queryable { + from(table: TableNode): Query + update(o: Dictionary): ModifyingQuery + update(o: {}): ModifyingQuery + group(...nodes: any[]): Query + order(...criteria: OrderByValueNode[]): Query + limit(l: number): Query + offset(o: number): Query + } + + export interface ModifyingQuery extends Executable { + returning(...nodes: any[]): Query + where(...nodes: any[]): ModifyingQuery + } + + export interface TableNode { + join(table: TableNode): JoinTableNode + leftJoin(table: TableNode): JoinTableNode + } + + export interface JoinTableNode extends TableNode { + on(filter: BinaryNode): TableNode + on(filter: string): TableNode + } + + interface CreateQuery extends Executable { + ifNotExists(): Executable + } + interface DropQuery extends Executable { + ifExists(): Executable + } + export interface Table extends TableNode, Queryable { + create(): CreateQuery + drop(): DropQuery + as(name: string): Table + update(o: any): ModifyingQuery + insert(row: T): ModifyingQuery + insert(rows: T[]): ModifyingQuery + select(): Query + select(...nodes: any[]): Query + from(table: TableNode): Query + star(): Column + subQuery(): SubQuery + eventEmitter: { + emit: (type: string, ...args: any[]) => void + on: (eventName: string, handler: Function) => void + } + columns: Column[] + sql: SQL; + alter(): AlterQuery + } + export interface AlterQuery extends Executable { + addColumn(column: Column): AlterQuery; + addColumn(name: string, options: string): AlterQuery; + dropColumn(column: Column): AlterQuery; + renameColumn(column: Column, newColumn: Column): AlterQuery; + renameColumn(column: Column, newName: string): AlterQuery; + renameColumn(name: string, newName: string): AlterQuery; + rename(newName: string): AlterQuery + } + + export interface SQL { + functions: { + LOWER(c: Column): Column + } + } + + export interface BinaryNode { + and(node: BinaryNode): BinaryNode + or(node: BinaryNode): BinaryNode + } + + export interface Column { + in(arr: T[]): BinaryNode + in(subQuery: SubQuery): BinaryNode + notIn(arr: T[]): BinaryNode + equals(node: any): BinaryNode + notEquals(node: any): BinaryNode + gte(node: any): BinaryNode + lte(node: any): BinaryNode + gt(node: any): BinaryNode + lt(node: any): BinaryNode + like(str: string): BinaryNode + multiply: { + (node: Column): Column + (n: number): Column + } + isNull(): BinaryNode + isNotNull(): BinaryNode + sum(): Column + count(): Column + count(name: string): Column + distinct(): Column + as(name: string): Column + ascending: OrderByValueNode + descending: OrderByValueNode + asc: OrderByValueNode + desc: OrderByValueNode + } + + export interface AnydbSql extends DatabaseConnection { + define(map: TableDefinition): Table; + transaction(fn: (tx: Transaction) => Promise): Promise + allOf(...tables: Table[]): any + models: Dictionary> + functions: { + LOWER: (name: Column) => Column + RTRIM: (name: Column) => Column + } + makeFunction(name: string): Function + begin(): Transaction + open(): void; + close(): void; + getPool(): AnyDBPool; + dialect(): string; + } +} + +declare function anydbSQL(config: Object): anydbSQL.AnydbSql; + +export = anydbSQL; diff --git a/api-error-handler/api-error-handler.d.ts b/api-error-handler/api-error-handler.d.ts index 96fbb16b29..eceae9bb4b 100644 --- a/api-error-handler/api-error-handler.d.ts +++ b/api-error-handler/api-error-handler.d.ts @@ -5,26 +5,25 @@ /// -declare module 'api-error-handler' { - import * as express from 'express'; - namespace apiErrorHandler { +import * as express from 'express'; - // Body response: the JSON returned by api-error-handler - // See https://github.com/expressjs/api-error-handler/blob/1.0.0/index.js - interface Response { - status: number; - stack?: string; - message: string; +declare namespace apiErrorHandler { - // Client errors - code?: any; - name?: string; - type?: any; - } + // Body response: the JSON returned by api-error-handler + // See https://github.com/expressjs/api-error-handler/blob/1.0.0/index.js + interface Response { + status: number; + stack?: string; + message: string; + + // Client errors + code?: any; + name?: string; + type?: any; } - - function apiErrorHandler(options?: any): express.ErrorRequestHandler; - - export = apiErrorHandler; } + +declare function apiErrorHandler(options?: any): express.ErrorRequestHandler; + +export = apiErrorHandler; diff --git a/apn/apn.d.ts b/apn/apn.d.ts index cf11b13c0e..2c4d39d81b 100644 --- a/apn/apn.d.ts +++ b/apn/apn.d.ts @@ -4,361 +4,360 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare module "apn" { - import events = require("events"); - import net = require("net"); - export interface ConnectionOptions { - /** - * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) - */ - cert?:string|Buffer; - /** - * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) - */ - key?:string|Buffer; - /** - * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). - */ - ca?:(string|Buffer)[]; - /** - * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above. - */ - pfx?:string|Buffer; - /** - * The passphrase for the connection key, if required - */ - passphrase?:string; - /** - * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) - */ - production?:boolean; - /** - * Enable when you are using a VoIP certificate to enable paylods up to 4096 bytes. - */ - voip?:boolean; - /** - * Gateway port (Defaults to: `2195`) - */ - port?:number; - /** - * Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`) - */ - rejectUnauthorized?:boolean; - /** - * Number of notifications to cache for error purposes (See "Handling Errors" below, (Defaults to: `1000`) - */ - cacheLength?:number; - /** - * Whether the cache should grow in response to messages being lost after errors. (Will still emit a 'cacheTooSmall' event) (Defaults to: `true`) - */ - autoAdjustCache?:boolean; - /** - * The maximum number of connections to create for sending messages. (Defaults to: `1`) - */ - maxConnections?:number; - /** - * The duration of time the module should wait, in milliseconds, when trying to establish a connection to Apple before failing. 0 = Disabled. {Defaults to: `10000`} - */ - connectTimeout?:number; - /** - * The duration the socket should stay alive with no activity in milliseconds. 0 = Disabled. (Defaults to: `3600000` - 1h) - */ - connectionTimeout?:number; - /** - * The maximum number of connection failures that will be tolerated before `apn` will "terminate". (Defaults to: 10) - */ - connectionRetryLimit?:number; - /** - * Whether to buffer notifications and resend them after failure. (Defaults to: `true`) - */ - buffersNotifications?:number; - /** - * Whether to aggresively empty the notification buffer while connected - if set to true node-apn may enter a tight loop under heavy load while delivering notifications. (Defaults to: `false`) - */ - fastMode?:boolean; - } - export class Connection extends events.EventEmitter { - constructor(options:ConnectionOptions); - /** - * This is the business end of the module. Create a `Notification` object and pass it in, along with a single recipient or an array of them and node-apn will take care of the rest, delivering the notification to each recipient. - * - * A "recipient" is either a `Device` object, a `String`, or a `Buffer` containing the device token. `Device` objects are used internally and will be created if necessary. Where applicable, all events will return a `Device` regardless of the type passed to this method. - */ - pushNotification(notification:Notification, recipient:Device|string|Buffer|(Device|string|Buffer)[]):void; - /** - * Used to manually adjust the "cacheLength" property in the options. This is ideal if you choose to use the `cacheTooSmall` event to tweak your environment. It is safe for increasing and reducing cache size. - */ - setCacheLength(newLength:number):void; - /** - * Indicate to node-apn that when the queue of pending notifications is fully drained that it should close all open connections. This will mean that if there are no other pending resources (open sockets, running timers, etc.) the application will terminate. If notifications are pushed after the connection has completely shutdown a new connection will be established and, if applicable, `shutdown` will need to be called again. - */ - shutdown():void; - /** - * Emitted when an error occurs during initialisation of the module, usually due to a problem with the keys and certificates. - */ - on(event: "error", listener: (error:Error) => void):this; - /** - * Emitted when the connection socket experiences an error. This may be useful for debugging but no action should be necessary. - */ - on(event: "socketError", listener: (error:Error) => void):this; - /** - * Emitted when a notification has been sent to Apple - not a guarantee that it has been accepted by Apple, an error relating to it may occur later on. A notification may also be "transmitted" several times if a preceding notification caused an error requiring retransmission. - */ - on(event: "transmitted", listener: (notification:Notification, decive:Device) => void):this; - /** - * Emitted when all pending notifications have been transmitted to Apple and the pending queue is empty. This may be called more than once if a notification error occurs and notifications must be re-sent. - */ - on(event: "completed", listener: () => void):this; - /** - * Emitted when Apple returns a notification as invalid but the notification has already been expunged from the cache - usually due to high throughput and indicates that notifications will be getting lost. The parameter is an estimate of how many notifications have been lost. You should experiment with increasing the cache size or enabling ```autoAdjustCache``` if you see this frequently. - * - * **Note**: With ```autoAdjustCache``` enabled this event will still be emitted when an adjustment is triggered. - */ - on(event: "cacheTooSmall", listener: (sizeDifference:number) => void):this; - /** - * Emitted when a connection to Apple is successfully established. The parameter indicates the number of open connections. No action is required as the connection is managed internally. - */ - on(event: "connected", listener: (openSockets:net.Socket[]) => void):this; - /** - * Emitted when the connection to Apple has been closed, this could be for numerous reasons, for example an error has occurred or the connection has timed out. The parameter is the same as for `connected` and again, no action is required. - */ - on(event: "disconnected", listener: (openSockets:net.Socket[]) => void):this; - /** - * Emitted when the connectionTimeout option has been specified and no activity has occurred on a socket for a specified duration. The socket will be closed immediately after this event and a `disconnected` event will also be emitted. - */ - on(event: "timeout", listener: () => void):this; - /** - * Emitted when a message has been received from Apple stating that a notification was invalid or if an internal error occurred before that notification could be pushed to Apple. If the notification is still in the cache it will be passed as the second argument, otherwise null. Where possible the associated `Device` object will be passed as a third parameter, however in cases where the token supplied to the module cannot be parsed into a `Buffer` the supplied value will be returned. - * Error codes smaller than 512 correspond to those returned by Apple as per their [docs][errors]. Other errors are applicable to `node-apn` itself. Definitions can be found in `lib/errors.js`. - */ - on(event: "transmissionError", listener: (errorCode:number, notification:Notification, device:Device|Buffer) => void):this; - on(event: string, listener: Function):this; - } - export interface NotificationAlertOptions { - title?:string; - body:string; - "title-loc-key"?:string; - "title-loc-args"?:string[]; - "action-loc-key"?:string; - "loc-key"?:string; - "loc-args"?:string[]; - "launch-image"?:string; - } - export class Notification { - /** - * The maximum number of retries which should be performed when sending a notification if an error occurs. A value of 0 will only allow one attempt at sending (0 retries). Set to -1 to disable (default). - */ - public retryLimit:number; - /** - * The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately. - */ - public expiry:number; - /** - * From Apple's Documentation, Provide one of the following values: - * - * - 10 - The push message is sent immediately. (Default) - * > The push notification must trigger an alert, sound, or badge on the device. It is an error use this priority for a push that contains only the content-available key. - * - 5 - The push message is sent at a time that conserves power on the device receiving it. - */ - public priority:number; - /** - * The encoding to use when transmitting the notification to APNS, defaults to `utf8`. `utf16le` is also possible but as each character is represented by a minimum of 2 bytes, will at least halve the possible payload size. If in doubt leave as default. - */ - public encoding:string; - /** - * This object represents the root JSON object that you can add custom information for your application to. The properties below will only be added to the payload (under `aps`) when the notification is prepared for sending. - */ - public payload:any; - /** - * The value to specify for `payload.aps.badge` - */ - public badge:number; - /** - * The value to specify for `payload.aps.sound` - */ - public sound:string; - /** - * The value to specify for `payload.aps.alert` can be either a `String` or an `Object` as outlined by the payload documentation. - */ - public alert:string|NotificationAlertOptions; - /** - * Setting this to true will specify "content-available" in the payload when it is compiled. - */ - public newsstandAvailable:boolean; - /** - * Setting this to true will specify "content-available" in the payload when it is compiled. - */ - public contentAvailable:boolean; - /** - * The value to specify for the `mdm` field where applicable. - */ - public mdm:string|Object; - /** - * The value to specify for `payload.aps['url-args']`. This used for Safari Push NOtifications and should be an array of values in accordance with the Web Payload Documentation. - */ - public urlArgs:string[]; - /** - * When this parameter is set and `notification#trim()` is called it will attempt to truncate the string at the nearest space. - */ - public truncateAtWordEnd:boolean; - /** - * You can optionally pass in an object representing the payload, or configure properties on the returned object. - */ - constructor(payload?:any); - /** - * Set the `aps.alert` text body. This will use the most space-efficient means. - */ - setAlertText(alertText:string):Notification; - /** - * Set the `title` property of the `aps.alert` object - used with Safari Push Notifications - */ - setAlertTitle(alertTitle:string):Notification; - /** - * Set the `action` property of the `aps.alert` object - used with Safari Push Notifications - */ - setAlertAction(alertAction:string):Notification; - /** - * Set the `action-loc-key` property of the `aps.alert` object. - */ - setActionLocKey(key:string):Notification; - /** - * Set the `loc-key` property of the `aps.alert` object. - */ - setLocKey(key:string):Notification; - /** - * Set the `loc-args` property of the `aps.alert` object. - */ - setLocArgs(args:string[]):Notification; - /** - * Set the `launch-image` property of the `aps.alert` object. - */ - setLaunchImage(image:string):Notification; - /** - * Set the `mdm` property on the payload. - */ - setMDM(mdm:string|Object):Notification; - /** - * Set the `content-available` property of the `aps` object. - */ - setNewsstandAvailable(available:boolean):Notification; - /** - * Set the `content-available` property of the `aps` object. - */ - setContentAvailable(available:boolean):Notification; - /** - * Set the `url-args` property of the `aps` object. - */ - setUrlArgs(urlArgs:string[]):Notification; - /** - * Attempt to automatically trim the notification alert text body to meet the payload size limit of 2048 bytes. - */ - trim():number; - } - export class Device { - public token:Buffer; - /** - * `deviceToken` can be a `Buffer` or a `String` containing a "hex" representation of the token. Throws an error if the deviceToken supplied is invalid. - */ - constructor(deviceToken:string|Buffer); - } - - export interface FeedbackOptions { - /** - * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) - */ - cert?:string|Buffer; - /** - * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) - */ - key?:string|Buffer; - /** - * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). - */ - ca?:(string|Buffer)[]; - /** - * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will be used instead of certificate and key above. - */ - pfx?:string|Buffer; - /** - * The passphrase for the connection key, if required - */ - passphrase?:string; - /** - * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) - */ - production?:boolean; - /** - * Feedback server port (Defaults to: `2196`) - */ - port?:number; - /** - * Sets the behaviour for triggering the `feedback` event. When `true` the event will be triggered once per connection with an array of timestamp and device token tuples. Otherwise a `feedback` event will be emitted once per token received. (Defaults to: true) - */ - batchFeedback?:boolean; - /** - * The maximum number of tokens to pass when emitting the event - a value of 0 will cause all tokens to be passed after connection is reset. After this number of tokens are received the `feedback` event will be emitted. (Only applies when `batchFeedback` is enabled) - */ - batchSize?:number; - /** - * How often to automatically poll the feedback service. Set to `0` to disable. (Defaults to: `3600`) - */ - interval?:number; - } - export interface FeedbackData { - time:number; - device:Device; - } - /** - * Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()` - */ - export class Feedback { - constructor(options:FeedbackOptions); - /** - * Trigger a query of the feedback service. If `interval` is non-zero then this method will be called automatically. - */ - start():void; - /** - * You can cancel the interval by calling `feedback.cancel()`. If you do not wish to have the service automatically queried then set `interval` to 0 and use `feedback.start()` to manually invoke it one time. - */ - cancel():void; - /** - * Emitted when an error occurs initialising the module. Usually caused by failing to load the certificates. - */ - on(event: "error", listener: (error:Error) => void):Feedback; - /** - * Emitted when an error occurs receiving or processing the feedback and in the case of a socket error occurring. These errors are usually informational and node-apn will automatically recover. - */ - on(event: "feedbackError", listener: (error:Error) => void):Feedback; - /** - * Emitted when data has been received from the feedback service, typically once per connection. `feedbackData` is an array of objects, each containing the `time` returned by the server (epoch time) and the `device` a `Buffer` containing the device token. - */ - on(event: "feedback", listener: (feedbackData:FeedbackData[]) => void):Feedback; - on(event: string, listener: Function):Feedback; - } - - export enum Errors { - "noErrorsEncountered"= 0, - "processingError"= 1, - "missingDeviceToken"= 2, - "missingTopic"= 3, - "missingPayload"= 4, - "invalidTokenSize"= 5, - "invalidTopicSize"= 6, - "invalidPayloadSize"= 7, - "invalidToken"= 8, - "apnsShutdown"= 10, - "none"= 255, - "retryLimitExceeded"= 512, - "moduleInitialisationFailed"= 513, - "connectionRetryLimitExceeded"= 514, // When a connection is unable to be established. Usually because of a network / SSL error this will be emitted - "connectionTerminated"= 515 - } - - //Lowercase aliases - export {Connection as connection}; - export {Device as device}; - export {Errors as error}; - export {Feedback as feedback}; - export {Notification as notification}; +import events = require("events"); +import net = require("net"); +export interface ConnectionOptions { + /** + * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) + */ + cert?: string | Buffer; + /** + * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) + */ + key?: string | Buffer; + /** + * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). + */ + ca?: (string | Buffer)[]; + /** + * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above. + */ + pfx?: string | Buffer; + /** + * The passphrase for the connection key, if required + */ + passphrase?: string; + /** + * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) + */ + production?: boolean; + /** + * Enable when you are using a VoIP certificate to enable paylods up to 4096 bytes. + */ + voip?: boolean; + /** + * Gateway port (Defaults to: `2195`) + */ + port?: number; + /** + * Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`) + */ + rejectUnauthorized?: boolean; + /** + * Number of notifications to cache for error purposes (See "Handling Errors" below, (Defaults to: `1000`) + */ + cacheLength?: number; + /** + * Whether the cache should grow in response to messages being lost after errors. (Will still emit a 'cacheTooSmall' event) (Defaults to: `true`) + */ + autoAdjustCache?: boolean; + /** + * The maximum number of connections to create for sending messages. (Defaults to: `1`) + */ + maxConnections?: number; + /** + * The duration of time the module should wait, in milliseconds, when trying to establish a connection to Apple before failing. 0 = Disabled. {Defaults to: `10000`} + */ + connectTimeout?: number; + /** + * The duration the socket should stay alive with no activity in milliseconds. 0 = Disabled. (Defaults to: `3600000` - 1h) + */ + connectionTimeout?: number; + /** + * The maximum number of connection failures that will be tolerated before `apn` will "terminate". (Defaults to: 10) + */ + connectionRetryLimit?: number; + /** + * Whether to buffer notifications and resend them after failure. (Defaults to: `true`) + */ + buffersNotifications?: number; + /** + * Whether to aggresively empty the notification buffer while connected - if set to true node-apn may enter a tight loop under heavy load while delivering notifications. (Defaults to: `false`) + */ + fastMode?: boolean; } +declare export class Connection extends events.EventEmitter { + constructor(options: ConnectionOptions); + /** + * This is the business end of the module. Create a `Notification` object and pass it in, along with a single recipient or an array of them and node-apn will take care of the rest, delivering the notification to each recipient. + * + * A "recipient" is either a `Device` object, a `String`, or a `Buffer` containing the device token. `Device` objects are used internally and will be created if necessary. Where applicable, all events will return a `Device` regardless of the type passed to this method. + */ + pushNotification(notification: Notification, recipient: Device | string | Buffer | (Device | string | Buffer)[]): void; + /** + * Used to manually adjust the "cacheLength" property in the options. This is ideal if you choose to use the `cacheTooSmall` event to tweak your environment. It is safe for increasing and reducing cache size. + */ + setCacheLength(newLength: number): void; + /** + * Indicate to node-apn that when the queue of pending notifications is fully drained that it should close all open connections. This will mean that if there are no other pending resources (open sockets, running timers, etc.) the application will terminate. If notifications are pushed after the connection has completely shutdown a new connection will be established and, if applicable, `shutdown` will need to be called again. + */ + shutdown(): void; + /** + * Emitted when an error occurs during initialisation of the module, usually due to a problem with the keys and certificates. + */ + on(event: "error", listener: (error: Error) => void): this; + /** + * Emitted when the connection socket experiences an error. This may be useful for debugging but no action should be necessary. + */ + on(event: "socketError", listener: (error: Error) => void): this; + /** + * Emitted when a notification has been sent to Apple - not a guarantee that it has been accepted by Apple, an error relating to it may occur later on. A notification may also be "transmitted" several times if a preceding notification caused an error requiring retransmission. + */ + on(event: "transmitted", listener: (notification: Notification, decive: Device) => void): this; + /** + * Emitted when all pending notifications have been transmitted to Apple and the pending queue is empty. This may be called more than once if a notification error occurs and notifications must be re-sent. + */ + on(event: "completed", listener: () => void): this; + /** + * Emitted when Apple returns a notification as invalid but the notification has already been expunged from the cache - usually due to high throughput and indicates that notifications will be getting lost. The parameter is an estimate of how many notifications have been lost. You should experiment with increasing the cache size or enabling ```autoAdjustCache``` if you see this frequently. + * + * **Note**: With ```autoAdjustCache``` enabled this event will still be emitted when an adjustment is triggered. + */ + on(event: "cacheTooSmall", listener: (sizeDifference: number) => void): this; + /** + * Emitted when a connection to Apple is successfully established. The parameter indicates the number of open connections. No action is required as the connection is managed internally. + */ + on(event: "connected", listener: (openSockets: net.Socket[]) => void): this; + /** + * Emitted when the connection to Apple has been closed, this could be for numerous reasons, for example an error has occurred or the connection has timed out. The parameter is the same as for `connected` and again, no action is required. + */ + on(event: "disconnected", listener: (openSockets: net.Socket[]) => void): this; + /** + * Emitted when the connectionTimeout option has been specified and no activity has occurred on a socket for a specified duration. The socket will be closed immediately after this event and a `disconnected` event will also be emitted. + */ + on(event: "timeout", listener: () => void): this; + /** + * Emitted when a message has been received from Apple stating that a notification was invalid or if an internal error occurred before that notification could be pushed to Apple. If the notification is still in the cache it will be passed as the second argument, otherwise null. Where possible the associated `Device` object will be passed as a third parameter, however in cases where the token supplied to the module cannot be parsed into a `Buffer` the supplied value will be returned. + + * Error codes smaller than 512 correspond to those returned by Apple as per their [docs][errors]. Other errors are applicable to `node-apn` itself. Definitions can be found in `lib/errors.js`. + */ + on(event: "transmissionError", listener: (errorCode: number, notification: Notification, device: Device | Buffer) => void): this; + on(event: string, listener: Function): this; +} +export interface NotificationAlertOptions { + title?: string; + body: string; + "title-loc-key"?: string; + "title-loc-args"?: string[]; + "action-loc-key"?: string; + "loc-key"?: string; + "loc-args"?: string[]; + "launch-image"?: string; +} +declare export class Notification { + /** + * The maximum number of retries which should be performed when sending a notification if an error occurs. A value of 0 will only allow one attempt at sending (0 retries). Set to -1 to disable (default). + */ + public retryLimit: number; + /** + * The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately. + */ + public expiry: number; + /** + * From Apple's Documentation, Provide one of the following values: + * + * - 10 - The push message is sent immediately. (Default) + * > The push notification must trigger an alert, sound, or badge on the device. It is an error use this priority for a push that contains only the content-available key. + * - 5 - The push message is sent at a time that conserves power on the device receiving it. + */ + public priority: number; + /** + * The encoding to use when transmitting the notification to APNS, defaults to `utf8`. `utf16le` is also possible but as each character is represented by a minimum of 2 bytes, will at least halve the possible payload size. If in doubt leave as default. + */ + public encoding: string; + /** + * This object represents the root JSON object that you can add custom information for your application to. The properties below will only be added to the payload (under `aps`) when the notification is prepared for sending. + */ + public payload: any; + /** + * The value to specify for `payload.aps.badge` + */ + public badge: number; + /** + * The value to specify for `payload.aps.sound` + */ + public sound: string; + /** + * The value to specify for `payload.aps.alert` can be either a `String` or an `Object` as outlined by the payload documentation. + */ + public alert: string | NotificationAlertOptions; + /** + * Setting this to true will specify "content-available" in the payload when it is compiled. + */ + public newsstandAvailable: boolean; + /** + * Setting this to true will specify "content-available" in the payload when it is compiled. + */ + public contentAvailable: boolean; + /** + * The value to specify for the `mdm` field where applicable. + */ + public mdm: string | Object; + /** + * The value to specify for `payload.aps['url-args']`. This used for Safari Push NOtifications and should be an array of values in accordance with the Web Payload Documentation. + */ + public urlArgs: string[]; + /** + * When this parameter is set and `notification#trim()` is called it will attempt to truncate the string at the nearest space. + */ + public truncateAtWordEnd: boolean; + /** + * You can optionally pass in an object representing the payload, or configure properties on the returned object. + */ + constructor(payload?: any); + /** + * Set the `aps.alert` text body. This will use the most space-efficient means. + */ + setAlertText(alertText: string): Notification; + /** + * Set the `title` property of the `aps.alert` object - used with Safari Push Notifications + */ + setAlertTitle(alertTitle: string): Notification; + /** + * Set the `action` property of the `aps.alert` object - used with Safari Push Notifications + */ + setAlertAction(alertAction: string): Notification; + /** + * Set the `action-loc-key` property of the `aps.alert` object. + */ + setActionLocKey(key: string): Notification; + /** + * Set the `loc-key` property of the `aps.alert` object. + */ + setLocKey(key: string): Notification; + /** + * Set the `loc-args` property of the `aps.alert` object. + */ + setLocArgs(args: string[]): Notification; + /** + * Set the `launch-image` property of the `aps.alert` object. + */ + setLaunchImage(image: string): Notification; + /** + * Set the `mdm` property on the payload. + */ + setMDM(mdm: string | Object): Notification; + /** + * Set the `content-available` property of the `aps` object. + */ + setNewsstandAvailable(available: boolean): Notification; + /** + * Set the `content-available` property of the `aps` object. + */ + setContentAvailable(available: boolean): Notification; + /** + * Set the `url-args` property of the `aps` object. + */ + setUrlArgs(urlArgs: string[]): Notification; + /** + * Attempt to automatically trim the notification alert text body to meet the payload size limit of 2048 bytes. + */ + trim(): number; +} +declare export class Device { + public token: Buffer; + /** + * `deviceToken` can be a `Buffer` or a `String` containing a "hex" representation of the token. Throws an error if the deviceToken supplied is invalid. + */ + constructor(deviceToken: string | Buffer); +} + +export interface FeedbackOptions { + /** + * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) + */ + cert?: string | Buffer; + /** + * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) + */ + key?: string | Buffer; + /** + * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). + */ + ca?: (string | Buffer)[]; + /** + * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will be used instead of certificate and key above. + */ + pfx?: string | Buffer; + /** + * The passphrase for the connection key, if required + */ + passphrase?: string; + /** + * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) + */ + production?: boolean; + /** + * Feedback server port (Defaults to: `2196`) + */ + port?: number; + /** + * Sets the behaviour for triggering the `feedback` event. When `true` the event will be triggered once per connection with an array of timestamp and device token tuples. Otherwise a `feedback` event will be emitted once per token received. (Defaults to: true) + */ + batchFeedback?: boolean; + /** + * The maximum number of tokens to pass when emitting the event - a value of 0 will cause all tokens to be passed after connection is reset. After this number of tokens are received the `feedback` event will be emitted. (Only applies when `batchFeedback` is enabled) + */ + batchSize?: number; + /** + * How often to automatically poll the feedback service. Set to `0` to disable. (Defaults to: `3600`) + */ + interval?: number; +} +export interface FeedbackData { + time: number; + device: Device; +} +/** + * Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()` + */ +declare export class Feedback { + constructor(options: FeedbackOptions); + /** + * Trigger a query of the feedback service. If `interval` is non-zero then this method will be called automatically. + */ + start(): void; + /** + * You can cancel the interval by calling `feedback.cancel()`. If you do not wish to have the service automatically queried then set `interval` to 0 and use `feedback.start()` to manually invoke it one time. + */ + cancel(): void; + /** + * Emitted when an error occurs initialising the module. Usually caused by failing to load the certificates. + */ + on(event: "error", listener: (error: Error) => void): Feedback; + /** + * Emitted when an error occurs receiving or processing the feedback and in the case of a socket error occurring. These errors are usually informational and node-apn will automatically recover. + */ + on(event: "feedbackError", listener: (error: Error) => void): Feedback; + /** + * Emitted when data has been received from the feedback service, typically once per connection. `feedbackData` is an array of objects, each containing the `time` returned by the server (epoch time) and the `device` a `Buffer` containing the device token. + */ + on(event: "feedback", listener: (feedbackData: FeedbackData[]) => void): Feedback; + on(event: string, listener: Function): Feedback; +} + +declare export enum Errors { + "noErrorsEncountered" = 0, + "processingError" = 1, + "missingDeviceToken" = 2, + "missingTopic" = 3, + "missingPayload" = 4, + "invalidTokenSize" = 5, + "invalidTopicSize" = 6, + "invalidPayloadSize" = 7, + "invalidToken" = 8, + "apnsShutdown" = 10, + "none" = 255, + "retryLimitExceeded" = 512, + "moduleInitialisationFailed" = 513, + "connectionRetryLimitExceeded" = 514, // When a connection is unable to be established. Usually because of a network / SSL error this will be emitted + "connectionTerminated" = 515 +} + +//Lowercase aliases +export {Connection as connection}; +export {Device as device}; +export {Errors as error}; +export {Feedback as feedback}; +export {Notification as notification}; diff --git a/archiver/archiver.d.ts b/archiver/archiver.d.ts index d5133555a4..3a864d8822 100644 --- a/archiver/archiver.d.ts +++ b/archiver/archiver.d.ts @@ -14,29 +14,28 @@ =============================================== */ /// -declare module "archiver" { - import * as FS from 'fs'; - import * as STREAM from 'stream'; - - interface nameInterface { - name?: string; - } - - interface Archiver extends STREAM.Transform { - pipe(writeStream: FS.WriteStream): void; - append(readStream: FS.ReadStream, name: nameInterface): void; - finalize(): void; - } - - interface Options { - - } - - function archiver(format: string, options?: Options): Archiver; - - namespace archiver { - function create(format: string, options?: Options): Archiver; - } - - export = archiver; + +import * as FS from 'fs'; +import * as STREAM from 'stream'; + +interface nameInterface { + name?: string; } + +interface Archiver extends STREAM.Transform { + pipe(writeStream: FS.WriteStream): void; + append(readStream: FS.ReadStream, name: nameInterface): void; + finalize(): void; +} + +interface Options { + +} + +declare function archiver(format: string, options?: Options): Archiver; + +declare namespace archiver { + function create(format: string, options?: Options): Archiver; +} + +export = archiver; diff --git a/archy/archy.d.ts b/archy/archy.d.ts index f4e13ef8a9..82b101236c 100644 --- a/archy/archy.d.ts +++ b/archy/archy.d.ts @@ -3,19 +3,18 @@ // Definitions by: vvakame // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "archy" { - function archy(obj: archy.Data, prefix?: string, opts?: archy.Options): string; - function archy(obj: string, prefix?: string, opts?: archy.Options): string; - namespace archy { - interface Data { - label: string; - nodes?: (Data | string)[]; - } - interface Options { - unicode?: boolean; - } +declare function archy(obj: archy.Data, prefix?: string, opts?: archy.Options): string; +declare function archy(obj: string, prefix?: string, opts?: archy.Options): string; + +declare namespace archy { + interface Data { + label: string; + nodes?: (Data | string)[]; + } + interface Options { + unicode?: boolean; } - - export = archy; } + +export = archy; diff --git a/argparse/argparse.d.ts b/argparse/argparse.d.ts index 886fef8cc9..7847c962bc 100644 --- a/argparse/argparse.d.ts +++ b/argparse/argparse.d.ts @@ -3,88 +3,87 @@ // Definitions by: Andrew Schurman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "argparse" { - export class ArgumentParser extends ArgumentGroup { - constructor(options? : ArgumentParserOptions); - addSubparsers(options? : SubparserOptions) : SubParser; - parseArgs(args? : string[], ns? : Namespace|Object) : any; - printUsage() : void; - printHelp() : void; - formatUsage() : string; - formatHelp() : string; - parseKnownArgs(args? : string[], ns? : Namespace|Object) : any[]; - convertArgLineToArg(argLine : string) : string[]; - exit(status : number, message : string) : void; - error(err : string|Error) : void; - } - - interface Namespace {} - - class SubParser { - addParser(name : string, options? : SubArgumentParserOptions) : ArgumentParser; - } - - class ArgumentGroup { - addArgument(args : string[], options? : ArgumentOptions) : void; - addArgumentGroup(options? : ArgumentGroupOptions) : ArgumentGroup; - addMutuallyExclusiveGroup(options? : {required : boolean}) : ArgumentGroup; - setDefaults(options? : {}) : void; - getDefault(dest : string) : any; - } - - interface SubparserOptions { - title? : string; - description? : string; - prog? : string; - parserClass? : {new() : any}; - action? : string; - dest? : string; - help? : string; - metavar? : string; - } - - interface SubArgumentParserOptions extends ArgumentParserOptions { - aliases? : string[]; - help? : string; - } - - interface ArgumentParserOptions { - description? : string; - epilog? : string; - addHelp? : boolean; - argumentDefault? : any; - parents? : ArgumentParser[]; - prefixChars? : string; - formatterClass? : {new() : HelpFormatter|ArgumentDefaultsHelpFormatter|RawDescriptionHelpFormatter|RawTextHelpFormatter}; - prog? : string; - usage? : string; - version? : string; - } - - interface ArgumentGroupOptions { - prefixChars? : string; - argumentDefault? : any; - title? : string; - description? : string; - } +declare export class ArgumentParser extends ArgumentGroup { + constructor(options?: ArgumentParserOptions); - export class HelpFormatter {} - export class ArgumentDefaultsHelpFormatter {} - export class RawDescriptionHelpFormatter {} - export class RawTextHelpFormatter {} - - interface ArgumentOptions { - action? : string; - optionStrings? : string[]; - dest? : string; - nargs? : string|number; - constant? : any; - defaultValue? : any; - type? : string|Function; - choices? : string|string[]; - required? : boolean; - help? : string; - metavar? : string; - } + addSubparsers(options?: SubparserOptions): SubParser; + parseArgs(args?: string[], ns?: Namespace | Object): any; + printUsage(): void; + printHelp(): void; + formatUsage(): string; + formatHelp(): string; + parseKnownArgs(args?: string[], ns?: Namespace | Object): any[]; + convertArgLineToArg(argLine: string): string[]; + exit(status: number, message: string): void; + error(err: string | Error): void; +} + +interface Namespace { } + +declare class SubParser { + addParser(name: string, options?: SubArgumentParserOptions): ArgumentParser; +} + +declare class ArgumentGroup { + addArgument(args: string[], options?: ArgumentOptions): void; + addArgumentGroup(options?: ArgumentGroupOptions): ArgumentGroup; + addMutuallyExclusiveGroup(options?: { required: boolean }): ArgumentGroup; + setDefaults(options?: {}): void; + getDefault(dest: string): any; +} + +interface SubparserOptions { + title?: string; + description?: string; + prog?: string; + parserClass?: { new (): any }; + action?: string; + dest?: string; + help?: string; + metavar?: string; +} + +interface SubArgumentParserOptions extends ArgumentParserOptions { + aliases?: string[]; + help?: string; +} + +interface ArgumentParserOptions { + description?: string; + epilog?: string; + addHelp?: boolean; + argumentDefault?: any; + parents?: ArgumentParser[]; + prefixChars?: string; + formatterClass?: { new (): HelpFormatter | ArgumentDefaultsHelpFormatter | RawDescriptionHelpFormatter | RawTextHelpFormatter }; + prog?: string; + usage?: string; + version?: string; +} + +interface ArgumentGroupOptions { + prefixChars?: string; + argumentDefault?: any; + title?: string; + description?: string; +} + +declare export class HelpFormatter { } +declare export class ArgumentDefaultsHelpFormatter { } +declare export class RawDescriptionHelpFormatter { } +declare export class RawTextHelpFormatter { } + +interface ArgumentOptions { + action?: string; + optionStrings?: string[]; + dest?: string; + nargs?: string | number; + constant?: any; + defaultValue?: any; + type?: string | Function; + choices?: string | string[]; + required?: boolean; + help?: string; + metavar?: string; } diff --git a/asana/asana.d.ts b/asana/asana.d.ts index 61cb54d26f..e1a022fb6e 100644 --- a/asana/asana.d.ts +++ b/asana/asana.d.ts @@ -6,2471 +6,2469 @@ /// /// -declare module "asana" { - import * as Promise from 'bluebird'; - namespace asana { +import * as Promise from 'bluebird'; + +declare namespace asana { var Client: ClientStatic; interface ClientStatic { - /** - * Constructs a Client with instances of all the resources using the dispatcher. - * It also keeps a reference to the dispatcher so that way the end user can have - * access to it. - * @class - * @classdesc A wrapper for the Asana API which is authenticated for one user - * @param {Dispatcher} dispatcher The request dispatcher to use - * @param {Object} options Options to configure the client - * @param {String} [clientId] ID of the client, required for Oauth - * @param {String} [clientSecret] Secret key, for some Oauth flows - * @param {String} [redirectUri] Default redirect URI for this client - * @param {String} [asanaBaseUrl] Base URL for Asana, for debugging - */ - (dispatcher: Dispatcher, options?: ClientOptions): asana.Client; - /** - * Creates a new client. - * @param {Object} options Options for specifying the client, see constructor. - */ - create(options?: ClientOptions): Client; + /** + * Constructs a Client with instances of all the resources using the dispatcher. + * It also keeps a reference to the dispatcher so that way the end user can have + * access to it. + * @class + * @classdesc A wrapper for the Asana API which is authenticated for one user + * @param {Dispatcher} dispatcher The request dispatcher to use + * @param {Object} options Options to configure the client + * @param {String} [clientId] ID of the client, required for Oauth + * @param {String} [clientSecret] Secret key, for some Oauth flows + * @param {String} [redirectUri] Default redirect URI for this client + * @param {String} [asanaBaseUrl] Base URL for Asana, for debugging + */ + (dispatcher: Dispatcher, options?: ClientOptions): asana.Client; + /** + * Creates a new client. + * @param {Object} options Options for specifying the client, see constructor. + */ + create(options?: ClientOptions): Client; } /** Options to configure the client */ interface ClientOptions extends DispatcherOptions { - clientId?: string|number; - clientSecret?: string; - redirectUri?: string; - asanaBaseUrl?: string; + clientId?: string | number; + clientSecret?: string; + redirectUri?: string; + asanaBaseUrl?: string; } interface Client { - /** - * Ensures the client is authorized to make requests. Kicks off the - * configured Oauth flow, if any. - * - * @returns {Promise} A promise that resolves to this client when - * authorization is complete. - */ - authorize(): Promise; + /** + * Ensures the client is authorized to make requests. Kicks off the + * configured Oauth flow, if any. + * + * @returns {Promise} A promise that resolves to this client when + * authorization is complete. + */ + authorize(): Promise; - /** - * Configure the Client to use a user's API Key and then authenticate - * through HTTP Basic Authentication. This should only be done for testing, - * as requests using Oauth can provide more security, higher rate limits, and - * more features. - * @param {String} apiKey The Asana Api Key of the user - * @return {Client} this - * @param apiKey - * @return - */ - useBasicAuth(apiKey: string): this; + /** + * Configure the Client to use a user's API Key and then authenticate + * through HTTP Basic Authentication. This should only be done for testing, + * as requests using Oauth can provide more security, higher rate limits, and + * more features. + * @param {String} apiKey The Asana Api Key of the user + * @return {Client} this + * @param apiKey + * @return + */ + useBasicAuth(apiKey: string): this; - /** - * Configure the client to authenticate using a Personal Access Token. - * @param {String} accessToken The Personal Access Token to use for - * authenticating requests. - * @return {Client} this - * @param accessToken - * @return - */ - useAccessToken(accessToken: string): this; + /** + * Configure the client to authenticate using a Personal Access Token. + * @param {String} accessToken The Personal Access Token to use for + * authenticating requests. + * @return {Client} this + * @param accessToken + * @return + */ + useAccessToken(accessToken: string): this; - /** - * Configure the client to authenticate via Oauth. Credentials can be - * supplied, or they can be obtained by running an Oauth flow. - * @param {Object} options Options for Oauth. Includes any options for - * the selected flow. - * @option {Function} [flowType] Type of OauthFlow to use to obtain user - * authorization. Defaults to autodetect based on environment. - * @option {Object} [credentials] Credentials to use; no flow required to - * obtain authorization. This object should at a minimum contain an - * `access_token` string field. - * @return {Client} this - * @param options - * @return - */ - useOauth(options?: auth.OauthAuthenticatorOptions): this; + /** + * Configure the client to authenticate via Oauth. Credentials can be + * supplied, or they can be obtained by running an Oauth flow. + * @param {Object} options Options for Oauth. Includes any options for + * the selected flow. + * @option {Function} [flowType] Type of OauthFlow to use to obtain user + * authorization. Defaults to autodetect based on environment. + * @option {Object} [credentials] Credentials to use; no flow required to + * obtain authorization. This object should at a minimum contain an + * `access_token` string field. + * @return {Client} this + * @param options + * @return + */ + useOauth(options?: auth.OauthAuthenticatorOptions): this; - /** - * The internal dispatcher. This is mostly used by the resources but provided - * for custom requests to the API or API features that have not yet been added - * to the client. - * @type {Dispatcher} - */ - dispatcher: Dispatcher; - /** - * An instance of the Attachments resource. - * @type {Attachments} - */ - attachments: resources.Attachments; - /** - * An instance of the Events resource. - * @type {Events} - */ - events: resources.Events; - /** - * An instance of the Projects resource. - * @type {Projects} - */ - projects: resources.Projects; - /** - * An instance of the Stories resource. - * @type {Stories} - */ - stories: resources.Stories; - /** - * An instance of the Tags resource. - * @type {Tags} - */ - tags: resources.Tags; - /** - * An instance of the Tasks resource. - * @type {Tasks} - */ - tasks: resources.Tasks; - /** - * An instance of the Teams resource. - * @type {Teams} - */ - teams: resources.Teams; - /** - * An instance of the Users resource. - * @type {Users} - */ - users: resources.Users; - /** - * An instance of the Workspaces resource. - * @type {Workspaces} - */ - workspaces: resources.Workspaces; - /** - * Store off Oauth info. - */ - app: auth.App; + /** + * The internal dispatcher. This is mostly used by the resources but provided + * for custom requests to the API or API features that have not yet been added + * to the client. + * @type {Dispatcher} + */ + dispatcher: Dispatcher; + /** + * An instance of the Attachments resource. + * @type {Attachments} + */ + attachments: resources.Attachments; + /** + * An instance of the Events resource. + * @type {Events} + */ + events: resources.Events; + /** + * An instance of the Projects resource. + * @type {Projects} + */ + projects: resources.Projects; + /** + * An instance of the Stories resource. + * @type {Stories} + */ + stories: resources.Stories; + /** + * An instance of the Tags resource. + * @type {Tags} + */ + tags: resources.Tags; + /** + * An instance of the Tasks resource. + * @type {Tasks} + */ + tasks: resources.Tasks; + /** + * An instance of the Teams resource. + * @type {Teams} + */ + teams: resources.Teams; + /** + * An instance of the Users resource. + * @type {Users} + */ + users: resources.Users; + /** + * An instance of the Workspaces resource. + * @type {Workspaces} + */ + workspaces: resources.Workspaces; + /** + * Store off Oauth info. + */ + app: auth.App; } var Dispatcher: DispatcherStatic; interface DispatcherStatic { - /** - * Creates a dispatcher which will act as a basic wrapper for making HTTP - * requests to the API, and handle authentication. - * @class - * @classdesc A HTTP wrapper for the Asana API - * @param {Object} options for default behavior of the Dispatcher - * @option {Authenticator} [authenticator] Object to use for authentication. - * Can also be set later with `setAuthenticator`. - * @option {String} [retryOnRateLimit] Automatically handle `RateLimitEnforced` - * errors by sleeping and retrying after the waiting period. - * @option {Function} [handleUnauthorized] Automatically handle - * `NoAuthorization` with the callback. If the callback returns `true` - * (or a promise resolving to `true), will retry the request. - * @option {String} [asanaBaseUrl] Base URL for Asana, for debugging - * @option {Number} [requestTimeout] Timeout (in milliseconds) to wait for the - * request to finish. - */ - new (options?: DispatcherOptions): Dispatcher; + /** + * Creates a dispatcher which will act as a basic wrapper for making HTTP + * requests to the API, and handle authentication. + * @class + * @classdesc A HTTP wrapper for the Asana API + * @param {Object} options for default behavior of the Dispatcher + * @option {Authenticator} [authenticator] Object to use for authentication. + * Can also be set later with `setAuthenticator`. + * @option {String} [retryOnRateLimit] Automatically handle `RateLimitEnforced` + * errors by sleeping and retrying after the waiting period. + * @option {Function} [handleUnauthorized] Automatically handle + * `NoAuthorization` with the callback. If the callback returns `true` + * (or a promise resolving to `true), will retry the request. + * @option {String} [asanaBaseUrl] Base URL for Asana, for debugging + * @option {Number} [requestTimeout] Timeout (in milliseconds) to wait for the + * request to finish. + */ + new (options?: DispatcherOptions): Dispatcher; - /** - * Default handler for requests that are considered unauthorized. - * Requests that the authenticator try to refresh its credentials if - * possible. - * @return {Promise} True iff refresh was successful, false if not. - * @return - */ - maybeReauthorize(): Promise; + /** + * Default handler for requests that are considered unauthorized. + * Requests that the authenticator try to refresh its credentials if + * possible. + * @return {Promise} True iff refresh was successful, false if not. + * @return + */ + maybeReauthorize(): Promise; - /** - * The relative API path for the current version of the Asana API. - * @type {String} - */ - API_PATH : string; + /** + * The relative API path for the current version of the Asana API. + * @type {String} + */ + API_PATH: string; } interface DispatcherOptions { - authenticator?: auth.Authenticator; - retryOnRateLimit?: boolean; - handleUnauthorized?: () => boolean|Promise; - requestTimeout?: string; + authenticator?: auth.Authenticator; + retryOnRateLimit?: boolean; + handleUnauthorized?: () => boolean | Promise; + requestTimeout?: string; } interface Dispatcher { - /** - * Creates an Asana API Url by concatenating the ROOT_URL with path provided. - * @param {String} path The path - * @return {String} The url - * @param path - * @return - */ - url(path: string): string; - - /** - * Configure the authentication mechanism to use. - * @returns {Dispatcher} this - * @param authenticator - * @return - */ - setAuthenticator(authenticator: auth.Authenticator): this; - - /** - * Ensure the dispatcher is authorized to make requests. Call this before - * making any API requests. - * - * @returns {Promise} Resolves when the dispatcher is authorized, rejected if - * there was a problem authorizing. - * @return - */ - authorize(): Promise; - - /** - * Dispatches a request to the Asana API. The request parameters are passed to - * the request module. - * @param {Object} params The params for request - * @param {Object} [dispatchOptions] Options for handling request/response - * @return {Promise} The response for the request - * @param params - * @param dispatchOptions? - * @return - */ - dispatch(params: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a GET request to the Asana API. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - * @param path - * @param query? - * @param dispatchOptions? - * @return - */ - get(path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a POST request to the Asana API. - * @param {String} path The path of the API - * @param {Object} data The data to be sent - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - * @param path - * @param data - * @param dispatchOptions? - * @return - */ - post(path: string, data: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a PUT request to the Asana API. - * @param {String} path The path of the API - * @param {Object} data The data to be sent - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - * @param path - * @param data - * @param dispatchOptions? - * @return - */ - put(path: string, data: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a DELETE request to the Asana API. - * @param {String} path The path of the API - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `dispatch`. - * @return {Promise} The response for the request - * @param path - * @param dispatchOptions? - * @return - */ - delete(path: string, dispatchOptions?: any): Promise; - - /** - * The base URL for Asana - * @type {String} - */ - asanaBaseUrl : string; - - /** - * Whether requests should be automatically retried if rate limited. - * @type {Boolean} - */ - retryOnRateLimit : boolean; - - /** - * Handler for unauthorized requests which may seek reauthorization. - * Default behavior is available if configured with an Oauth authenticator - * that has a refresh token, and will refresh the current access token. - * @type {Function} - */ - handleUnauthorized : () => boolean|Promise; - - /** - * The amount of time in milliseconds to wait for a request to finish. - * @type {Number} - */ - requestTimeout : number; - } - - namespace auth { - var BasicAuthenticator: BasicAuthenticatorStatic; - - interface BasicAuthenticatorStatic { /** - * @param apiKey - */ - new (apiKey: string): BasicAuthenticator; - } - - interface BasicAuthenticator extends Authenticator { - /** - * @param {Object} request The request to modify, for the `request` library. - * @return {Object} The `request` parameter, modified to include authentication - * information using the stored credentials. - * @param request + * Creates an Asana API Url by concatenating the ROOT_URL with path provided. + * @param {String} path The path + * @return {String} The url + * @param path * @return */ - authenticateRequest(request: BasicAuthenticatorRequest): BasicAuthenticatorRequest; - } + url(path: string): string; - interface BasicAuthenticatorRequest { - auth : { - username : string; - password : string; - } - } - - var OauthAuthenticator: OauthAuthenticatorStatic; - - interface OauthAuthenticatorStatic { /** - * Creates an authenticator that uses Oauth for authentication. + * Configure the authentication mechanism to use. + * @returns {Dispatcher} this + * @param authenticator + * @return + */ + setAuthenticator(authenticator: auth.Authenticator): this; + + /** + * Ensure the dispatcher is authorized to make requests. Call this before + * making any API requests. * - * @param {Object} options Configure the authenticator; must specify one - * of `flow` or `credentials`. - * @option {App} app The app being authenticated for. - * @option {OauthFlow} [flow] The flow to use to get credentials - * when needed. - * @option {String|Object} [credentials] Initial credentials to use. This can - * be either the object returned from an access token request (which - * contains the token and some other metadata) or just the `access_token` - * field. - * @constructor - */ - new (options: OauthAuthenticatorOptions): OauthAuthenticator; - } - - interface OauthAuthenticatorOptions { - flowType?: auth.FlowType; - credentials?: Credentials|string; - } - - interface Credentials { - access_token?: string; - refresh_token?: string; - } - - interface OauthAuthenticator extends Authenticator { - /** - * @param {Object} request The request to modify, for the `request` library. - * @return {Object} The `request` parameter, modified to include authentication - * information using the stored credentials. - * @param request - * @return - */ - authenticateRequest(request: OauthAuthenticatorRequest): OauthAuthenticatorRequest; - } - - interface OauthAuthenticatorRequest { - /** - * When browserify-d, the `auth` component of the `request` library - * doesn't work so well, so we just manually set the bearer token instead. - */ - headers : { - Authorization : string; - } - } - - /** - * A layer to abstract the differences between using different types of - * authentication (Oauth vs. Basic). The Authenticator is responsible for - * establishing credentials and applying them to outgoing requests. - * @constructor - */ - interface Authenticator { - /** - * Establishes credentials. - * - * @return {Promise} Resolves when initial credentials have been - * completed and `authenticateRequest` calls can expect to succeed. - * @return - */ - establishCredentials(): Promise; - - /** - * Attempts to refresh credentials, if possible, given the current credentials. - * - * @return {Promise} Resolves to `true` if credentials have been successfully - * established and `authenticateRequests` can expect to succeed, else - * resolves to `false`. - * @return - */ - refreshCredentials(): Promise; - } - - var App: AppStatic; - - interface AppStatic { - /** - * An abstraction around an App used with Asana. - * - * @options {Object} Options to construct the app - * @option {String} clientId The ID of the app - * @option {String} [clientSecret] The secret key, if available here - * @option {String} [redirectUri] The default redirect URI - * @option {String} [scope] Scope to use, supports `default` and `scim` - * @option {String} [asanaBaseUrl] Base URL to use for Asana, for debugging - * @constructor - */ - new (options: AppOptions): App; - } - - interface AppOptions extends AsanaAuthorizeUrlOptions { - clientId?: string|number; - clientSecret?: string; - scope?: string; - } - - interface App { - /** - * @param {Object} options Overrides to the app's defaults - * @option {String} asanaBaseUrl - * @option {String} redirectUri - * @returns {String} The URL used to authorize a user for the app. - * @param options - * @return - */ - asanaAuthorizeUrl(options?: AsanaAuthorizeUrlOptions): string; - - /** - * @param {Object} options Overrides to the app's defaults - * @option {String} asanaBaseUrl - * @option {String} redirectUri - * @returns {String} The URL used to acquire an access token. - * @param options - * @return - */ - asanaTokenUrl(options?: AsanaAuthorizeUrlOptions): string; - - /** - * @param {String} code An authorization code obtained via `asanaAuthorizeUrl`. - * @param {Object} options Overrides to the app's defaults - * @option {String} asanaBaseUrl - * @option {String} redirectUri - * @return {Promise} The token, which will include the `access_token` - * used for API access, as well as a `refresh_token` which can be stored - * to get a new access token without going through the flow again. - * @param code - * @param options - * @return - */ - accessTokenFromCode(code: string, options?: AsanaAuthorizeUrlOptions): Promise; - - /** - * @param {String} refreshToken A refresh token obtained via Oauth. - * @param {Object} options Overrides to the app's defaults - * @option {String} asanaBaseUrl - * @option {String} redirectUri - * @return {Promise} The token, which will include the `access_token` - * used for API access. - * @param refreshToken - * @param options - * @return - */ - accessTokenFromRefreshToken(refreshToken: string, options: AsanaAuthorizeUrlOptions): Promise; - - scope : string; - - asanaBaseUrl : string; - } - - interface AsanaAuthorizeUrlOptions { - redirectUri?: string; - asanaBaseUrl?: string; - } - - var OauthError: OauthErrorStatic; - - interface OauthErrorStatic { - /** - * @param options {Object} A data blob parsed from a query string or JSON - * response from the Asana API - * @option {String} error The string code identifying the error. - * @option {String} [error_uri] A link to help and information about the error. - * @option {String} [error_description] A description of the error. - * @constructor - */ - new (options: OauthErrorOptions): OauthError; - } - - interface OauthErrorOptions { - error?: string; - error_uri?: string; - error_description?: string; - } - - interface OauthError extends Error { - } - - /** - * Auto-detects the type of Oauth flow to use that's appropriate to the - * environment. - * - * @returns {Function|null} The type of Oauth flow to use, or null if no - * appropriate type could be determined. - * @param env - * @return - */ - function autoDetect(env: any): Function; - - var RedirectFlow: RedirectFlowStatic; - - interface RedirectFlowStatic extends FlowType { - /** - * An Oauth flow that runs in the browser and requests user authorization by - * redirecting to an authorization page on Asana, and redirecting back with - * the credentials. - * @param {Object} options See `BaseBrowserFlow` for options. - * @constructor - */ - new (options: any): RedirectFlow; - } - - interface RedirectFlow extends BaseBrowserFlow { - } - - var PopupFlow: PopupFlowStatic; - - interface PopupFlowStatic extends FlowType { - /** - * An Oauth flow that runs in the browser and requests user authorization by - * popping up a window and prompting the user. - * @param {Object} options See `BaseBrowserFlow` for options. - * @constructor - */ - new (options: any): PopupFlow; - } - - interface PopupFlow extends BaseBrowserFlow { - /** - * @param popupWidth - * @param popupHeight - */ - _popupParams(popupWidth: number, popupHeight: number): void; - - runReceiver(): void; - } - - var NativeFlow: NativeFlowStatic; - - interface NativeFlowStatic extends FlowType { - /** - * An Oauth flow that can be run from the console or an app that does - * not have the ability to open and manage a browser on its own. - * @param {Object} options - * @option {App} app App to authenticate for - * @option {String function(String)} [instructions] Function returning the - * instructions to output to the user. Passed the authorize url. - * @option {String function()} [prompt] String to output immediately before - * waiting for a line from stdin. - * @constructor - */ - new (options: any): NativeFlow; - } - - interface NativeFlow extends Flow { - /** - * Run the Oauth flow, prompting the user to go to the authorization URL - * and enter the code it displays when finished. - * - * @return {Promise} The access token object, which will include - * `access_token` and `refresh_token`. - */ - run(): void; - - /** - * @param {String} code An authorization code obtained via `asanaAuthorizeUrl`. - * @return {Promise} The token, which will include the `access_token` - * used for API access, as well as a `refresh_token` which can be stored - * to get a new access token without going through the flow again. - * @param code - */ - accessToken(code: string): void; - - /** - * @return {Promise} The access token, which will include a refresh token - * that can be stored in the future to create a client without going - * through the Oauth flow. - * @param url - * @return - */ - promptForCode(url: string): any; - } - - var ChromeExtensionFlow: ChromeExtensionFlowStatic; - - interface ChromeExtensionFlowStatic extends FlowType { - /** - * An Oauth flow that runs in a Chrome browser extension and requests user - * authorization by opening a temporary tab to prompt the user. - * @param {Object} options See `BaseBrowserFlow` for options, plus the below: - * @options {String} [receiverPath] Full path and filename from the base - * directory of the extension to the receiver page. This is an HTML file - * that has been made web-accessible, and that calls the receiver method - * `Asana.auth.ChromeExtensionFlow.runReceiver();`. - * @constructor - */ - new (options: any): ChromeExtensionFlow; - } - - interface ChromeExtensionFlow extends BaseBrowserFlow { - /** - * Runs the receiver code to send the Oauth result to the requesting tab. - */ - runReceiver(): void; - } - - var BaseBrowserFlow: BaseBrowserFlowStatic; - - interface BaseBrowserFlowStatic extends FlowType { - /** - * A base class for any flow that runs in the browser. All subclasses use the - * "implicit grant" flow to authenticate via the browser. - * @param {Object} options - * @option {App} app The app this flow is for - * @option {String} [redirectUri] The URL that Asana should redirect to once - * user authorization is complete. Defaults to the URL configured in - * the app, and if none then the current page URL. - * @constructor - */ - new (options: any): BaseBrowserFlow; - } - - interface BaseBrowserFlow extends Flow { - /** - * @param {String} authUrl The URL the user should be navigated to in order - * to authorize the app. - * @param {String} state The unique state generated for this auth request. - * @return {Promise} Resolved when authorization has successfully started, - * i.e. the user has been navigated to a page requesting authorization. - * @param authUrl - * @param state - * @return - */ - startAuthorization(authUrl: string, state: string): any; - - /** - * @return {Promise} Credentials returned from Oauth. - * @param state - */ - finishAuthorization(state: string): void; - - /** - * @return {String} The URL to redirect to that will receive the - * @return - */ - receiverUrl(): string; - - /** - * @return {String} The URL to redirect to that will receive the - * @return - */ - asanaBaseUrl(): string; - - /** - * @returns {String} Generate a new unique state parameter for a request. - * @return - */ - getStateParam(): string; - } - - interface FlowType { - new (options: any): Flow; - } - - interface Flow { - /** - * @returns {String} The URL used to authorize the user for the app. - * @return - */ - authorizeUrl(): string; - - /** - * Run the appropriate parts of the Oauth flow, attempting to establish user - * authorization. - * @returns {Promise} A promise that resolves to the Oauth credentials. - */ - run(): void; - } - } - - namespace errors { - class AsanaError extends Error { - /** - * @param message - * @return - */ - constructor(message: any); - - code: number; - value: any; - } - - class Forbidden extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - - - class InvalidRequest extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - - class NoAuthorization extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - - class NotFound extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - - class RateLimitEnforced extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - - class ServerError extends AsanaError { - /** - * @param value - * @return - */ - constructor(value: any); - } - } - - namespace resources { - interface AttachmentsStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Attachments; - } - - namespace Attachments { - interface Type extends Resource { - created_at: string; - permanent_url: string; - download_url: string; - view_url: string; - host: string; - parent: Resource; - } - } - - var Attachments: AttachmentsStatic; - - /** - * An _attachment_ object represents any file attached to a task in Asana, - * whether it's an uploaded file or one associated via a third-party service - * such as Dropbox or Google Drive. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Attachments extends Resource { - /** - * * Returns the full record for a single attachment. - * * @param {Number} attachment Globally unique identifier for the attachment. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param attachment - * @param params? - * @param dispatchOptions? - * @return - */ - findById(attachment: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the compact records for all attachments on the task. - * * @param {Number} task Globally unique identifier for the task. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - findByTask(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - } - - interface EventsStatic { - /** - * @param dispatcher - * @return - */ - new (dispatcher: Dispatcher): Events; - } - - var Events: EventsStatic; - - /** - * An _event_ is an object representing a change to a resource that was observed - * by an event subscription. - * - * In general, requesting events on a resource is faster and subject to higher - * rate limits than requesting the resource itself. Additionally, change events - * bubble up - listening to events on a project would include when stories are - * added to tasks in the project, even on subtasks. - * - * Establish an initial sync token by making a request with no sync token. - * The response will be a `412` error - the same as if the sync token had - * expired. - * - * Subsequent requests should always provide the sync token from the immediately - * preceding call. - * - * Sync tokens may not be valid if you attempt to go 'backward' in the history - * by requesting previous tokens, though re-requesting the current sync token - * is generally safe, and will always return the same results. - * - * When you receive a `412 Precondition Failed` error, it means that the - * sync token is either invalid or expired. If you are attempting to keep a set - * of data in sync, this signals you may need to re-crawl the data. - * - * Sync tokens always expire after 24 hours, but may expire sooner, depending on - * load on the service. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Events extends Resource { } - - interface ProjectsStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Projects; - } - - namespace Projects { - interface Type extends Resource { - created_at: string; - modified_at: string; - due_date: string; - current_status: Status; - public: boolean; - archived: boolean; - notes: string; - color: string; - workspace: Resource; - team: Resource; - members: Resource[]; - followers: Resource[]; - } - - interface CreateParams { - name?: string; - team?: number; - public?: boolean; - due_date: string; - notes?: string; - color?: string; - } - - interface FollowersParams { - followers: (number|string)[]; - } - - interface MembersParams { - members: (number|string)[]; - } - - interface Status { - color: string; - text: string; - html_text: string; - modified_at: string; - author: Resource; - } - - interface FindAllParams extends PaginationParams { - team?: number; - archived?: boolean; - } - - interface FindByParams extends PaginationParams { - archived?: boolean; - } - } - - var Projects: ProjectsStatic; - - /** - * A _project_ represents a prioritized list of tasks in Asana. It exists in a - * single workspace or organization and is accessible to a subset of users in - * that workspace or organization, depending on its permissions. - * - * Projects in organizations are shared with a single team. You cannot currently - * change the team of a project via the API. Non-organization workspaces do not - * have teams and so you should not specify the team of project in a - * regular workspace. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Projects extends Resource { - /** - * * Creates a new project in a workspace or team. - * * - * * Every project is required to be created in a specific workspace or - * * organization, and this cannot be changed once set. Note that you can use - * * the `workspace` parameter regardless of whether or not it is an - * * organization. - * * - * * If the workspace for your project _is_ an organization, you must also - * * supply a `team` to share the project with. - * * - * * Returns the full record of the newly created project. - * * @param {Object} data Data for the request - * * @param {String} data.workspace The workspace or organization to create the project in. - * * @param {String} [data.team] If creating in an organization, the specific team to create the - * * project in. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param data - * @param dispatchOptions? - * @return - */ - create(data: Projects.CreateParams & { workspace: number }, dispatchOptions?: any): Promise; - - /** - * * If the workspace for your project _is_ an organization, you must also - * * supply a `team` to share the project with. - * * - * * Returns the full record of the newly created project. - * * @param {Number} workspace The workspace or organization to create the project in. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param data - * @param dispatchOptions? - * @return - */ - createInWorkspace(workspace: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; - - /** - * * Creates a project shared with the given team. - * * - * * Returns the full record of the newly created project. - * * @param {Number} team The team to create the project in. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param team - * @param data - * @param dispatchOptions? - * @return - */ - createInTeam(team: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; - - /** - * * Returns the complete project record for a single project. - * * @param {Number} project The project to get. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param project - * @param params? - * @param dispatchOptions? - * @return - */ - findById(project: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * A specific, existing project can be updated by making a PUT request on the - * * URL for that project. Only the fields provided in the `data` block will be - * * updated; any unspecified fields will remain unchanged. - * * - * * When using this method, it is best to specify only those fields you wish - * * to change, or else you may overwrite changes made by another user since - * * you last retrieved the task. - * * - * * Returns the complete updated project record. - * * @param {Number} project The project to update. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param data - * @param dispatchOptions? - * @return - */ - update(project: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; - - /** - * * A specific, existing project can be deleted by making a DELETE request - * * on the URL for that project. - * * - * * Returns an empty data record. - * * @param {Number} project The project to delete. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param dispatchOptions? - * @return - */ - delete(project: number, dispatchOptions?: any): Promise; - - /** - * * Returns the compact project records for some filtered set of projects. - * * Use one or more of the parameters provided to filter the projects returned. - * * @param {Object} [params] Parameters for the request - * * @param {String} [params.workspace] The workspace or organization to filter projects on. - * * @param {String} [params.team] The team to filter projects on. - * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of - * * this parameter. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param params? - * @param dispatchOptions? - * @return - */ - findAll(params?: Projects.FindAllParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact project records for all projects in the workspace. - * * @param {Number} workspace The workspace or organization to find projects in. - * * @param {Object} [params] Parameters for the request - * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of - * * this parameter. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param params? - * @param dispatchOptions? - * @return - */ - findByWorkspace(workspace: number, params?: Projects.FindByParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact project records for all projects in the team. - * * @param {Number} team The team to find projects in. - * * @param {Object} [params] Parameters for the request - * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of - * * this parameter. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param team - * @param params? - * @param dispatchOptions? - * @return - */ - findByTeam(team: number, params?: Projects.FindByParams, dispatchOptions?: any): Promise>; - - /** - * * Returns compact records for all sections in the specified project. - * * @param {Number} project The project to get sections from. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param params? - * @param dispatchOptions? - * @return - */ - sections(project: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact task records for all tasks within the given project, - * * ordered by their priority within the project. Tasks can exist in more than one project at a time. - * * @param {Number} project The project in which to search for tasks. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param params? - * @param dispatchOptions? - * @return - */ - tasks(project: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Adds the specified list of users as followers to the project. Followers are a subset of members, therefore if - * * the users are not already members of the project they will also become members as a result of this operation. - * * Returns the updated project record. - * * @param {Number} project The project to add followers to. - * * @param {Object} data Data for the request - * * @param {Array} data.followers An array of followers to add to the project. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param data - * @param dispatchOptions? - * @return - */ - addFollowers(project: number, data: Projects.FollowersParams, dispatchOptions?: any): Promise; - - /** - * * Removes the specified list of users from following the project, this will not affect project membership status. - * * Returns the updated project record. - * * @param {Number} project The project to remove followers from. - * * @param {Object} data Data for the request - * * @param {Array} data.followers An array of followers to remove from the project. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param data - * @param dispatchOptions? - * @return - */ - removeFollowers(project: number, data: Projects.FollowersParams, dispatchOptions?: any): Promise; - - /** - * * Adds the specified list of users as members of the project. Returns the updated project record. - * * @param {Number} project The project to add members to. - * * @param {Object} data Data for the request - * * @param {Array} data.members An array of members to add to the project. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param data - * @param dispatchOptions? - * @return - */ - addMembers(project: number, data: Projects.MembersParams, dispatchOptions?: any): Promise; - - /** - * * Removes the specified list of members from the project. Returns the updated project record. - * * @param {Number} project The project to remove members from. - * * @param {Object} data Data for the request - * * @param {Array} data.members An array of members to remove from the project. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param project - * @param data - * @param dispatchOptions? - * @return - */ - removeMembers(project: number, data: Projects.MembersParams, dispatchOptions?: any): Promise; - } - - interface StoriesStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Stories; - } - - namespace Stories { - interface ShortType extends Resource { - created_at: string; - created_by: Resource; - type: string; - text: string; - } - - interface Type extends ShortType { - html_text: string; - source: string; - target: Resource; - hearts: Type[]; - } - } - - var Stories: StoriesStatic; - - /** - * A _story_ represents an activity associated with an object in the Asana - * system. Stories are generated by the system whenever users take actions such - * as creating or assigning tasks, or moving tasks between projects. _Comments_ - * are also a form of user-generated story. - * - * Stories are a form of history in the system, and as such they are read-only. - * Once generated, it is not possible to modify a story. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Stories extends Resource { - /** - * * Returns the compact records for all stories on the task. - * * @param {Number} task Globally unique identifier for the task. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - findByTask(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the full record for a single story. - * * @param {Number} story Globally unique identifier for the story. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param story - * @param params? - * @param dispatchOptions? - * @return - */ - findById(story: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Adds a comment to a task. The comment will be authored by the - * * currently authenticated user, and timestamped when the server receives - * * the request. - * * - * * Returns the full record for the new story added to the task. - * * @param {Number} task Globally unique identifier for the task. - * * @param {Object} data Data for the request - * * @param {String} data.text The plain text of the comment to add. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - createOnTask(task: number, data: any, dispatchOptions?: any): Promise>; - } - - interface TagsStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Tags; - } - - namespace Tags { - interface Type extends Resource { - created_at: string; - notes: string; - workspace: Resource; - color: string; - followers: Resource[]; - } - - interface FindAllParams extends PaginationParams { - team?: number; - archived?: boolean; - } - } - - var Tags: TagsStatic; - - /** - * A _tag_ is a label that can be attached to any task in Asana. It exists in a - * single workspace or organization. - * - * Tags have some metadata associated with them, but it is possible that we will - * simplify them in the future so it is not encouraged to rely too heavily on it. - * Unlike projects, tags do not provide any ordering on the tasks they - * are associated with. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Tags extends Resource { - /** - * * Creates a new tag in a workspace or organization. - * * - * * Every tag is required to be created in a specific workspace or - * * organization, and this cannot be changed once set. Note that you can use - * * the `workspace` parameter regardless of whether or not it is an - * * organization. - * * - * * Returns the full record of the newly created tag. - * * @param {Object} data Data for the request - * * @param {String} data.workspace The workspace or organization to create the tag in. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param data - * @param dispatchOptions? - * @return - */ - create(data: Tags.Type & { workspace: string }, dispatchOptions?: any): Promise; - - /** - * * Creates a new tag in a workspace or organization. - * * - * * Every tag is required to be created in a specific workspace or - * * organization, and this cannot be changed once set. Note that you can use - * * the `workspace` parameter regardless of whether or not it is an - * * organization. - * * - * * Returns the full record of the newly created tag. - * * @param {Number} workspace The workspace or organization to create the tag in. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param data - * @param dispatchOptions? - * @return - */ - createInWorkspace(workspace: number, data: Tags.Type, dispatchOptions?: any): Promise; - - /** - * * Returns the complete tag record for a single tag. - * * @param {Number} tag The tag to get. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param tag - * @param params? - * @param dispatchOptions? - * @return - */ - findById(tag: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Updates the properties of a tag. Only the fields provided in the `data` - * * block will be updated; any unspecified fields will remain unchanged. - * * - * * When using this method, it is best to specify only those fields you wish - * * to change, or else you may overwrite changes made by another user since - * * you last retrieved the task. - * * - * * Returns the complete updated tag record. - * * @param {Number} tag The tag to update. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param tag - * @param data - * @param dispatchOptions? - * @return - */ - update(tag: number, data: Tags.Type, dispatchOptions?: any): Promise; - - /** - * * A specific, existing tag can be deleted by making a DELETE request - * * on the URL for that tag. - * * - * * Returns an empty data record. - * * @param {Number} tag The tag to delete. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param tag - * @param dispatchOptions? - * @return - */ - delete(tag: number, dispatchOptions?: any): Promise; - - /** - * * Returns the compact tag records for some filtered set of tags. - * * Use one or more of the parameters provided to filter the tags returned. - * * @param {Object} [params] Parameters for the request - * * @param {String} [params.workspace] The workspace or organization to filter tags on. - * * @param {String} [params.team] The team to filter tags on. - * * @param {Boolean} [params.archived] Only return tags whose `archived` field takes on the value of - * * this parameter. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param params? - * @param dispatchOptions? - * @return - */ - findAll(params?: Tags.FindAllParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact tag records for all tags in the workspace. - * * @param {Number} workspace The workspace or organization to find tags in. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param params? - * @param dispatchOptions? - * @return - */ - findByWorkspace(workspace: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact task records for all tasks with the given tag. - * * Tasks can have more than one tag at a time. - * * @param {Number} tag The tag to fetch tasks from. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param tag - * @param params? - * @param dispatchOptions? - * @return - */ - getTasksWithTag(tag: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - } - - interface TasksStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Tasks; - } - - namespace Tasks { - interface Type extends Resource { - created_at: string; - modified_at: string; - completed_at: string; - completed: boolean; - due_on: string; - due_at: string; - assignee_status: string; - assignee: Resource; - notes: string; - workspace: Resource; - num_hearts: number; - hearted: boolean; - parent: Resource; - tags: Resource[]; - projects: Resource[]; - memberships: Membership[]; - followers: Resource[]; - } - - interface CreateParams { - name: string; - completed?: boolean; - hearted?: boolean; - notes?: string; - } - - interface FollowersParams { - followers: (number|string)[]; - } - - interface AddProjectParams { - project: number; - insertBefore?: number; - insertAfter?: number; - section?: number; - } - - interface RemoveProjectParams { - project: number; - } - - interface TagParams { - tag: string; - } - - interface CommentParams { - text: string; - } - - interface FindAllParams extends PaginationParams { - assignee?: number; - workspace: number; - completed_since?: string; - modified_since?: string; - } - } - - var Tasks: TasksStatic; - - /** - * The _task_ is the basic object around which many operations in Asana are - * centered. In the Asana application, multiple tasks populate the middle pane - * according to some view parameters, and the set of selected tasks determines - * the more detailed information presented in the details pane. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Tasks extends Resource { - /** - * * Creating a new task is as easy as POSTing to the `/tasks` endpoint - * * with a data block containing the fields you'd like to set on the task. - * * Any unspecified fields will take on default values. - * * - * * Every task is required to be created in a specific workspace, and this - * * workspace cannot be changed once set. The workspace need not be set - * * explicitly if you specify a `project` or a `parent` task instead. - * * @param {Object} data Data for the request - * * @param {Number} [data.workspace] The workspace to create a task in. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param data - * @param dispatchOptions? - * @return - */ - create(data: Tasks.CreateParams & { workspace: string }, dispatchOptions?: any): Promise; - - /** - * * Creating a new task is as easy as POSTing to the `/tasks` endpoint - * * with a data block containing the fields you'd like to set on the task. - * * Any unspecified fields will take on default values. - * * - * * Every task is required to be created in a specific workspace, and this - * * workspace cannot be changed once set. The workspace need not be set - * * explicitly if you specify a `project` or a `parent` task instead. - * * @param {Number} workspace The workspace to create a task in. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param data - * @param dispatchOptions? - * @return - */ - createInWorkspace(workspace: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; - - /** - * * Returns the complete task record for a single task. - * * @param {Number} task The task to get. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - findById(task: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * A specific, existing task can be updated by making a PUT request on the - * * URL for that task. Only the fields provided in the `data` block will be - * * updated; any unspecified fields will remain unchanged. - * * - * * When using this method, it is best to specify only those fields you wish - * * to change, or else you may overwrite changes made by another user since - * * you last retrieved the task. - * * - * * Returns the complete updated task record. - * * @param {Number} task The task to update. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - update(task: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; - - /** - * * A specific, existing task can be deleted by making a DELETE request on the - * * URL for that task. Deleted tasks go into the "trash" of the user making - * * the delete request. Tasks can be recovered from the trash within a period - * * of 30 days; afterward they are completely removed from the system. - * * - * * Returns an empty data record. - * * @param {Number} task The task to delete. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param dispatchOptions? - * @return - */ - delete(task: number, dispatchOptions?: any): Promise; - - /** - * * Returns the compact task records for all tasks within the given project, - * * ordered by their priority within the project. - * * @param {Number} projectId The project in which to search for tasks. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param projectId - * @param params? - * @param dispatchOptions? - * @return - */ - findByProject(projectId: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact task records for all tasks with the given tag. - * * @param {Number} tag The tag in which to search for tasks. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param tag - * @param params? - * @param dispatchOptions? - * @return - */ - findByTag(tag: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Returns the compact task records for some filtered set of tasks. Use one - * * or more of the parameters provided to filter the tasks returned. - * * @param {Object} [params] Parameters for the request - * * @param {Number} [params.assignee] The assignee to filter tasks on. - * * @param {Number} [params.workspace] The workspace or organization to filter tasks on. - * * @param {Number} [params.completed_since] Only return tasks that are either incomplete or that have been - * * completed since this time. - * * @param {Number} [params.modified_since] Only return tasks that have been modified since the given time. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param params? - * @param dispatchOptions? - * @return - */ - findAll(params?: Tasks.FindAllParams, dispatchOptions?: any): Promise>; - - /** - * * Adds each of the specified followers to the task, if they are not already - * * following. Returns the complete, updated record for the affected task. - * * @param {Number} task The task to add followers to. - * * @param {Object} data Data for the request - * * @param {Array} data.followers An array of followers to add to the task. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - addFollowers(task: number, data: Tasks.FollowersParams, dispatchOptions?: any): Promise; - - /** - * * Removes each of the specified followers from the task if they are - * * following. Returns the complete, updated record for the affected task. - * * @param {Number} task The task to remove followers from. - * * @param {Object} data Data for the request - * * @param {Array} data.followers An array of followers to remove from the task. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - removeFollowers(task: number, data: Tasks.FollowersParams, dispatchOptions?: any): Promise; - - /** - * * Returns a compact representation of all of the projects the task is in. - * * @param {Number} task The task to get projects on. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - projects(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Adds the task to the specified project, in the optional location - * * specified. If no location arguments are given, the task will be added to - * * the beginning of the project. - * * - * * `addProject` can also be used to reorder a task within a project that - * * already contains it. - * * - * * Returns an empty data block. - * * @param {Number} task The task to add to a project. - * * @param {Object} data Data for the request - * * @param {Number} data.project The project to add the task to. - * * @param {Number} [data.insertAfter] A task in the project to insert the task after, or `null` to - * * insert at the beginning of the list. - * * @param {Number} [data.insertBefore] A task in the project to insert the task before, or `null` to - * * insert at the end of the list. - * * @param {Number} [data.section] A section in the project to insert the task into. The task will be - * * inserted at the top of the section. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - addProject(task: number, data: Tasks.AddProjectParams, dispatchOptions?: any): Promise<{}>; - - /** - * * Removes the task from the specified project. The task will still exist - * * in the system, but it will not be in the project anymore. - * * - * * Returns an empty data block. - * * @param {Number} task The task to remove from a project. - * * @param {Object} data Data for the request - * * @param {Number} data.project The project to remove the task from. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - removeProject(task: number, data: Tasks.RemoveProjectParams, dispatchOptions?: any): Promise<{}>; - - /** - * * Returns a compact representation of all of the tags the task has. - * * @param {Number} task The task to get tags on. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - tags(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Adds a tag to a task. Returns an empty data block. - * * @param {Number} task The task to add a tag to. - * * @param {Object} data Data for the request - * * @param {Number} data.tag The tag to add to the task. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - addTag(task: number, data: Tasks.TagParams, dispatchOptions?: any): Promise<{}>; - - /** - * * Removes a tag from the task. Returns an empty data block. - * * @param {Number} task The task to remove a tag from. - * * @param {Object} data Data for the request - * * @param {String} data.tag The tag to remove from the task. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - removeTag(task: number, data: Tasks.TagParams, dispatchOptions?: any): Promise<{}>; - - /** - * * Returns a compact representation of all of the subtasks of a task. - * * @param {Number} task The task to get the subtasks of. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - subtasks(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Creates a new subtask and adds it to the parent task. Returns the full record - * * for the newly created subtask. - * * @param {Number} task The task to add a subtask to. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - addSubtask(task: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; - - /** - * * Returns a compact representation of all of the stories on the task. - * * @param {Number} task The task containing the stories to get. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param params? - * @param dispatchOptions? - * @return - */ - stories(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * Adds a comment to a task. The comment will be authored by the - * * currently authenticated user, and timestamped when the server receives - * * the request. - * * - * * Returns the full record for the new story added to the task. - * * @param {Number} task Globally unique identifier for the task. - * * @param {Object} data Data for the request - * * @param {String} data.text The plain text of the comment to add. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param task - * @param data - * @param dispatchOptions? - * @return - */ - addComment(task: number, data: Tasks.CommentParams, dispatchOptions?: any): Promise; - } - - interface TeamsStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Teams; - } - - namespace Teams { - interface Type extends Resource { - organization: Resource; - } - } - - var Teams: TeamsStatic; - - /** - * A _team_ is used to group related projects and people together within an - * organization. Each project in an organization is associated with a team. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Teams extends Resource { - /** - * * Returns the full record for a single team. - * * @param {Number} team Globally unique identifier for the team. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param team - * @param params? - * @param dispatchOptions? - * @return - */ - findById(team: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the compact records for all teams in the organization visible to - * * the authorized user. - * * @param {Number} organization Globally unique identifier for the workspace or organization. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param organization - * @param params? - * @param dispatchOptions? - * @return - */ - findByOrganization(organization: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the compact records for all users that are members of the team. - * * @param {Number} team Globally unique identifier for the team. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param team - * @param params? - * @param dispatchOptions? - * @return - */ - users(team: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * The user making this call must be a member of the team in order to add others. - * * The user to add must exist in the same organization as the team in order to be added. - * * The user to add can be referenced by their globally unique user ID or their email address. - * * Returns the full user record for the added user. - * * @param {Number} team Globally unique identifier for the team. - * * @param {Object} data Data for the request - * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, - * * the globally unique identifier for the user, or the keyword `me` - * * to indicate the current user making the request. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param team - * @param data - * @param dispatchOptions? - * @return - */ - addUser(team: number, data: UserParams, dispatchOptions?: any): Promise; - - /** - * * The user to remove can be referenced by their globally unique user ID or their email address. - * * Removes the user from the specified team. Returns an empty data record. - * * @param {Number} team Globally unique identifier for the team. - * * @param {Object} data Data for the request - * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, - * * the globally unique identifier for the user, or the keyword `me` - * * to indicate the current user making the request. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param team - * @param data - * @param dispatchOptions? - * @return - */ - removeUser(team: number, data: UserParams, dispatchOptions?: any): Promise; - } - - interface UsersStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Users; - } - - namespace Users { - interface FindAllParams extends PaginationParams { - workspace: number; - } - - interface Type extends Resource { - email: string; - workspaces: Resource[]; - photo: { [key: string]: string }; - } - } - - var Users: UsersStatic; - - /** - * A _user_ object represents an account in Asana that can be given access to - * various workspaces, projects, and tasks. - * - * Like other objects in the system, users are referred to by numerical IDs. - * However, the special string identifier `me` can be used anywhere - * a user ID is accepted, to refer to the current authenticated user. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Users extends Resource { - /** - * * Returns the full user record for the currently authenticated user. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param params? - * @param dispatchOptions? - * @return - */ - me(params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the full user record for the single user with the provided ID. - * * @param {Number|String} user An identifier for the user. Can be one of an email address, - * * the globally unique identifier for the user, or the keyword `me` - * * to indicate the current user making the request. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param user - * @param params? - * @param dispatchOptions? - * @return - */ - findById(user: string|number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the user records for all users in the specified workspace or - * * organization. - * * @param {Number} workspace The workspace in which to get users. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param params? - * @param dispatchOptions? + * @returns {Promise} Resolves when the dispatcher is authorized, rejected if + * there was a problem authorizing. * @return */ - findByWorkspace(workspace: number, params?: Params, dispatchOptions?: any): Promise>; + authorize(): Promise; /** - * * Returns the user records for all users in all workspaces and organizations - * * accessible to the authenticated user. Accepts an optional workspace ID - * * parameter. - * * @param {Object} [params] Parameters for the request - * * @param {Number} [params.workspace] The workspace or organization to filter users on. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API + * Dispatches a request to the Asana API. The request parameters are passed to + * the request module. + * @param {Object} params The params for request + * @param {Object} [dispatchOptions] Options for handling request/response + * @return {Promise} The response for the request * @param params * @param dispatchOptions? * @return */ - findAll(params: Users.FindAllParams, dispatchOptions?: any): Promise; - } + dispatch(params: any, dispatchOptions?: any): Promise; - /** - * **Webhooks are currently in BETA - The information here may change.** - * - * Webhooks allow an application to be notified of changes. This is in addition - * to the ability to fetch those changes directly as - * [Events](/developers/api-reference/events) - in fact, Webhooks are just a way - * to receive Events via HTTP POST at the time they occur instead of polling for - * them. For services accessible via HTTP this is often vastly more convenient, - * and if events are not too frequent can be significantly more efficient. - * - * In both cases, however, changes are represented as Event objects - refer to - * the [Events documentation](/developers/api-reference/events) for more - * information on what data these events contain. - * - * **NOTE:** While Webhooks send arrays of Event objects to their target, the - * Event objects themselves contain *only IDs*, rather than the actual resource - * they are referencing. So while a normal event you receive via GET /events - * would look like this: - * - * {\ - * "resource": {\ - * "id": 1337,\ - * "name": "My Task"\ - * },\ - * "parent": null,\ - * "created_at": "2013-08-21T18:20:37.972Z",\ - * "user": {\ - * "id": 1123,\ - * "name": "Tom Bizarro"\ - * },\ - * "action": "changed",\ - * "type": "task"\ - * } - * - * In a Webhook payload you would instead receive this: - * - * {\ - * "resource": 1337,\ - * "parent": null,\ - * "created_at": "2013-08-21T18:20:37.972Z",\ - * "user": 1123,\ - * "action": "changed",\ - * "type": "task"\ - * } - * - * Webhooks themselves contain only the information necessary to deliver the - * events to the desired target as they are generated. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - class Webhooks extends Resource { /** - * @param dispatcher + * Dispatches a GET request to the Asana API. + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `dispatch`. + * @return {Promise} The response for the request + * @param path + * @param query? + * @param dispatchOptions? + * @return */ - constructor(dispatcher: Dispatcher); + get(path: string, query?: any, dispatchOptions?: any): Promise; /** - * * Establishing a webhook is a two-part process. First, a simple HTTP POST - * * similar to any other resource creation. Since you could have multiple - * * webhooks we recommend specifying a unique local id for each target. - * * - * * Next comes the confirmation handshake. When a webhook is created, we will - * * send a test POST to the `target` with an `X-Hook-Secret` header as - * * described in the - * * [Resthooks Security documentation](http://resthooks.org/docs/security/). - * * The target must respond with a `200 OK` and a matching `X-Hook-Secret` - * * header to confirm that this webhook subscription is indeed expected. - * * - * * If you do not acknowledge the webhook's confirmation handshake it will - * * fail to setup, and you will receive an error in response to your attempt - * * to create it. This means you need to be able to receive and complete the - * * webhook *while* the POST request is in-flight. - * * @param {Number} resource A resource ID to subscribe to. The resource can be a task or project. - * * @param {String} target The URL to receive the HTTP POST. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param resource - * @param target + * Dispatches a POST request to the Asana API. + * @param {String} path The path of the API + * @param {Object} data The data to be sent + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `dispatch`. + * @return {Promise} The response for the request + * @param path * @param data * @param dispatchOptions? * @return */ - create(resource: number, target: string, data: any, dispatchOptions?: any): Promise; + post(path: string, data: any, dispatchOptions?: any): Promise; /** - * * Returns the compact representation of all webhooks your app has - * * registered for the authenticated user in the given workspace. - * * @param {Number} workspace The workspace to query for webhooks in. - * * @param {Object} [params] Parameters for the request - * * @param {Number} [params.resource] Only return webhooks for the given resource. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param params? - * @param dispatchOptions? - * @return - */ - getAll(workspace: number, params?: any, dispatchOptions?: any): Promise; - - /** - * * Returns the full record for the given webhook. - * * @param {String} webhook The webhook to get. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param webhook - * @param params? - * @param dispatchOptions? - * @return - */ - getById(webhook: string, params?: any, dispatchOptions?: any): Promise; - - /** - * * This method permanently removes a webhook. Note that it may be possible - * * to receive a request that was already in flight after deleting the - * * webhook, but no further requests will be issued. - * * @param {String} webhook The webhook to delete. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param webhook - * @param dispatchOptions? - * @return - */ - deleteById(webhook: string, dispatchOptions?: any): Promise; - } - - interface WorkspacesStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Workspaces; - } - - namespace Workspaces { - interface ShortType extends Resource { - id_organization?: boolean; - } - - interface Type extends Resource { - id_organization: boolean; - email_domains: string[]; - } - - interface TypeaheadParams { - type: string; - query?: string; - count?: number; - } - } - - var Workspaces: WorkspacesStatic; - - /** - * A _workspace_ is the highest-level organizational unit in Asana. All projects - * and tasks have an associated workspace. - * - * An _organization_ is a special kind of workspace that represents a company. - * In an organization, you can group your projects into teams. You can read - * more about how organizations work on the Asana Guide. - * To tell if your workspace is an organization or not, check its - * `is_organization` property. - * - * Over time, we intend to migrate most workspaces into organizations and to - * release more organization-specific functionality. We may eventually deprecate - * using workspace-based APIs for organizations. Currently, and until after - * some reasonable grace period following any further announcements, you can - * still reference organizations in any `workspace` parameter. - * @class - * @param {Dispatcher} dispatcher The API dispatcher - */ - interface Workspaces extends Resource { - /** - * * Returns the full workspace record for a single workspace. - * * @param {Number} workspace Globally unique identifier for the workspace or organization. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The requested resource - * @param workspace - * @param params? - * @param dispatchOptions? - * @return - */ - findById(workspace: number, params?: Params, dispatchOptions?: any): Promise; - - /** - * * Returns the compact records for all workspaces visible to the authorized user. - * * @param {Object} [params] Parameters for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param params? - * @param dispatchOptions? - * @return - */ - findAll(params?: PaginationParams, dispatchOptions?: any): Promise>; - - /** - * * A specific, existing workspace can be updated by making a PUT request on - * * the URL for that workspace. Only the fields provided in the data block - * * will be updated; any unspecified fields will remain unchanged. - * * - * * Currently the only field that can be modified for a workspace is its `name`. - * * - * * Returns the complete, updated workspace record. - * * @param {Number} workspace The workspace to update. - * * @param {Object} data Data for the request - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace + * Dispatches a PUT request to the Asana API. + * @param {String} path The path of the API + * @param {Object} data The data to be sent + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `dispatch`. + * @return {Promise} The response for the request + * @param path * @param data * @param dispatchOptions? * @return */ - update(workspace: number, data: { name?: string }, dispatchOptions?: any): Promise; + put(path: string, data: any, dispatchOptions?: any): Promise; /** - * * Retrieves objects in the workspace based on an auto-completion/typeahead - * * search algorithm. This feature is meant to provide results quickly, so do - * * not rely on this API to provide extremely accurate search results. The - * * result set is limited to a single page of results with a maximum size, - * * so you won't be able to fetch large numbers of results. - * * @param {Number} workspace The workspace to fetch objects from. - * * @param {Object} [params] Parameters for the request - * * @param {String} params.type The type of values the typeahead should return. - * * Note that unlike in the names of endpoints, the types listed here are - * * in singular form (e.g. `task`). Using multiple types is not yet supported. - * * @param {String} [params.query] The string that will be used to search for relevant objects. If an - * * empty string is passed in, the API will currently return an empty - * * result set. - * * @param {Number} [params.count] The number of results to return. The default is `20` if this - * * parameter is omitted, with a minimum of `1` and a maximum of `100`. - * * If there are fewer results found than requested, all will be returned. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param params? - * @param dispatchOptions? - * @return - */ - typeahead(workspace: number, params?: Workspaces.TypeaheadParams, dispatchOptions?: any): Promise; - - /** - * * The user can be referenced by their globally unique user ID or their email address. - * * Returns the full user record for the invited user. - * * @param {Number} workspace The workspace or organization to invite the user to. - * * @param {Object} data Data for the request - * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, - * * the globally unique identifier for the user, or the keyword `me` - * * to indicate the current user making the request. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param data - * @param dispatchOptions? - * @return - */ - addUser(workspace: number, data: UserParams, dispatchOptions?: any): Promise; - - /** - * * The user making this call must be an admin in the workspace. - * * Returns an empty data record. - * * @param {Number} workspace The workspace or organization to invite the user to. - * * @param {Object} data Data for the request - * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, - * * the globally unique identifier for the user, or the keyword `me` - * * to indicate the current user making the request. - * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request - * * @return {Promise} The response from the API - * @param workspace - * @param data - * @param dispatchOptions? - * @return - */ - removeUser(workspace: number, data: UserParams, dispatchOptions?: any): Promise; - } - - interface ResourceStatic { - /** - * @param dispatcher - */ - new (dispatcher: Dispatcher): Resource; - - /** - * @type {number} Default number of items to get per page. - */ - DEFAULT_PAGE_LIMIT: number; - - /** - * Helper method that dispatches a GET request to the API, where the expected - * result is a collection. - * @param {Dispatcher} dispatcher - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The Collection response for the request - * @param dispatcher - * @param path - * @param query? - * @param dispatchOptions? - */ - getCollection(dispatcher: any, path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Helper method for any request Promise from the Dispatcher, unwraps the `data` - * value from the payload. - * @param {Promise} promise A promise returned from a `Dispatcher` request. - * @return {Promise} The `data` portion of the response payload. - * @param promise - * @return - */ - unwrap(promise: any): Promise; - } - - var Resource: ResourceStatic; - - /** - * Base class for a resource accessible via the API. Uses a `Dispatcher` to - * access the resources. - * @param {Dispatcher} dispatcher - * @constructor - */ - interface Resource { - /** - * Dispatches a GET request to the API, where the expected result is a - * single resource. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - * @param path - * @param query? - * @param dispatchOptions? - * @return - */ - dispatchGet(path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a GET request to the API, where the expected result is a - * collection. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - * @param path - * @param query? - * @param dispatchOptions? - * @return - */ - dispatchGetCollection(path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a POST request to the API, where the expected response is a - * single resource. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - * @param path - * @param query? - * @param dispatchOptions? - * @return - */ - dispatchPost(path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a POST request to the API, where the expected response is a - * single resource. - * @param {String} path The path of the API - * @param {Object} [query] The query params - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request - * @param path - * @param query? - * @param dispatchOptions? - * @return - */ - dispatchPut(path: string, query?: any, dispatchOptions?: any): Promise; - - /** - * Dispatches a DELETE request to the API. The expected response is an - * empty resource. - * @param {String} path The path of the API - * @param {Object} [dispatchOptions] Options for handling the request and - * response. See `Dispatcher.dispatch`. - * @return {Promise} The response for the request + * Dispatches a DELETE request to the Asana API. + * @param {String} path The path of the API + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `dispatch`. + * @return {Promise} The response for the request * @param path * @param dispatchOptions? * @return */ - dispatchDelete(path: string, dispatchOptions?: any): Promise; - } + delete(path: string, dispatchOptions?: any): Promise; - interface ResourceList { - data: T[]; - _response: { - data: T[]; - next_page?: NextPage; - }; - _dispatcher: { - authenticator: { - apiKey: string; - }; - asanaBaseUrl: string; - retryOnRateLimit: boolean; - requestTimeout: number; - _cachedVersionInfo: VersionInfo; + /** + * The base URL for Asana + * @type {String} + */ + asanaBaseUrl: string; + + /** + * Whether requests should be automatically retried if rate limited. + * @type {Boolean} + */ + retryOnRateLimit: boolean; + + /** + * Handler for unauthorized requests which may seek reauthorization. + * Default behavior is available if configured with an Oauth authenticator + * that has a refresh token, and will refresh the current access token. + * @type {Function} + */ + handleUnauthorized: () => boolean | Promise; + + /** + * The amount of time in milliseconds to wait for a request to finish. + * @type {Number} + */ + requestTimeout: number; + } + + namespace auth { + var BasicAuthenticator: BasicAuthenticatorStatic; + + interface BasicAuthenticatorStatic { + /** + * @param apiKey + */ + new (apiKey: string): BasicAuthenticator; } - } - type SimpleResourceList = ResourceList; + interface BasicAuthenticator extends Authenticator { + /** + * @param {Object} request The request to modify, for the `request` library. + * @return {Object} The `request` parameter, modified to include authentication + * information using the stored credentials. + * @param request + * @return + */ + authenticateRequest(request: BasicAuthenticatorRequest): BasicAuthenticatorRequest; + } - interface NextPage { - offset: string; - uri: string; - path: string; - } + interface BasicAuthenticatorRequest { + auth: { + username: string; + password: string; + } + } - interface VersionInfo { - version: string; - language: string; - language_version: string; - os: string; - os_version: string; - } + var OauthAuthenticator: OauthAuthenticatorStatic; - interface Resource { - id: number; - name: string; - } + interface OauthAuthenticatorStatic { + /** + * Creates an authenticator that uses Oauth for authentication. + * + * @param {Object} options Configure the authenticator; must specify one + * of `flow` or `credentials`. + * @option {App} app The app being authenticated for. + * @option {OauthFlow} [flow] The flow to use to get credentials + * when needed. + * @option {String|Object} [credentials] Initial credentials to use. This can + * be either the object returned from an access token request (which + * contains the token and some other metadata) or just the `access_token` + * field. + * @constructor + */ + new (options: OauthAuthenticatorOptions): OauthAuthenticator; + } - interface PaginationParams extends Params { - limit?: number; - offset?: string; - } + interface OauthAuthenticatorOptions { + flowType?: auth.FlowType; + credentials?: Credentials | string; + } - interface Params { - opt_fields?: string; - opt_expand?: string; - } + interface Credentials { + access_token?: string; + refresh_token?: string; + } - interface UserParams { - user: string|number; - } + interface OauthAuthenticator extends Authenticator { + /** + * @param {Object} request The request to modify, for the `request` library. + * @return {Object} The `request` parameter, modified to include authentication + * information using the stored credentials. + * @param request + * @return + */ + authenticateRequest(request: OauthAuthenticatorRequest): OauthAuthenticatorRequest; + } - interface Membership { - project: Resource; - section: Resource; - } + interface OauthAuthenticatorRequest { + /** + * When browserify-d, the `auth` component of the `request` library + * doesn't work so well, so we just manually set the bearer token instead. + */ + headers: { + Authorization: string; + } + } + + /** + * A layer to abstract the differences between using different types of + * authentication (Oauth vs. Basic). The Authenticator is responsible for + * establishing credentials and applying them to outgoing requests. + * @constructor + */ + interface Authenticator { + /** + * Establishes credentials. + * + * @return {Promise} Resolves when initial credentials have been + * completed and `authenticateRequest` calls can expect to succeed. + * @return + */ + establishCredentials(): Promise; + + /** + * Attempts to refresh credentials, if possible, given the current credentials. + * + * @return {Promise} Resolves to `true` if credentials have been successfully + * established and `authenticateRequests` can expect to succeed, else + * resolves to `false`. + * @return + */ + refreshCredentials(): Promise; + } + + var App: AppStatic; + + interface AppStatic { + /** + * An abstraction around an App used with Asana. + * + * @options {Object} Options to construct the app + * @option {String} clientId The ID of the app + * @option {String} [clientSecret] The secret key, if available here + * @option {String} [redirectUri] The default redirect URI + * @option {String} [scope] Scope to use, supports `default` and `scim` + * @option {String} [asanaBaseUrl] Base URL to use for Asana, for debugging + * @constructor + */ + new (options: AppOptions): App; + } + + interface AppOptions extends AsanaAuthorizeUrlOptions { + clientId?: string | number; + clientSecret?: string; + scope?: string; + } + + interface App { + /** + * @param {Object} options Overrides to the app's defaults + * @option {String} asanaBaseUrl + * @option {String} redirectUri + * @returns {String} The URL used to authorize a user for the app. + * @param options + * @return + */ + asanaAuthorizeUrl(options?: AsanaAuthorizeUrlOptions): string; + + /** + * @param {Object} options Overrides to the app's defaults + * @option {String} asanaBaseUrl + * @option {String} redirectUri + * @returns {String} The URL used to acquire an access token. + * @param options + * @return + */ + asanaTokenUrl(options?: AsanaAuthorizeUrlOptions): string; + + /** + * @param {String} code An authorization code obtained via `asanaAuthorizeUrl`. + * @param {Object} options Overrides to the app's defaults + * @option {String} asanaBaseUrl + * @option {String} redirectUri + * @return {Promise} The token, which will include the `access_token` + * used for API access, as well as a `refresh_token` which can be stored + * to get a new access token without going through the flow again. + * @param code + * @param options + * @return + */ + accessTokenFromCode(code: string, options?: AsanaAuthorizeUrlOptions): Promise; + + /** + * @param {String} refreshToken A refresh token obtained via Oauth. + * @param {Object} options Overrides to the app's defaults + * @option {String} asanaBaseUrl + * @option {String} redirectUri + * @return {Promise} The token, which will include the `access_token` + * used for API access. + * @param refreshToken + * @param options + * @return + */ + accessTokenFromRefreshToken(refreshToken: string, options: AsanaAuthorizeUrlOptions): Promise; + + scope: string; + + asanaBaseUrl: string; + } + + interface AsanaAuthorizeUrlOptions { + redirectUri?: string; + asanaBaseUrl?: string; + } + + var OauthError: OauthErrorStatic; + + interface OauthErrorStatic { + /** + * @param options {Object} A data blob parsed from a query string or JSON + * response from the Asana API + * @option {String} error The string code identifying the error. + * @option {String} [error_uri] A link to help and information about the error. + * @option {String} [error_description] A description of the error. + * @constructor + */ + new (options: OauthErrorOptions): OauthError; + } + + interface OauthErrorOptions { + error?: string; + error_uri?: string; + error_description?: string; + } + + interface OauthError extends Error { + } + + /** + * Auto-detects the type of Oauth flow to use that's appropriate to the + * environment. + * + * @returns {Function|null} The type of Oauth flow to use, or null if no + * appropriate type could be determined. + * @param env + * @return + */ + function autoDetect(env: any): Function; + + var RedirectFlow: RedirectFlowStatic; + + interface RedirectFlowStatic extends FlowType { + /** + * An Oauth flow that runs in the browser and requests user authorization by + * redirecting to an authorization page on Asana, and redirecting back with + * the credentials. + * @param {Object} options See `BaseBrowserFlow` for options. + * @constructor + */ + new (options: any): RedirectFlow; + } + + interface RedirectFlow extends BaseBrowserFlow { + } + + var PopupFlow: PopupFlowStatic; + + interface PopupFlowStatic extends FlowType { + /** + * An Oauth flow that runs in the browser and requests user authorization by + * popping up a window and prompting the user. + * @param {Object} options See `BaseBrowserFlow` for options. + * @constructor + */ + new (options: any): PopupFlow; + } + + interface PopupFlow extends BaseBrowserFlow { + /** + * @param popupWidth + * @param popupHeight + */ + _popupParams(popupWidth: number, popupHeight: number): void; + + runReceiver(): void; + } + + var NativeFlow: NativeFlowStatic; + + interface NativeFlowStatic extends FlowType { + /** + * An Oauth flow that can be run from the console or an app that does + * not have the ability to open and manage a browser on its own. + * @param {Object} options + * @option {App} app App to authenticate for + * @option {String function(String)} [instructions] Function returning the + * instructions to output to the user. Passed the authorize url. + * @option {String function()} [prompt] String to output immediately before + * waiting for a line from stdin. + * @constructor + */ + new (options: any): NativeFlow; + } + + interface NativeFlow extends Flow { + /** + * Run the Oauth flow, prompting the user to go to the authorization URL + * and enter the code it displays when finished. + * + * @return {Promise} The access token object, which will include + * `access_token` and `refresh_token`. + */ + run(): void; + + /** + * @param {String} code An authorization code obtained via `asanaAuthorizeUrl`. + * @return {Promise} The token, which will include the `access_token` + * used for API access, as well as a `refresh_token` which can be stored + * to get a new access token without going through the flow again. + * @param code + */ + accessToken(code: string): void; + + /** + * @return {Promise} The access token, which will include a refresh token + * that can be stored in the future to create a client without going + * through the Oauth flow. + * @param url + * @return + */ + promptForCode(url: string): any; + } + + var ChromeExtensionFlow: ChromeExtensionFlowStatic; + + interface ChromeExtensionFlowStatic extends FlowType { + /** + * An Oauth flow that runs in a Chrome browser extension and requests user + * authorization by opening a temporary tab to prompt the user. + * @param {Object} options See `BaseBrowserFlow` for options, plus the below: + * @options {String} [receiverPath] Full path and filename from the base + * directory of the extension to the receiver page. This is an HTML file + * that has been made web-accessible, and that calls the receiver method + * `Asana.auth.ChromeExtensionFlow.runReceiver();`. + * @constructor + */ + new (options: any): ChromeExtensionFlow; + } + + interface ChromeExtensionFlow extends BaseBrowserFlow { + /** + * Runs the receiver code to send the Oauth result to the requesting tab. + */ + runReceiver(): void; + } + + var BaseBrowserFlow: BaseBrowserFlowStatic; + + interface BaseBrowserFlowStatic extends FlowType { + /** + * A base class for any flow that runs in the browser. All subclasses use the + * "implicit grant" flow to authenticate via the browser. + * @param {Object} options + * @option {App} app The app this flow is for + * @option {String} [redirectUri] The URL that Asana should redirect to once + * user authorization is complete. Defaults to the URL configured in + * the app, and if none then the current page URL. + * @constructor + */ + new (options: any): BaseBrowserFlow; + } + + interface BaseBrowserFlow extends Flow { + /** + * @param {String} authUrl The URL the user should be navigated to in order + * to authorize the app. + * @param {String} state The unique state generated for this auth request. + * @return {Promise} Resolved when authorization has successfully started, + * i.e. the user has been navigated to a page requesting authorization. + * @param authUrl + * @param state + * @return + */ + startAuthorization(authUrl: string, state: string): any; + + /** + * @return {Promise} Credentials returned from Oauth. + * @param state + */ + finishAuthorization(state: string): void; + + /** + * @return {String} The URL to redirect to that will receive the + * @return + */ + receiverUrl(): string; + + /** + * @return {String} The URL to redirect to that will receive the + * @return + */ + asanaBaseUrl(): string; + + /** + * @returns {String} Generate a new unique state parameter for a request. + * @return + */ + getStateParam(): string; + } + + interface FlowType { + new (options: any): Flow; + } + + interface Flow { + /** + * @returns {String} The URL used to authorize the user for the app. + * @return + */ + authorizeUrl(): string; + + /** + * Run the appropriate parts of the Oauth flow, attempting to establish user + * authorization. + * @returns {Promise} A promise that resolves to the Oauth credentials. + */ + run(): void; + } + } + + namespace errors { + class AsanaError extends Error { + /** + * @param message + * @return + */ + constructor(message: any); + + code: number; + value: any; + } + + class Forbidden extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + + + class InvalidRequest extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + + class NoAuthorization extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + + class NotFound extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + + class RateLimitEnforced extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + + class ServerError extends AsanaError { + /** + * @param value + * @return + */ + constructor(value: any); + } + } + + namespace resources { + interface AttachmentsStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Attachments; + } + + namespace Attachments { + interface Type extends Resource { + created_at: string; + permanent_url: string; + download_url: string; + view_url: string; + host: string; + parent: Resource; + } + } + + var Attachments: AttachmentsStatic; + + /** + * An _attachment_ object represents any file attached to a task in Asana, + * whether it's an uploaded file or one associated via a third-party service + * such as Dropbox or Google Drive. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Attachments extends Resource { + /** + * * Returns the full record for a single attachment. + * * @param {Number} attachment Globally unique identifier for the attachment. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param attachment + * @param params? + * @param dispatchOptions? + * @return + */ + findById(attachment: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the compact records for all attachments on the task. + * * @param {Number} task Globally unique identifier for the task. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + findByTask(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + } + + interface EventsStatic { + /** + * @param dispatcher + * @return + */ + new (dispatcher: Dispatcher): Events; + } + + var Events: EventsStatic; + + /** + * An _event_ is an object representing a change to a resource that was observed + * by an event subscription. + * + * In general, requesting events on a resource is faster and subject to higher + * rate limits than requesting the resource itself. Additionally, change events + * bubble up - listening to events on a project would include when stories are + * added to tasks in the project, even on subtasks. + * + * Establish an initial sync token by making a request with no sync token. + * The response will be a `412` error - the same as if the sync token had + * expired. + * + * Subsequent requests should always provide the sync token from the immediately + * preceding call. + * + * Sync tokens may not be valid if you attempt to go 'backward' in the history + * by requesting previous tokens, though re-requesting the current sync token + * is generally safe, and will always return the same results. + * + * When you receive a `412 Precondition Failed` error, it means that the + * sync token is either invalid or expired. If you are attempting to keep a set + * of data in sync, this signals you may need to re-crawl the data. + * + * Sync tokens always expire after 24 hours, but may expire sooner, depending on + * load on the service. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Events extends Resource { } + + interface ProjectsStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Projects; + } + + namespace Projects { + interface Type extends Resource { + created_at: string; + modified_at: string; + due_date: string; + current_status: Status; + public: boolean; + archived: boolean; + notes: string; + color: string; + workspace: Resource; + team: Resource; + members: Resource[]; + followers: Resource[]; + } + + interface CreateParams { + name?: string; + team?: number; + public?: boolean; + due_date: string; + notes?: string; + color?: string; + } + + interface FollowersParams { + followers: (number | string)[]; + } + + interface MembersParams { + members: (number | string)[]; + } + + interface Status { + color: string; + text: string; + html_text: string; + modified_at: string; + author: Resource; + } + + interface FindAllParams extends PaginationParams { + team?: number; + archived?: boolean; + } + + interface FindByParams extends PaginationParams { + archived?: boolean; + } + } + + var Projects: ProjectsStatic; + + /** + * A _project_ represents a prioritized list of tasks in Asana. It exists in a + * single workspace or organization and is accessible to a subset of users in + * that workspace or organization, depending on its permissions. + * + * Projects in organizations are shared with a single team. You cannot currently + * change the team of a project via the API. Non-organization workspaces do not + * have teams and so you should not specify the team of project in a + * regular workspace. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Projects extends Resource { + /** + * * Creates a new project in a workspace or team. + * * + * * Every project is required to be created in a specific workspace or + * * organization, and this cannot be changed once set. Note that you can use + * * the `workspace` parameter regardless of whether or not it is an + * * organization. + * * + * * If the workspace for your project _is_ an organization, you must also + * * supply a `team` to share the project with. + * * + * * Returns the full record of the newly created project. + * * @param {Object} data Data for the request + * * @param {String} data.workspace The workspace or organization to create the project in. + * * @param {String} [data.team] If creating in an organization, the specific team to create the + * * project in. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param data + * @param dispatchOptions? + * @return + */ + create(data: Projects.CreateParams & { workspace: number }, dispatchOptions?: any): Promise; + + /** + * * If the workspace for your project _is_ an organization, you must also + * * supply a `team` to share the project with. + * * + * * Returns the full record of the newly created project. + * * @param {Number} workspace The workspace or organization to create the project in. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + createInWorkspace(workspace: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; + + /** + * * Creates a project shared with the given team. + * * + * * Returns the full record of the newly created project. + * * @param {Number} team The team to create the project in. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param team + * @param data + * @param dispatchOptions? + * @return + */ + createInTeam(team: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; + + /** + * * Returns the complete project record for a single project. + * * @param {Number} project The project to get. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param project + * @param params? + * @param dispatchOptions? + * @return + */ + findById(project: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * A specific, existing project can be updated by making a PUT request on the + * * URL for that project. Only the fields provided in the `data` block will be + * * updated; any unspecified fields will remain unchanged. + * * + * * When using this method, it is best to specify only those fields you wish + * * to change, or else you may overwrite changes made by another user since + * * you last retrieved the task. + * * + * * Returns the complete updated project record. + * * @param {Number} project The project to update. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param data + * @param dispatchOptions? + * @return + */ + update(project: number, data: Projects.CreateParams, dispatchOptions?: any): Promise; + + /** + * * A specific, existing project can be deleted by making a DELETE request + * * on the URL for that project. + * * + * * Returns an empty data record. + * * @param {Number} project The project to delete. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param dispatchOptions? + * @return + */ + delete(project: number, dispatchOptions?: any): Promise; + + /** + * * Returns the compact project records for some filtered set of projects. + * * Use one or more of the parameters provided to filter the projects returned. + * * @param {Object} [params] Parameters for the request + * * @param {String} [params.workspace] The workspace or organization to filter projects on. + * * @param {String} [params.team] The team to filter projects on. + * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of + * * this parameter. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param params? + * @param dispatchOptions? + * @return + */ + findAll(params?: Projects.FindAllParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact project records for all projects in the workspace. + * * @param {Number} workspace The workspace or organization to find projects in. + * * @param {Object} [params] Parameters for the request + * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of + * * this parameter. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + findByWorkspace(workspace: number, params?: Projects.FindByParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact project records for all projects in the team. + * * @param {Number} team The team to find projects in. + * * @param {Object} [params] Parameters for the request + * * @param {Boolean} [params.archived] Only return projects whose `archived` field takes on the value of + * * this parameter. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param team + * @param params? + * @param dispatchOptions? + * @return + */ + findByTeam(team: number, params?: Projects.FindByParams, dispatchOptions?: any): Promise>; + + /** + * * Returns compact records for all sections in the specified project. + * * @param {Number} project The project to get sections from. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param params? + * @param dispatchOptions? + * @return + */ + sections(project: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact task records for all tasks within the given project, + * * ordered by their priority within the project. Tasks can exist in more than one project at a time. + * * @param {Number} project The project in which to search for tasks. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param params? + * @param dispatchOptions? + * @return + */ + tasks(project: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Adds the specified list of users as followers to the project. Followers are a subset of members, therefore if + * * the users are not already members of the project they will also become members as a result of this operation. + * * Returns the updated project record. + * * @param {Number} project The project to add followers to. + * * @param {Object} data Data for the request + * * @param {Array} data.followers An array of followers to add to the project. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param data + * @param dispatchOptions? + * @return + */ + addFollowers(project: number, data: Projects.FollowersParams, dispatchOptions?: any): Promise; + + /** + * * Removes the specified list of users from following the project, this will not affect project membership status. + * * Returns the updated project record. + * * @param {Number} project The project to remove followers from. + * * @param {Object} data Data for the request + * * @param {Array} data.followers An array of followers to remove from the project. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param data + * @param dispatchOptions? + * @return + */ + removeFollowers(project: number, data: Projects.FollowersParams, dispatchOptions?: any): Promise; + + /** + * * Adds the specified list of users as members of the project. Returns the updated project record. + * * @param {Number} project The project to add members to. + * * @param {Object} data Data for the request + * * @param {Array} data.members An array of members to add to the project. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param data + * @param dispatchOptions? + * @return + */ + addMembers(project: number, data: Projects.MembersParams, dispatchOptions?: any): Promise; + + /** + * * Removes the specified list of members from the project. Returns the updated project record. + * * @param {Number} project The project to remove members from. + * * @param {Object} data Data for the request + * * @param {Array} data.members An array of members to remove from the project. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param project + * @param data + * @param dispatchOptions? + * @return + */ + removeMembers(project: number, data: Projects.MembersParams, dispatchOptions?: any): Promise; + } + + interface StoriesStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Stories; + } + + namespace Stories { + interface ShortType extends Resource { + created_at: string; + created_by: Resource; + type: string; + text: string; + } + + interface Type extends ShortType { + html_text: string; + source: string; + target: Resource; + hearts: Type[]; + } + } + + var Stories: StoriesStatic; + + /** + * A _story_ represents an activity associated with an object in the Asana + * system. Stories are generated by the system whenever users take actions such + * as creating or assigning tasks, or moving tasks between projects. _Comments_ + * are also a form of user-generated story. + * + * Stories are a form of history in the system, and as such they are read-only. + * Once generated, it is not possible to modify a story. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Stories extends Resource { + /** + * * Returns the compact records for all stories on the task. + * * @param {Number} task Globally unique identifier for the task. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + findByTask(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the full record for a single story. + * * @param {Number} story Globally unique identifier for the story. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param story + * @param params? + * @param dispatchOptions? + * @return + */ + findById(story: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Adds a comment to a task. The comment will be authored by the + * * currently authenticated user, and timestamped when the server receives + * * the request. + * * + * * Returns the full record for the new story added to the task. + * * @param {Number} task Globally unique identifier for the task. + * * @param {Object} data Data for the request + * * @param {String} data.text The plain text of the comment to add. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + createOnTask(task: number, data: any, dispatchOptions?: any): Promise>; + } + + interface TagsStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Tags; + } + + namespace Tags { + interface Type extends Resource { + created_at: string; + notes: string; + workspace: Resource; + color: string; + followers: Resource[]; + } + + interface FindAllParams extends PaginationParams { + team?: number; + archived?: boolean; + } + } + + var Tags: TagsStatic; + + /** + * A _tag_ is a label that can be attached to any task in Asana. It exists in a + * single workspace or organization. + * + * Tags have some metadata associated with them, but it is possible that we will + * simplify them in the future so it is not encouraged to rely too heavily on it. + * Unlike projects, tags do not provide any ordering on the tasks they + * are associated with. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Tags extends Resource { + /** + * * Creates a new tag in a workspace or organization. + * * + * * Every tag is required to be created in a specific workspace or + * * organization, and this cannot be changed once set. Note that you can use + * * the `workspace` parameter regardless of whether or not it is an + * * organization. + * * + * * Returns the full record of the newly created tag. + * * @param {Object} data Data for the request + * * @param {String} data.workspace The workspace or organization to create the tag in. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param data + * @param dispatchOptions? + * @return + */ + create(data: Tags.Type & { workspace: string }, dispatchOptions?: any): Promise; + + /** + * * Creates a new tag in a workspace or organization. + * * + * * Every tag is required to be created in a specific workspace or + * * organization, and this cannot be changed once set. Note that you can use + * * the `workspace` parameter regardless of whether or not it is an + * * organization. + * * + * * Returns the full record of the newly created tag. + * * @param {Number} workspace The workspace or organization to create the tag in. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + createInWorkspace(workspace: number, data: Tags.Type, dispatchOptions?: any): Promise; + + /** + * * Returns the complete tag record for a single tag. + * * @param {Number} tag The tag to get. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param tag + * @param params? + * @param dispatchOptions? + * @return + */ + findById(tag: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Updates the properties of a tag. Only the fields provided in the `data` + * * block will be updated; any unspecified fields will remain unchanged. + * * + * * When using this method, it is best to specify only those fields you wish + * * to change, or else you may overwrite changes made by another user since + * * you last retrieved the task. + * * + * * Returns the complete updated tag record. + * * @param {Number} tag The tag to update. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param tag + * @param data + * @param dispatchOptions? + * @return + */ + update(tag: number, data: Tags.Type, dispatchOptions?: any): Promise; + + /** + * * A specific, existing tag can be deleted by making a DELETE request + * * on the URL for that tag. + * * + * * Returns an empty data record. + * * @param {Number} tag The tag to delete. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param tag + * @param dispatchOptions? + * @return + */ + delete(tag: number, dispatchOptions?: any): Promise; + + /** + * * Returns the compact tag records for some filtered set of tags. + * * Use one or more of the parameters provided to filter the tags returned. + * * @param {Object} [params] Parameters for the request + * * @param {String} [params.workspace] The workspace or organization to filter tags on. + * * @param {String} [params.team] The team to filter tags on. + * * @param {Boolean} [params.archived] Only return tags whose `archived` field takes on the value of + * * this parameter. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param params? + * @param dispatchOptions? + * @return + */ + findAll(params?: Tags.FindAllParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact tag records for all tags in the workspace. + * * @param {Number} workspace The workspace or organization to find tags in. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + findByWorkspace(workspace: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact task records for all tasks with the given tag. + * * Tasks can have more than one tag at a time. + * * @param {Number} tag The tag to fetch tasks from. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param tag + * @param params? + * @param dispatchOptions? + * @return + */ + getTasksWithTag(tag: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + } + + interface TasksStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Tasks; + } + + namespace Tasks { + interface Type extends Resource { + created_at: string; + modified_at: string; + completed_at: string; + completed: boolean; + due_on: string; + due_at: string; + assignee_status: string; + assignee: Resource; + notes: string; + workspace: Resource; + num_hearts: number; + hearted: boolean; + parent: Resource; + tags: Resource[]; + projects: Resource[]; + memberships: Membership[]; + followers: Resource[]; + } + + interface CreateParams { + name: string; + completed?: boolean; + hearted?: boolean; + notes?: string; + } + + interface FollowersParams { + followers: (number | string)[]; + } + + interface AddProjectParams { + project: number; + insertBefore?: number; + insertAfter?: number; + section?: number; + } + + interface RemoveProjectParams { + project: number; + } + + interface TagParams { + tag: string; + } + + interface CommentParams { + text: string; + } + + interface FindAllParams extends PaginationParams { + assignee?: number; + workspace: number; + completed_since?: string; + modified_since?: string; + } + } + + var Tasks: TasksStatic; + + /** + * The _task_ is the basic object around which many operations in Asana are + * centered. In the Asana application, multiple tasks populate the middle pane + * according to some view parameters, and the set of selected tasks determines + * the more detailed information presented in the details pane. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Tasks extends Resource { + /** + * * Creating a new task is as easy as POSTing to the `/tasks` endpoint + * * with a data block containing the fields you'd like to set on the task. + * * Any unspecified fields will take on default values. + * * + * * Every task is required to be created in a specific workspace, and this + * * workspace cannot be changed once set. The workspace need not be set + * * explicitly if you specify a `project` or a `parent` task instead. + * * @param {Object} data Data for the request + * * @param {Number} [data.workspace] The workspace to create a task in. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param data + * @param dispatchOptions? + * @return + */ + create(data: Tasks.CreateParams & { workspace: string }, dispatchOptions?: any): Promise; + + /** + * * Creating a new task is as easy as POSTing to the `/tasks` endpoint + * * with a data block containing the fields you'd like to set on the task. + * * Any unspecified fields will take on default values. + * * + * * Every task is required to be created in a specific workspace, and this + * * workspace cannot be changed once set. The workspace need not be set + * * explicitly if you specify a `project` or a `parent` task instead. + * * @param {Number} workspace The workspace to create a task in. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + createInWorkspace(workspace: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; + + /** + * * Returns the complete task record for a single task. + * * @param {Number} task The task to get. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + findById(task: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * A specific, existing task can be updated by making a PUT request on the + * * URL for that task. Only the fields provided in the `data` block will be + * * updated; any unspecified fields will remain unchanged. + * * + * * When using this method, it is best to specify only those fields you wish + * * to change, or else you may overwrite changes made by another user since + * * you last retrieved the task. + * * + * * Returns the complete updated task record. + * * @param {Number} task The task to update. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + update(task: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; + + /** + * * A specific, existing task can be deleted by making a DELETE request on the + * * URL for that task. Deleted tasks go into the "trash" of the user making + * * the delete request. Tasks can be recovered from the trash within a period + * * of 30 days; afterward they are completely removed from the system. + * * + * * Returns an empty data record. + * * @param {Number} task The task to delete. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param dispatchOptions? + * @return + */ + delete(task: number, dispatchOptions?: any): Promise; + + /** + * * Returns the compact task records for all tasks within the given project, + * * ordered by their priority within the project. + * * @param {Number} projectId The project in which to search for tasks. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param projectId + * @param params? + * @param dispatchOptions? + * @return + */ + findByProject(projectId: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact task records for all tasks with the given tag. + * * @param {Number} tag The tag in which to search for tasks. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param tag + * @param params? + * @param dispatchOptions? + * @return + */ + findByTag(tag: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Returns the compact task records for some filtered set of tasks. Use one + * * or more of the parameters provided to filter the tasks returned. + * * @param {Object} [params] Parameters for the request + * * @param {Number} [params.assignee] The assignee to filter tasks on. + * * @param {Number} [params.workspace] The workspace or organization to filter tasks on. + * * @param {Number} [params.completed_since] Only return tasks that are either incomplete or that have been + * * completed since this time. + * * @param {Number} [params.modified_since] Only return tasks that have been modified since the given time. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param params? + * @param dispatchOptions? + * @return + */ + findAll(params?: Tasks.FindAllParams, dispatchOptions?: any): Promise>; + + /** + * * Adds each of the specified followers to the task, if they are not already + * * following. Returns the complete, updated record for the affected task. + * * @param {Number} task The task to add followers to. + * * @param {Object} data Data for the request + * * @param {Array} data.followers An array of followers to add to the task. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + addFollowers(task: number, data: Tasks.FollowersParams, dispatchOptions?: any): Promise; + + /** + * * Removes each of the specified followers from the task if they are + * * following. Returns the complete, updated record for the affected task. + * * @param {Number} task The task to remove followers from. + * * @param {Object} data Data for the request + * * @param {Array} data.followers An array of followers to remove from the task. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + removeFollowers(task: number, data: Tasks.FollowersParams, dispatchOptions?: any): Promise; + + /** + * * Returns a compact representation of all of the projects the task is in. + * * @param {Number} task The task to get projects on. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + projects(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Adds the task to the specified project, in the optional location + * * specified. If no location arguments are given, the task will be added to + * * the beginning of the project. + * * + * * `addProject` can also be used to reorder a task within a project that + * * already contains it. + * * + * * Returns an empty data block. + * * @param {Number} task The task to add to a project. + * * @param {Object} data Data for the request + * * @param {Number} data.project The project to add the task to. + * * @param {Number} [data.insertAfter] A task in the project to insert the task after, or `null` to + * * insert at the beginning of the list. + * * @param {Number} [data.insertBefore] A task in the project to insert the task before, or `null` to + * * insert at the end of the list. + * * @param {Number} [data.section] A section in the project to insert the task into. The task will be + * * inserted at the top of the section. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + addProject(task: number, data: Tasks.AddProjectParams, dispatchOptions?: any): Promise<{}>; + + /** + * * Removes the task from the specified project. The task will still exist + * * in the system, but it will not be in the project anymore. + * * + * * Returns an empty data block. + * * @param {Number} task The task to remove from a project. + * * @param {Object} data Data for the request + * * @param {Number} data.project The project to remove the task from. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + removeProject(task: number, data: Tasks.RemoveProjectParams, dispatchOptions?: any): Promise<{}>; + + /** + * * Returns a compact representation of all of the tags the task has. + * * @param {Number} task The task to get tags on. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + tags(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Adds a tag to a task. Returns an empty data block. + * * @param {Number} task The task to add a tag to. + * * @param {Object} data Data for the request + * * @param {Number} data.tag The tag to add to the task. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + addTag(task: number, data: Tasks.TagParams, dispatchOptions?: any): Promise<{}>; + + /** + * * Removes a tag from the task. Returns an empty data block. + * * @param {Number} task The task to remove a tag from. + * * @param {Object} data Data for the request + * * @param {String} data.tag The tag to remove from the task. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + removeTag(task: number, data: Tasks.TagParams, dispatchOptions?: any): Promise<{}>; + + /** + * * Returns a compact representation of all of the subtasks of a task. + * * @param {Number} task The task to get the subtasks of. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + subtasks(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Creates a new subtask and adds it to the parent task. Returns the full record + * * for the newly created subtask. + * * @param {Number} task The task to add a subtask to. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + addSubtask(task: number, data: Tasks.CreateParams, dispatchOptions?: any): Promise; + + /** + * * Returns a compact representation of all of the stories on the task. + * * @param {Number} task The task containing the stories to get. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param params? + * @param dispatchOptions? + * @return + */ + stories(task: number, params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * Adds a comment to a task. The comment will be authored by the + * * currently authenticated user, and timestamped when the server receives + * * the request. + * * + * * Returns the full record for the new story added to the task. + * * @param {Number} task Globally unique identifier for the task. + * * @param {Object} data Data for the request + * * @param {String} data.text The plain text of the comment to add. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param task + * @param data + * @param dispatchOptions? + * @return + */ + addComment(task: number, data: Tasks.CommentParams, dispatchOptions?: any): Promise; + } + + interface TeamsStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Teams; + } + + namespace Teams { + interface Type extends Resource { + organization: Resource; + } + } + + var Teams: TeamsStatic; + + /** + * A _team_ is used to group related projects and people together within an + * organization. Each project in an organization is associated with a team. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Teams extends Resource { + /** + * * Returns the full record for a single team. + * * @param {Number} team Globally unique identifier for the team. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param team + * @param params? + * @param dispatchOptions? + * @return + */ + findById(team: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the compact records for all teams in the organization visible to + * * the authorized user. + * * @param {Number} organization Globally unique identifier for the workspace or organization. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param organization + * @param params? + * @param dispatchOptions? + * @return + */ + findByOrganization(organization: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the compact records for all users that are members of the team. + * * @param {Number} team Globally unique identifier for the team. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param team + * @param params? + * @param dispatchOptions? + * @return + */ + users(team: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * The user making this call must be a member of the team in order to add others. + * * The user to add must exist in the same organization as the team in order to be added. + * * The user to add can be referenced by their globally unique user ID or their email address. + * * Returns the full user record for the added user. + * * @param {Number} team Globally unique identifier for the team. + * * @param {Object} data Data for the request + * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, + * * the globally unique identifier for the user, or the keyword `me` + * * to indicate the current user making the request. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param team + * @param data + * @param dispatchOptions? + * @return + */ + addUser(team: number, data: UserParams, dispatchOptions?: any): Promise; + + /** + * * The user to remove can be referenced by their globally unique user ID or their email address. + * * Removes the user from the specified team. Returns an empty data record. + * * @param {Number} team Globally unique identifier for the team. + * * @param {Object} data Data for the request + * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, + * * the globally unique identifier for the user, or the keyword `me` + * * to indicate the current user making the request. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param team + * @param data + * @param dispatchOptions? + * @return + */ + removeUser(team: number, data: UserParams, dispatchOptions?: any): Promise; + } + + interface UsersStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Users; + } + + namespace Users { + interface FindAllParams extends PaginationParams { + workspace: number; + } + + interface Type extends Resource { + email: string; + workspaces: Resource[]; + photo: { [key: string]: string }; + } + } + + var Users: UsersStatic; + + /** + * A _user_ object represents an account in Asana that can be given access to + * various workspaces, projects, and tasks. + * + * Like other objects in the system, users are referred to by numerical IDs. + * However, the special string identifier `me` can be used anywhere + * a user ID is accepted, to refer to the current authenticated user. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Users extends Resource { + /** + * * Returns the full user record for the currently authenticated user. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param params? + * @param dispatchOptions? + * @return + */ + me(params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the full user record for the single user with the provided ID. + * * @param {Number|String} user An identifier for the user. Can be one of an email address, + * * the globally unique identifier for the user, or the keyword `me` + * * to indicate the current user making the request. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param user + * @param params? + * @param dispatchOptions? + * @return + */ + findById(user: string | number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the user records for all users in the specified workspace or + * * organization. + * * @param {Number} workspace The workspace in which to get users. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + findByWorkspace(workspace: number, params?: Params, dispatchOptions?: any): Promise>; + + /** + * * Returns the user records for all users in all workspaces and organizations + * * accessible to the authenticated user. Accepts an optional workspace ID + * * parameter. + * * @param {Object} [params] Parameters for the request + * * @param {Number} [params.workspace] The workspace or organization to filter users on. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param params + * @param dispatchOptions? + * @return + */ + findAll(params: Users.FindAllParams, dispatchOptions?: any): Promise; + } + + /** + * **Webhooks are currently in BETA - The information here may change.** + * + * Webhooks allow an application to be notified of changes. This is in addition + * to the ability to fetch those changes directly as + * [Events](/developers/api-reference/events) - in fact, Webhooks are just a way + * to receive Events via HTTP POST at the time they occur instead of polling for + * them. For services accessible via HTTP this is often vastly more convenient, + * and if events are not too frequent can be significantly more efficient. + * + * In both cases, however, changes are represented as Event objects - refer to + * the [Events documentation](/developers/api-reference/events) for more + * information on what data these events contain. + * + * **NOTE:** While Webhooks send arrays of Event objects to their target, the + * Event objects themselves contain *only IDs*, rather than the actual resource + * they are referencing. So while a normal event you receive via GET /events + * would look like this: + * + * {\ + * "resource": {\ + * "id": 1337,\ + * "name": "My Task"\ + * },\ + * "parent": null,\ + * "created_at": "2013-08-21T18:20:37.972Z",\ + * "user": {\ + * "id": 1123,\ + * "name": "Tom Bizarro"\ + * },\ + * "action": "changed",\ + * "type": "task"\ + * } + * + * In a Webhook payload you would instead receive this: + * + * {\ + * "resource": 1337,\ + * "parent": null,\ + * "created_at": "2013-08-21T18:20:37.972Z",\ + * "user": 1123,\ + * "action": "changed",\ + * "type": "task"\ + * } + * + * Webhooks themselves contain only the information necessary to deliver the + * events to the desired target as they are generated. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + class Webhooks extends Resource { + /** + * @param dispatcher + */ + constructor(dispatcher: Dispatcher); + + /** + * * Establishing a webhook is a two-part process. First, a simple HTTP POST + * * similar to any other resource creation. Since you could have multiple + * * webhooks we recommend specifying a unique local id for each target. + * * + * * Next comes the confirmation handshake. When a webhook is created, we will + * * send a test POST to the `target` with an `X-Hook-Secret` header as + * * described in the + * * [Resthooks Security documentation](http://resthooks.org/docs/security/). + * * The target must respond with a `200 OK` and a matching `X-Hook-Secret` + * * header to confirm that this webhook subscription is indeed expected. + * * + * * If you do not acknowledge the webhook's confirmation handshake it will + * * fail to setup, and you will receive an error in response to your attempt + * * to create it. This means you need to be able to receive and complete the + * * webhook *while* the POST request is in-flight. + * * @param {Number} resource A resource ID to subscribe to. The resource can be a task or project. + * * @param {String} target The URL to receive the HTTP POST. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param resource + * @param target + * @param data + * @param dispatchOptions? + * @return + */ + create(resource: number, target: string, data: any, dispatchOptions?: any): Promise; + + /** + * * Returns the compact representation of all webhooks your app has + * * registered for the authenticated user in the given workspace. + * * @param {Number} workspace The workspace to query for webhooks in. + * * @param {Object} [params] Parameters for the request + * * @param {Number} [params.resource] Only return webhooks for the given resource. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + getAll(workspace: number, params?: any, dispatchOptions?: any): Promise; + + /** + * * Returns the full record for the given webhook. + * * @param {String} webhook The webhook to get. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param webhook + * @param params? + * @param dispatchOptions? + * @return + */ + getById(webhook: string, params?: any, dispatchOptions?: any): Promise; + + /** + * * This method permanently removes a webhook. Note that it may be possible + * * to receive a request that was already in flight after deleting the + * * webhook, but no further requests will be issued. + * * @param {String} webhook The webhook to delete. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param webhook + * @param dispatchOptions? + * @return + */ + deleteById(webhook: string, dispatchOptions?: any): Promise; + } + + interface WorkspacesStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Workspaces; + } + + namespace Workspaces { + interface ShortType extends Resource { + id_organization?: boolean; + } + + interface Type extends Resource { + id_organization: boolean; + email_domains: string[]; + } + + interface TypeaheadParams { + type: string; + query?: string; + count?: number; + } + } + + var Workspaces: WorkspacesStatic; + + /** + * A _workspace_ is the highest-level organizational unit in Asana. All projects + * and tasks have an associated workspace. + * + * An _organization_ is a special kind of workspace that represents a company. + * In an organization, you can group your projects into teams. You can read + * more about how organizations work on the Asana Guide. + * To tell if your workspace is an organization or not, check its + * `is_organization` property. + * + * Over time, we intend to migrate most workspaces into organizations and to + * release more organization-specific functionality. We may eventually deprecate + * using workspace-based APIs for organizations. Currently, and until after + * some reasonable grace period following any further announcements, you can + * still reference organizations in any `workspace` parameter. + * @class + * @param {Dispatcher} dispatcher The API dispatcher + */ + interface Workspaces extends Resource { + /** + * * Returns the full workspace record for a single workspace. + * * @param {Number} workspace Globally unique identifier for the workspace or organization. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The requested resource + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + findById(workspace: number, params?: Params, dispatchOptions?: any): Promise; + + /** + * * Returns the compact records for all workspaces visible to the authorized user. + * * @param {Object} [params] Parameters for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param params? + * @param dispatchOptions? + * @return + */ + findAll(params?: PaginationParams, dispatchOptions?: any): Promise>; + + /** + * * A specific, existing workspace can be updated by making a PUT request on + * * the URL for that workspace. Only the fields provided in the data block + * * will be updated; any unspecified fields will remain unchanged. + * * + * * Currently the only field that can be modified for a workspace is its `name`. + * * + * * Returns the complete, updated workspace record. + * * @param {Number} workspace The workspace to update. + * * @param {Object} data Data for the request + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + update(workspace: number, data: { name?: string }, dispatchOptions?: any): Promise; + + /** + * * Retrieves objects in the workspace based on an auto-completion/typeahead + * * search algorithm. This feature is meant to provide results quickly, so do + * * not rely on this API to provide extremely accurate search results. The + * * result set is limited to a single page of results with a maximum size, + * * so you won't be able to fetch large numbers of results. + * * @param {Number} workspace The workspace to fetch objects from. + * * @param {Object} [params] Parameters for the request + * * @param {String} params.type The type of values the typeahead should return. + * * Note that unlike in the names of endpoints, the types listed here are + * * in singular form (e.g. `task`). Using multiple types is not yet supported. + * * @param {String} [params.query] The string that will be used to search for relevant objects. If an + * * empty string is passed in, the API will currently return an empty + * * result set. + * * @param {Number} [params.count] The number of results to return. The default is `20` if this + * * parameter is omitted, with a minimum of `1` and a maximum of `100`. + * * If there are fewer results found than requested, all will be returned. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param params? + * @param dispatchOptions? + * @return + */ + typeahead(workspace: number, params?: Workspaces.TypeaheadParams, dispatchOptions?: any): Promise; + + /** + * * The user can be referenced by their globally unique user ID or their email address. + * * Returns the full user record for the invited user. + * * @param {Number} workspace The workspace or organization to invite the user to. + * * @param {Object} data Data for the request + * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, + * * the globally unique identifier for the user, or the keyword `me` + * * to indicate the current user making the request. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + addUser(workspace: number, data: UserParams, dispatchOptions?: any): Promise; + + /** + * * The user making this call must be an admin in the workspace. + * * Returns an empty data record. + * * @param {Number} workspace The workspace or organization to invite the user to. + * * @param {Object} data Data for the request + * * @param {Number|String} data.user An identifier for the user. Can be one of an email address, + * * the globally unique identifier for the user, or the keyword `me` + * * to indicate the current user making the request. + * * @param {Object} [dispatchOptions] Options, if any, to pass the dispatcher for the request + * * @return {Promise} The response from the API + * @param workspace + * @param data + * @param dispatchOptions? + * @return + */ + removeUser(workspace: number, data: UserParams, dispatchOptions?: any): Promise; + } + + interface ResourceStatic { + /** + * @param dispatcher + */ + new (dispatcher: Dispatcher): Resource; + + /** + * @type {number} Default number of items to get per page. + */ + DEFAULT_PAGE_LIMIT: number; + + /** + * Helper method that dispatches a GET request to the API, where the expected + * result is a collection. + * @param {Dispatcher} dispatcher + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The Collection response for the request + * @param dispatcher + * @param path + * @param query? + * @param dispatchOptions? + */ + getCollection(dispatcher: any, path: string, query?: any, dispatchOptions?: any): Promise; + + /** + * Helper method for any request Promise from the Dispatcher, unwraps the `data` + * value from the payload. + * @param {Promise} promise A promise returned from a `Dispatcher` request. + * @return {Promise} The `data` portion of the response payload. + * @param promise + * @return + */ + unwrap(promise: any): Promise; + } + + var Resource: ResourceStatic; + + /** + * Base class for a resource accessible via the API. Uses a `Dispatcher` to + * access the resources. + * @param {Dispatcher} dispatcher + * @constructor + */ + interface Resource { + /** + * Dispatches a GET request to the API, where the expected result is a + * single resource. + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The response for the request + * @param path + * @param query? + * @param dispatchOptions? + * @return + */ + dispatchGet(path: string, query?: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a GET request to the API, where the expected result is a + * collection. + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The response for the request + * @param path + * @param query? + * @param dispatchOptions? + * @return + */ + dispatchGetCollection(path: string, query?: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a POST request to the API, where the expected response is a + * single resource. + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The response for the request + * @param path + * @param query? + * @param dispatchOptions? + * @return + */ + dispatchPost(path: string, query?: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a POST request to the API, where the expected response is a + * single resource. + * @param {String} path The path of the API + * @param {Object} [query] The query params + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The response for the request + * @param path + * @param query? + * @param dispatchOptions? + * @return + */ + dispatchPut(path: string, query?: any, dispatchOptions?: any): Promise; + + /** + * Dispatches a DELETE request to the API. The expected response is an + * empty resource. + * @param {String} path The path of the API + * @param {Object} [dispatchOptions] Options for handling the request and + * response. See `Dispatcher.dispatch`. + * @return {Promise} The response for the request + * @param path + * @param dispatchOptions? + * @return + */ + dispatchDelete(path: string, dispatchOptions?: any): Promise; + } + + interface ResourceList { + data: T[]; + _response: { + data: T[]; + next_page?: NextPage; + }; + _dispatcher: { + authenticator: { + apiKey: string; + }; + asanaBaseUrl: string; + retryOnRateLimit: boolean; + requestTimeout: number; + _cachedVersionInfo: VersionInfo; + } + } + + type SimpleResourceList = ResourceList; + + interface NextPage { + offset: string; + uri: string; + path: string; + } + + interface VersionInfo { + version: string; + language: string; + language_version: string; + os: string; + os_version: string; + } + + interface Resource { + id: number; + name: string; + } + + interface PaginationParams extends Params { + limit?: number; + offset?: string; + } + + interface Params { + opt_fields?: string; + opt_expand?: string; + } + + interface UserParams { + user: string | number; + } + + interface Membership { + project: Resource; + section: Resource; + } } var VERSION: string; - } - - export = asana; } +export = asana; diff --git a/aspnet-identity-pw/aspnet-identity-pw.d.ts b/aspnet-identity-pw/aspnet-identity-pw.d.ts index 390033602b..4fd74c721b 100644 --- a/aspnet-identity-pw/aspnet-identity-pw.d.ts +++ b/aspnet-identity-pw/aspnet-identity-pw.d.ts @@ -3,11 +3,10 @@ // Definitions by: jt000 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "aspnet-identity-pw" { - export function hashPassword(password: string): string; - export function hashPassword(password: string, callback: (err: any, result: string)=>void): void; - export function validatePassword(password: string, hashedPass: string): boolean; - export function validatePassword(password: string, hashedPass: string, callback: (err: any, result: boolean) => void): void; -} +declare export function hashPassword(password: string): string; +declare export function hashPassword(password: string, callback: (err: any, result: string) => void): void; + +declare export function validatePassword(password: string, hashedPass: string): boolean; +declare export function validatePassword(password: string, hashedPass: string, callback: (err: any, result: boolean) => void): void; diff --git a/assertion-error/assertion-error.d.ts b/assertion-error/assertion-error.d.ts index a0295bd8b3..8663df799d 100644 --- a/assertion-error/assertion-error.d.ts +++ b/assertion-error/assertion-error.d.ts @@ -3,13 +3,12 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'assertion-error' { - class AssertionError implements Error { - constructor(message: string, props?: any, ssf?: Function); - name: string; - message: string; - showDiff: boolean; - stack: string; - } - export = AssertionError; + +declare class AssertionError implements Error { + constructor(message: string, props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; } +export = AssertionError; diff --git a/assertsharp/assertsharp.d.ts b/assertsharp/assertsharp.d.ts index c4cf80e867..ef800f5396 100644 --- a/assertsharp/assertsharp.d.ts +++ b/assertsharp/assertsharp.d.ts @@ -3,19 +3,18 @@ // Definitions by: Bruno Leonardo Michels // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "assertsharp" { - export default class Assert { - static AreEqual(expected: T, actual: T, message?: string): void; - static AreNotEqual(notExpected: T, actual: T, message?: string): void; - static AreNotSame(notExpected: T, actual: T, message?: string): void; - static AreSequenceEqual(expected: T[], actual: T[], equals?: (x: any, y: any) => boolean, message?: string): void; - static Fail(message?: string): void; - static IsFalse(actual: boolean, message?: string): void; - static IsInstanceOfType(actual: any, expectedType: Function, message?: string): void; - static IsNotInstanceOfType(actual: any, wrongType: Function, message?: string): void; - static IsNotNull(actual: any, message?: string): void; - static IsNull(actual: any, message?: string): void; - static IsTrue(actual: boolean, message?: string): void; - static Throws(fn: () => void, message?: string): void; - } + +declare export default class Assert { + static AreEqual(expected: T, actual: T, message?: string): void; + static AreNotEqual(notExpected: T, actual: T, message?: string): void; + static AreNotSame(notExpected: T, actual: T, message?: string): void; + static AreSequenceEqual(expected: T[], actual: T[], equals?: (x: any, y: any) => boolean, message?: string): void; + static Fail(message?: string): void; + static IsFalse(actual: boolean, message?: string): void; + static IsInstanceOfType(actual: any, expectedType: Function, message?: string): void; + static IsNotInstanceOfType(actual: any, wrongType: Function, message?: string): void; + static IsNotNull(actual: any, message?: string): void; + static IsNull(actual: any, message?: string): void; + static IsTrue(actual: boolean, message?: string): void; + static Throws(fn: () => void, message?: string): void; } diff --git a/async-lock/async-lock.d.ts b/async-lock/async-lock.d.ts index e5f8613c73..296307300c 100644 --- a/async-lock/async-lock.d.ts +++ b/async-lock/async-lock.d.ts @@ -3,28 +3,27 @@ // Definitions by: Elisée MAURER // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "async-lock" { - interface AsyncLockDoneCallback { - (err?: Error, ret?: any): void; - } - interface AsyncLockOptions { +interface AsyncLockDoneCallback { + (err?: Error, ret?: any): void; +} + +interface AsyncLockOptions { timeout?: number; maxPending?: number; domainReentrant?: boolean; Promise?: any; - } +} - class AsyncLock { +declare class AsyncLock { constructor(options?: AsyncLockOptions); - acquire(key: string|string[], fn: (done: AsyncLockDoneCallback) => any, cb: AsyncLockDoneCallback, opts?: AsyncLockOptions): void; - acquire(key: string|string[], fn: (done: AsyncLockDoneCallback) => any, opts?: AsyncLockOptions): PromiseLike; + acquire(key: string | string[], fn: (done: AsyncLockDoneCallback) => any, cb: AsyncLockDoneCallback, opts?: AsyncLockOptions): void; + acquire(key: string | string[], fn: (done: AsyncLockDoneCallback) => any, opts?: AsyncLockOptions): PromiseLike; isBusy(): boolean; - } - - namespace AsyncLock {} - - export = AsyncLock; } + +declare namespace AsyncLock { } + +export = AsyncLock; diff --git a/async-writer/async-writer.d.ts b/async-writer/async-writer.d.ts index 56c5bb898b..ef8bddfac3 100644 --- a/async-writer/async-writer.d.ts +++ b/async-writer/async-writer.d.ts @@ -5,74 +5,73 @@ /// -declare module 'async-writer' { - import stream = require('stream'); - import events = require('events'); - namespace async_writer { - interface EventFunction { - (event: string, callback: Function): void; - } +import stream = require('stream'); +import events = require('events'); - class StringWriter { - constructor(events: events.EventEmitter); - end(): void; - write(what: string): StringWriter; - toString(): string; - } +declare namespace async_writer { + interface EventFunction { + (event: string, callback: Function): void; + } - class BufferedWriter { - constructor(wrappedStream: stream.Stream); - flush(): void; - on(event: string, callback: Function): BufferedWriter; - once(event: string, callback: Function): BufferedWriter; - clear(): void; - end(): void; - write(what: string): BufferedWriter; - } + class StringWriter { + constructor(events: events.EventEmitter); + end(): void; + write(what: string): StringWriter; + toString(): string; + } - interface BeginAsyncOptions { - last?: boolean; - timeout?: number; - name?: string; - } + class BufferedWriter { + constructor(wrappedStream: stream.Stream); + flush(): void; + on(event: string, callback: Function): BufferedWriter; + once(event: string, callback: Function): BufferedWriter; + clear(): void; + end(): void; + write(what: string): BufferedWriter; + } - class AsyncWriter { - static enableAsyncStackTrace():void; + interface BeginAsyncOptions { + last?: boolean; + timeout?: number; + name?: string; + } - constructor(writer?: any, global?: {[s: string]: any}, async?: boolean, buffer?: boolean); - isAsyncWriter: AsyncWriter; - sync(): void; - getAttributes(): {[s: string]: any}; - getAttribute(): any; - write(str: string): AsyncWriter; - getOutput(): string; - captureString(func: Function, thisObj: Object): string; - swapWriter(newWriter: StringWriter | BufferedWriter, func: Function, thisObj: Object): void; - createNestedWriter(writer: StringWriter | BufferedWriter): AsyncWriter; - beginAsync(options?: number | BeginAsyncOptions): AsyncWriter; - handleBeginAsync(options: number | BeginAsyncOptions, parent: AsyncWriter): void; - on(event: string, callback: Function): AsyncWriter; - once(event: string, callback: Function): AsyncWriter; - onLast(callback: Function): AsyncWriter; - emit(arg: any): AsyncWriter; - removeListener(): AsyncWriter; - pipe(stream: stream.Stream): AsyncWriter; - error(e: Error): void; - end(data?: any): AsyncWriter; - handleEnd(isAsync: boolean): void; - _finish(): void; - flush(): void; - } + class AsyncWriter { + static enableAsyncStackTrace(): void; - interface AsyncWriterOptions { - global?: {[s: string]: any}; - buffer?: boolean; - } + constructor(writer?: any, global?: { [s: string]: any }, async?: boolean, buffer?: boolean); + isAsyncWriter: AsyncWriter; + sync(): void; + getAttributes(): { [s: string]: any }; + getAttribute(): any; + write(str: string): AsyncWriter; + getOutput(): string; + captureString(func: Function, thisObj: Object): string; + swapWriter(newWriter: StringWriter | BufferedWriter, func: Function, thisObj: Object): void; + createNestedWriter(writer: StringWriter | BufferedWriter): AsyncWriter; + beginAsync(options?: number | BeginAsyncOptions): AsyncWriter; + handleBeginAsync(options: number | BeginAsyncOptions, parent: AsyncWriter): void; + on(event: string, callback: Function): AsyncWriter; + once(event: string, callback: Function): AsyncWriter; + onLast(callback: Function): AsyncWriter; + emit(arg: any): AsyncWriter; + removeListener(): AsyncWriter; + pipe(stream: stream.Stream): AsyncWriter; + error(e: Error): void; + end(data?: any): AsyncWriter; + handleEnd(isAsync: boolean): void; + _finish(): void; + flush(): void; + } - function create(writer?: any, options?: AsyncWriterOptions): AsyncWriter; - function enableAsyncStackTrace(): void; - } + interface AsyncWriterOptions { + global?: { [s: string]: any }; + buffer?: boolean; + } - export = async_writer; + function create(writer?: any, options?: AsyncWriterOptions): AsyncWriter; + function enableAsyncStackTrace(): void; } + +export = async_writer; diff --git a/asyncblock/asyncblock.d.ts b/asyncblock/asyncblock.d.ts index 6ec1ad1579..c4f8d3da21 100644 --- a/asyncblock/asyncblock.d.ts +++ b/asyncblock/asyncblock.d.ts @@ -4,70 +4,68 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "asyncblock" { - function asyncblock(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void; - namespace asyncblock { +declare function asyncblock(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void; + +declare namespace asyncblock { export function nostack(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void; export interface IFlow { - add(responseFormat?: string[]): IExecuteFunction; - add(key: string, responseFormat?: string[]): IExecuteFunction; - add(key: number, responseFormat?: string[]): IExecuteFunction; - add(options: IFlowOptions): IExecuteFunction; - callback(responseFormat?: string[]): IExecuteFunction; - callback(key: string, responseFormat?: string[]): IExecuteFunction; - callback(key: number, responseFormat?: string[]): IExecuteFunction; - callback(options: IFlowOptions): IExecuteFunction; - wait(key?: string): T; - wait(key?: number): T; + add(responseFormat?: string[]): IExecuteFunction; + add(key: string, responseFormat?: string[]): IExecuteFunction; + add(key: number, responseFormat?: string[]): IExecuteFunction; + add(options: IFlowOptions): IExecuteFunction; + callback(responseFormat?: string[]): IExecuteFunction; + callback(key: string, responseFormat?: string[]): IExecuteFunction; + callback(key: number, responseFormat?: string[]): IExecuteFunction; + callback(options: IFlowOptions): IExecuteFunction; + wait(key?: string): T; + wait(key?: number): T; - get(key: string): T; - set(key: string, responseFormat?: string[]): IExecuteFunction; - set(options: IFlowOptions): IExecuteFunction; - del(key: string): void; + get(key: string): T; + set(key: string, responseFormat?: string[]): IExecuteFunction; + set(options: IFlowOptions): IExecuteFunction; + del(key: string): void; - sync(task: any): T; - queue(toExecute: IExecuteFunction): void; - queue(key: string, toExecute: IExecuteFunction): void; - queue(key: number, toExecute: IExecuteFunction): void; - queue(responseFormat: string[], toExecute: IExecuteFunction): void; - queue(key: string, responseFormat: string[], toExecute: IExecuteFunction): void; - queue(key: number, responseFormat: string[], toExecute: IExecuteFunction): void; - queue(options: IFlowOptions, toExecute: IExecuteFunction): void; - doneAdding(): void; - forceWait(): T; + sync(task: any): T; + queue(toExecute: IExecuteFunction): void; + queue(key: string, toExecute: IExecuteFunction): void; + queue(key: number, toExecute: IExecuteFunction): void; + queue(responseFormat: string[], toExecute: IExecuteFunction): void; + queue(key: string, responseFormat: string[], toExecute: IExecuteFunction): void; + queue(key: number, responseFormat: string[], toExecute: IExecuteFunction): void; + queue(options: IFlowOptions, toExecute: IExecuteFunction): void; + doneAdding(): void; + forceWait(): T; - maxParallel: number; - errorCallback: (err: any) => void; - taskTimeout: number; - timeoutIsError: boolean; + maxParallel: number; + errorCallback: (err: any) => void; + taskTimeout: number; + timeoutIsError: boolean; } export interface IFlowOptions { - ignoreError?: boolean; // default false - key?: string; // string | number - responseFormat?: string[]; - timeout?: number; - timeoutIsError?: boolean; - dontWait?: boolean; - firstArgIsError?: boolean; // default true + ignoreError?: boolean; // default false + key?: string; // string | number + responseFormat?: string[]; + timeout?: number; + timeoutIsError?: boolean; + dontWait?: boolean; + firstArgIsError?: boolean; // default true } export interface IExecuteFunction { - (err: any, res1: T1, res2: T2, res3: T3): any; - (err: any, res1: T1, res2: T2): any; - (err: any, res: T): any; - (err: any): any; + (err: any, res1: T1, res2: T2, res3: T3): any; + (err: any, res1: T1, res2: T2): any; + (err: any, res: T): any; + (err: any): any; - // firstArgIsError === false - (res1: T1, res2: T2, res3: T3): any; - (res1: T1, res2: T2): any; - (res: T): any; + // firstArgIsError === false + (res1: T1, res2: T2, res3: T3): any; + (res1: T1, res2: T2): any; + (res: T): any; } - } - - export = asyncblock; } +export = asyncblock; diff --git a/atpl/atpl.d.ts b/atpl/atpl.d.ts index a966a8383f..ccb3bfa1c7 100644 --- a/atpl/atpl.d.ts +++ b/atpl/atpl.d.ts @@ -5,16 +5,15 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/atpl.d.ts -declare module "atpl" { - export function compile(templateString: string, options: any): (context:any) => string; - export function __express(filename: string, options: any, callback: Function): any; - export function registerExtension(items: any): void; - export function registerTags(items: any): void; - export function registerFunctions(items: any): void; - export function registerFilters(items: any): void; - export function registerTests(items: any): void; +declare export function compile(templateString: string, options: any): (context: any) => string; +declare export function __express(filename: string, options: any, callback: Function): any; - export function renderFileSync(viewsPath: string, filename: string, parameters: any, cache: boolean ): string; - export function renderFile(viewsPath: string, filename: string, parameters: any, cache: boolean, done: (err: Error, result?: string) => void): void; -} +declare export function registerExtension(items: any): void; +declare export function registerTags(items: any): void; +declare export function registerFunctions(items: any): void; +declare export function registerFilters(items: any): void; +declare export function registerTests(items: any): void; + +declare export function renderFileSync(viewsPath: string, filename: string, parameters: any, cache: boolean): string; +declare export function renderFile(viewsPath: string, filename: string, parameters: any, cache: boolean, done: (err: Error, result?: string) => void): void; diff --git a/autoprefixer-core/autoprefixer-core.d.ts b/autoprefixer-core/autoprefixer-core.d.ts index 2463880441..1b04092a71 100644 --- a/autoprefixer-core/autoprefixer-core.d.ts +++ b/autoprefixer-core/autoprefixer-core.d.ts @@ -3,42 +3,41 @@ // Definitions by: Asana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "autoprefixer-core" { - interface Config { - browsers?: string[]; - cascade?: boolean; - remove?: boolean; - } - interface Options { - from?: string; - to?: string; - safe?: boolean; - map?: { - inline?: boolean; - prev?: string | Object; - } - } - - interface Result { - css: string; - map: string; - opts: Options; - } - - interface Processor { - postcss: any; - info(): string; - process(css: string, opts?: Options): Result; - } - - interface Exports { - (config: Config): Processor; - postcss: any; - info(): string; - process(css: string, opts?: Options): Result; - } - - var exports: Exports; - export = exports; +interface Config { + browsers?: string[]; + cascade?: boolean; + remove?: boolean; } + +interface Options { + from?: string; + to?: string; + safe?: boolean; + map?: { + inline?: boolean; + prev?: string | Object; + } +} + +interface Result { + css: string; + map: string; + opts: Options; +} + +interface Processor { + postcss: any; + info(): string; + process(css: string, opts?: Options): Result; +} + +interface Exports { + (config: Config): Processor; + postcss: any; + info(): string; + process(css: string, opts?: Options): Result; +} + +declare var exports: Exports; +export = exports; diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index eb54a5991d..786e840b84 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -7,1191 +7,1190 @@ /// -declare module "aws-sdk" { - export var config: ClientConfig; - export function Config(json: any): void; +declare export var config: ClientConfig; - export class Credentials { - constructor(accessKeyId: string, secretAccessKey: string, sessionToken?: string); - accessKeyId: string; - } +declare export function Config(json: any): void; - export interface Logger { - write?: (chunk: any, encoding?: string, callback?: () => void) => void; - log?: (...messages: any[]) => void; - } - - export interface HttpOptions { - proxy?: string; - agent?: any; - timeout?: number; - xhrAsync?: boolean; - xhrWithCredentials?: boolean; - } - - export class Endpoint { - constructor(endpoint:string); - - host:string; - hostname:string; - href:string; - port:number; - protocol:string; - } - - export interface Services { - autoscaling?: any; - cloudformation?: any; - cloudfront?: any; - cloudsearch?: any; - cloudsearchdomain?: any; - cloudtrail?: any; - cloudwatch?: any; - cloudwatchlogs?: any; - cognitoidentity?: any; - cognitosync?: any; - datapipeline?: any; - directconnect?: any; - dynamodb?: any; - ec2?: any; - ecs?: any; - elasticache?: any; - elasticbeanstalk?: any; - elastictranscoder?: any; - elb?: any; - emr?: any; - glacier?: any; - httpOptions?: HttpOptions; - iam?: any; - importexport?: any; - kinesis?: any; - opsworks?: any; - rds?: any; - redshift?: any; - route53?: any; - route53domains?: any; - s3?: any; - ses?: any; - simpledb?: any; - sns?: any; - sqs?: any; - storagegateway?: any; - sts?: any; - support?: any; - swf?: any; - } - - export interface ClientConfigPartial extends Services { - credentials?: Credentials; - region?: string; - computeChecksums?: boolean; - convertResponseTypes?: boolean; - logger?: Logger; - maxRedirects?: number; - maxRetries?: number; - paramValidation?: boolean; - s3ForcePathStyle?: boolean; - apiVersion?: any; - apiVersions?: Services; - signatureVersion?: string; - sslEnabled?: boolean; - systemClockOffset?: number; - } - - export interface ClientConfig extends ClientConfigPartial { - update?: (options: ClientConfigPartial, allUnknownKeys?: boolean) => void; - getCredentials?: (callback: (err?: any) => void) => void ; - loadFromPath?: (path: string) => void; - credentials: Credentials; - region: string; - } - - export class SQS { - constructor(options?: any); - endpoint:Endpoint; - - addPermission(params: SQS.AddPermissionParams, callback: (err:Error, data:any) => void): void; - changeMessageVisibility(params: SQS.ChangeMessageVisibilityParams, callback: (err:Error, data:any) => void): void; - changeMessageVisibilityBatch(params: SQS.ChangeMessageVisibilityBatchParams, callback: (err:Error, data:SQS.ChangeMessageVisibilityBatchResponse) => void): void; - createQueue(params: SQS.CreateQueueParams, callback: (err: Error, data: SQS.CreateQueueResult) => void): void; - deleteMessage(params: SQS.DeleteMessageParams, callback: (err: Error, data: any) => void): void; - deleteMessageBatch(params: SQS.DeleteMessageBatchParams, callback: (err: Error, data: SQS.DeleteMessageBatchResult) => void): void; - deleteQueue(params: { QueueUrl: string; }, callback: (err: Error, data: any) => void): void; - getQueueAttributes(params: SQS.GetQueueAttributesParams, callback: (err: Error, data: SQS.GetQueueAttributesResult) => void): void; - getQueueUrl(params: SQS.GetQueueUrlParams, callback: (err: Error, data: { QueueUrl: string; }) => void): void; - listDeadLetterSourceQueues(params: {QueueUrl:string}, callback: (err: Error, data: {queueUrls: string[]}) => void): void; - listQueues(params: {QueueNamePrefix?:string}, callback: (err: Error, data: {QueueUrls: string[]}) => void): void; - purgeQueue(params: {QueueUrl: string}, callback: (err: Error, data: any) => void): void; - receiveMessage(params: SQS.ReceiveMessageParams, callback: (err: Error, data: SQS.ReceiveMessageResult) => void): void; - removePermission(params: {QueueUrl: string, Label: string}, callback: (err: Error, data: any) => void): void; - sendMessage(params: SQS.SendMessageParams, callback: (err: Error, data: SQS.SendMessageResult) => void): void; - sendMessageBatch(params: SQS.SendMessageBatchParams, callback: (err: Error, data: SQS.SendMessageBatchResult) => void): void; - setQueueAttributes(params: SQS.SetQueueAttributesParams, callback: (err: Error, data: any) => void): void; - } - - export class SES { - constructor(options?: any); - public client: Ses.Client; - } - - export class SNS { - constructor(options?: any); - public client: Sns.Client; - } - - export class SimpleWorkflow { - constructor(options?: any); - public client: Swf.Client; - } - - export class S3 { - constructor(options?: any); - putObject(params: s3.PutObjectRequest, callback: (err: any, data: any) => void): void; - getObject(params: s3.GetObjectRequest, callback: (err: any, data: any) => void): void; - } - - export class ECS { - constructor(options?: any); - - createService(params: ecs.CreateServicesParams, callback: (err: any, data: any) => void): void; - describeServices(params: ecs.DescribeServicesParams, callback: (err: any, data: any) => void): void; - describeTaskDefinition(params: ecs.DescribeTaskDefinitionParams, callback: (err: any, data: any) => void): void; - registerTaskDefinition(params: ecs.RegisterTaskDefinitionParams, callback: (err: any, data: any) => void): void; - updateService(params: ecs.UpdateServiceParams, callback: (err: any, data: any) => void): void; - } - - export class DynamoDB { - constructor(options?: any); - } - - export module DynamoDB { - export class DocumentClient { - constructor(options?: any); - } - } - - export module SQS { - - export interface SqsOptions { - params?: any; - endpoint?: string; - accessKeyId?: string; - secretAccessKey?: string; - sessionToken?: Credentials; - credentials?: Credentials; - credentialProvider?: any; - region?: string; - maxRetries?: number; - maxRedirects?: number; - sslEnabled?: boolean; - paramValidation?: boolean; - computeChecksums?: boolean; - convertResponseTypes?: boolean; - correctClockSkew?: boolean; - s3ForcePathStyle?: boolean; - s3BucketEndpoint?: boolean; - httpOptions?: HttpOptions; - apiVersion?: string; - apiVersions?: { [serviceName:string]: string}; - logger?: Logger; - systemClockOffset?: number; - signatureVersion?: string; - signatureCache?: boolean; - } - - export interface AddPermissionParams { - QueueUrl: string; - Label: string; - AWSAccountIds:string[]; - Actions:string[]; - } - - export interface ChangeMessageVisibilityParams { - QueueUrl: string, - ReceiptHandle: string, - VisibilityTimeout: number - } - - export interface ChangeMessageVisibilityBatchParams { - QueueUrl: string, - Entries: { Id: string; ReceiptHandle: string; VisibilityTimeout?: number; }[] - } - - export interface ChangeMessageVisibilityBatchResponse { - Successful: { Id:string }[]; - Failed: BatchResultErrorEntry[]; - } - - export interface SendMessageParams { - QueueUrl: string; - MessageBody: string; - DelaySeconds?: number; - MessageAttributes?: { [name:string]: MessageAttribute; } - } - - export interface ReceiveMessageParams { - QueueUrl: string; - MaxNumberOfMessages?: number; - VisibilityTimeout?: number; - AttributeNames?: string[]; - MessageAttributeNames?: string[]; - WaitTimeSeconds?:number; - } - - export interface DeleteMessageBatchParams { - QueueUrl: string; - Entries: DeleteMessageBatchRequestEntry[]; - } - - export interface DeleteMessageBatchRequestEntry { - Id: string; - ReceiptHandle: string; - } - - export interface DeleteMessageParams { - QueueUrl: string; - ReceiptHandle: string; - } - - export interface SendMessageBatchParams { - QueueUrl: string; - Entries: SendMessageBatchRequestEntry[]; - } - - export interface SendMessageBatchRequestEntry { - Id: string; - MessageBody: string; - DelaySeconds?: number; - MessageAttributes?: { [name:string]: MessageAttribute; } - } - - export interface CreateQueueParams { - QueueName: string; - Attributes: QueueAttributes; - } - - export interface QueueAttributes { - [name:string]: any; - DelaySeconds?: number; - MaximumMessageSize?: number; - MessageRetentionPeriod?: number; - Policy?: any; - ReceiveMessageWaitTimeSeconds?: number; - VisibilityTimeout?: number; - RedrivePolicy?: any; - } - - export interface GetQueueAttributesParams { - QueueUrl: string; - AttributeNames: string[]; - } - - export interface GetQueueAttributesResult { - Attributes: {[name:string]: string}; - } - - export interface GetQueueUrlParams { - QueueName: string; - QueueOwnerAWSAccountId?: string; - } - - export interface SendMessageResult { - MessageId: string; - MD5OfMessageBody: string; - MD5OfMessageAttributes: string; - } - - export interface ReceiveMessageResult { - Messages: Message[]; - } - - export interface Message { - MessageId: string; - ReceiptHandle: string; - MD5OfBody: string; - Body: string; - Attributes: { [name:string]:any }; - MD5OfMessageAttributes:string; - MessageAttributes: { [name:string]: MessageAttribute; } - } - - export interface MessageAttribute { - StringValue?: string; - BinaryValue?: any; //(Buffer, Typed Array, Blob, String) - StringListValues?: string[]; - BinaryListValues?: any[]; - DataType: string; - } - - export interface DeleteMessageBatchResult { - Successful: DeleteMessageBatchResultEntry[]; - Failed: BatchResultErrorEntry[]; - } - - export interface DeleteMessageBatchResultEntry { - Id: string; - } - - export interface BatchResultErrorEntry { - Id: string; - Code: string; - Message?: string; - SenderFault: boolean; - } - - export interface SendMessageBatchResult { - Successful: SendMessageBatchResultEntry[]; - Failed: BatchResultErrorEntry[]; - } - - export interface SendMessageBatchResultEntry { - Id: string; - MessageId: string; - MD5OfMessageBody: string; - MD5OfMessageAttributes:string; - } - - export interface CreateQueueResult { - QueueUrl: string; - } - - export interface SetQueueAttributesParams { - QueueUrl: string; - Attributes: QueueAttributes; - } - - } - - export module Ses { - - export interface Client { - config: ClientConfig; - - sendEmail(params: any, callback: (err: any, data: SendEmailResult) => void): void; - } - - export interface SendEmailRequest { - Source: string; - Destination: Destination; - Message: Message; - ReplyToAddresses: string[]; - ReturnPath: string; - } - - export class Destination { - ToAddresses: string[]; - CcAddresses: string[]; - BccAddresses: string[]; - } - - export class Message { - Subject: Content; - Body: Body; - } - - export class Content { - Data: string; - Charset: string; - } - - export class Body { - Text: Content; - Html: Content; - } - - export class SendEmailResult { - MessageId: string; - } - - } - - export module Swf { - - export class Client { - //constructor(options?: any); - public config: ClientConfig; - - countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void; - countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void; - deprecateActivityType(params: any, callback: (err: any, data: any) => void): void; - deprecateDomain(params: any, callback: (err: any, data: any) => void): void; - deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void; - describeActivityType(params: any, callback: (err: any, data: any) => void): void; - describeDomain(params: any, callback: (err: any, data: any) => void): void; - describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - describeWorkflowType(params: any, callback: (err: any, data: any) => void): void; - getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void; - listActivityTypes(params: any, callback: (err: any, data: any) => void): void; - listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - listDomains(params: any, callback: (err: any, data: any) => void): void; - listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; - listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void; - pollForActivityTask(params: any, callback: (err: any, data: ActivityTask) => void): void; - pollForDecisionTask(params: any, callback: (err: any, data: DecisionTask) => void): void; - recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void; - registerActivityType(params: any, callback: (err: any, data: any) => void): void; - registerDomain(params: any, callback: (err: any, data: any) => void): void; - registerWorkflowType(params: any, callback: (err: any, data: any) => void): void; - requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - respondActivityTaskCanceled(params: RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void; - respondActivityTaskCompleted(params: RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void; - respondActivityTaskFailed(params: RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void; - respondDecisionTaskCompleted(params: RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void; - signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - startWorkflowExecution(params: any, callback: (err: any, data: StartWorkflowExecutionResult) => void): void; - terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; - } - - export interface PollForActivityTaskRequest { - domain?: string; - taskList?: TaskList; - identity?: string; - } - - export interface TaskList { - name?: string; - } - - export interface PollForDecisionTaskRequest { - domain?: string; - taskList?: TaskList; - identity?: string; - nextPageToken?: string; - maximumPageSize?: number; - reverseOrder?: Boolean; - } - - export interface StartWorkflowExecutionRequest { - domain?: string; - workflowId?: string; - workflowType?: WorkflowType; - taskList?: TaskList; - input?: string; - executionStartToCloseTimeout?: string; - tagList?: string[]; - taskStartToCloseTimeout?: string; - childPolicy?: string; - } - - export interface WorkflowType { - name?: string; - version?: string; - } - - export interface RespondDecisionTaskCompletedRequest { - taskToken?: string; - decisions?: Decision[]; - executionContext?: string; - } - - export interface Decision { - decisionType?: string; - scheduleActivityTaskDecisionAttributes?: ScheduleActivityTaskDecisionAttributes; - requestCancelActivityTaskDecisionAttributes?: RequestCancelActivityTaskDecisionAttributes; - completeWorkflowExecutionDecisionAttributes?: CompleteWorkflowExecutionDecisionAttributes; - failWorkflowExecutionDecisionAttributes?: FailWorkflowExecutionDecisionAttributes; - cancelWorkflowExecutionDecisionAttributes?: CancelWorkflowExecutionDecisionAttributes; - continueAsNewWorkflowExecutionDecisionAttributes?: ContinueAsNewWorkflowExecutionDecisionAttributes; - recordMarkerDecisionAttributes?: RecordMarkerDecisionAttributes; - startTimerDecisionAttributes?: StartTimerDecisionAttributes; - cancelTimerDecisionAttributes?: CancelTimerDecisionAttributes; - signalExternalWorkflowExecutionDecisionAttributes?: SignalExternalWorkflowExecutionDecisionAttributes; - requestCancelExternalWorkflowExecutionDecisionAttributes?: RequestCancelExternalWorkflowExecutionDecisionAttributes; - startChildWorkflowExecutionDecisionAttributes?: StartChildWorkflowExecutionDecisionAttributes; - } - - export interface ScheduleActivityTaskDecisionAttributes { - activityType?: ActivityType; - activityId?: string; - control?: string; - input?: string; - scheduleToCloseTimeout?: string; - taskList?: TaskList; - scheduleToStartTimeout?: string; - startToCloseTimeout?: string; - heartbeatTimeout?: string; - } - - export interface ActivityType { - name?: string; - version?: string; - } - - export interface RequestCancelActivityTaskDecisionAttributes { - activityId?: string; - } - - export interface CompleteWorkflowExecutionDecisionAttributes { - result?: string; - } - - export interface FailWorkflowExecutionDecisionAttributes { - reason?: string; - details?: string; - } - - export interface CancelWorkflowExecutionDecisionAttributes { - details?: string; - } - - export interface ContinueAsNewWorkflowExecutionDecisionAttributes { - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - workflowTypeVersion?: string; - } - - export interface RecordMarkerDecisionAttributes { - markerName?: string; - details?: string; - } - - export interface StartTimerDecisionAttributes { - timerId?: string; - control?: string; - startToFireTimeout?: string; - } - - export interface CancelTimerDecisionAttributes { - timerId?: string; - } - - export interface SignalExternalWorkflowExecutionDecisionAttributes { - workflowId?: string; - runId?: string; - signalName?: string; - input?: string; - control?: string; - } - - export interface RequestCancelExternalWorkflowExecutionDecisionAttributes { - workflowId?: string; - runId?: string; - control?: string; - } - - export interface StartChildWorkflowExecutionDecisionAttributes { - workflowType?: WorkflowType; - workflowId?: string; - control?: string; - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - } - - export interface RespondActivityTaskCompletedRequest { - taskToken?: string; - result?: string; - } - - export interface RespondActivityTaskFailedRequest { - taskToken?: string; - reason?: string; - details?: string; - } - - export interface RespondActivityTaskCanceledRequest { - taskToken?: string; - details?: string; - } - - export interface DecisionTask { - taskToken?: string; - startedEventId?: number; - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - events?: HistoryEvent[]; - nextPageToken?: string; - previousStartedEventId?: number; - } - - export interface WorkflowExecution { - workflowId?: string; - runId?: string; - } - - export interface HistoryEvent { - eventTimestamp?: any; - eventType?: string; - eventId?: number; - workflowExecutionStartedEventAttributes?: WorkflowExecutionStartedEventAttributes; - workflowExecutionCompletedEventAttributes?: WorkflowExecutionCompletedEventAttributes; - completeWorkflowExecutionFailedEventAttributes?: CompleteWorkflowExecutionFailedEventAttributes; - workflowExecutionFailedEventAttributes?: WorkflowExecutionFailedEventAttributes; - failWorkflowExecutionFailedEventAttributes?: FailWorkflowExecutionFailedEventAttributes; - workflowExecutionTimedOutEventAttributes?: WorkflowExecutionTimedOutEventAttributes; - workflowExecutionCanceledEventAttributes?: WorkflowExecutionCanceledEventAttributes; - cancelWorkflowExecutionFailedEventAttributes?: CancelWorkflowExecutionFailedEventAttributes; - workflowExecutionContinuedAsNewEventAttributes?: WorkflowExecutionContinuedAsNewEventAttributes; - continueAsNewWorkflowExecutionFailedEventAttributes?: ContinueAsNewWorkflowExecutionFailedEventAttributes; - workflowExecutionTerminatedEventAttributes?: WorkflowExecutionTerminatedEventAttributes; - workflowExecutionCancelRequestedEventAttributes?: WorkflowExecutionCancelRequestedEventAttributes; - decisionTaskScheduledEventAttributes?: DecisionTaskScheduledEventAttributes; - decisionTaskStartedEventAttributes?: DecisionTaskStartedEventAttributes; - decisionTaskCompletedEventAttributes?: DecisionTaskCompletedEventAttributes; - decisionTaskTimedOutEventAttributes?: DecisionTaskTimedOutEventAttributes; - activityTaskScheduledEventAttributes?: ActivityTaskScheduledEventAttributes; - activityTaskStartedEventAttributes?: ActivityTaskStartedEventAttributes; - activityTaskCompletedEventAttributes?: ActivityTaskCompletedEventAttributes; - activityTaskFailedEventAttributes?: ActivityTaskFailedEventAttributes; - activityTaskTimedOutEventAttributes?: ActivityTaskTimedOutEventAttributes; - activityTaskCanceledEventAttributes?: ActivityTaskCanceledEventAttributes; - activityTaskCancelRequestedEventAttributes?: ActivityTaskCancelRequestedEventAttributes; - workflowExecutionSignaledEventAttributes?: WorkflowExecutionSignaledEventAttributes; - markerRecordedEventAttributes?: MarkerRecordedEventAttributes; - timerStartedEventAttributes?: TimerStartedEventAttributes; - timerFiredEventAttributes?: TimerFiredEventAttributes; - timerCanceledEventAttributes?: TimerCanceledEventAttributes; - startChildWorkflowExecutionInitiatedEventAttributes?: StartChildWorkflowExecutionInitiatedEventAttributes; - childWorkflowExecutionStartedEventAttributes?: ChildWorkflowExecutionStartedEventAttributes; - childWorkflowExecutionCompletedEventAttributes?: ChildWorkflowExecutionCompletedEventAttributes; - childWorkflowExecutionFailedEventAttributes?: ChildWorkflowExecutionFailedEventAttributes; - childWorkflowExecutionTimedOutEventAttributes?: ChildWorkflowExecutionTimedOutEventAttributes; - childWorkflowExecutionCanceledEventAttributes?: ChildWorkflowExecutionCanceledEventAttributes; - childWorkflowExecutionTerminatedEventAttributes?: ChildWorkflowExecutionTerminatedEventAttributes; - signalExternalWorkflowExecutionInitiatedEventAttributes?: SignalExternalWorkflowExecutionInitiatedEventAttributes; - externalWorkflowExecutionSignaledEventAttributes?: ExternalWorkflowExecutionSignaledEventAttributes; - signalExternalWorkflowExecutionFailedEventAttributes?: SignalExternalWorkflowExecutionFailedEventAttributes; - externalWorkflowExecutionCancelRequestedEventAttributes?: ExternalWorkflowExecutionCancelRequestedEventAttributes; - requestCancelExternalWorkflowExecutionInitiatedEventAttributes?: RequestCancelExternalWorkflowExecutionInitiatedEventAttributes; - requestCancelExternalWorkflowExecutionFailedEventAttributes?: RequestCancelExternalWorkflowExecutionFailedEventAttributes; - scheduleActivityTaskFailedEventAttributes?: ScheduleActivityTaskFailedEventAttributes; - requestCancelActivityTaskFailedEventAttributes?: RequestCancelActivityTaskFailedEventAttributes; - startTimerFailedEventAttributes?: StartTimerFailedEventAttributes; - cancelTimerFailedEventAttributes?: CancelTimerFailedEventAttributes; - startChildWorkflowExecutionFailedEventAttributes?: StartChildWorkflowExecutionFailedEventAttributes; - } - - export interface WorkflowExecutionStartedEventAttributes { - input?: string; - executionStartToCloseTimeout?: string; - taskStartToCloseTimeout?: string; - childPolicy?: string; - taskList?: TaskList; - workflowType?: WorkflowType; - tagList?: string[]; - continuedExecutionRunId?: string; - parentWorkflowExecution?: WorkflowExecution; - parentInitiatedEventId?: number; - } - - export interface WorkflowExecutionCompletedEventAttributes { - result?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CompleteWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionFailedEventAttributes { - reason?: string; - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface FailWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionTimedOutEventAttributes { - timeoutType?: string; - childPolicy?: string; - } - - export interface WorkflowExecutionCanceledEventAttributes { - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CancelWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionContinuedAsNewEventAttributes { - input?: string; - decisionTaskCompletedEventId?: number; - newExecutionRunId?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - taskStartToCloseTimeout?: string; - childPolicy?: string; - tagList?: string[]; - workflowType?: WorkflowType; - } - - export interface ContinueAsNewWorkflowExecutionFailedEventAttributes { - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface WorkflowExecutionTerminatedEventAttributes { - reason?: string; - details?: string; - childPolicy?: string; - cause?: string; - } - - export interface WorkflowExecutionCancelRequestedEventAttributes { - externalWorkflowExecution?: WorkflowExecution; - externalInitiatedEventId?: number; - cause?: string; - } - - export interface DecisionTaskScheduledEventAttributes { - taskList?: TaskList; - startToCloseTimeout?: string; - } - - export interface DecisionTaskStartedEventAttributes { - identity?: string; - scheduledEventId?: number; - } - - export interface DecisionTaskCompletedEventAttributes { - executionContext?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface DecisionTaskTimedOutEventAttributes { - timeoutType?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskScheduledEventAttributes { - activityType?: ActivityType; - activityId?: string; - input?: string; - control?: string; - scheduleToStartTimeout?: string; - scheduleToCloseTimeout?: string; - startToCloseTimeout?: string; - taskList?: TaskList; - decisionTaskCompletedEventId?: number; - heartbeatTimeout?: string; - } - - export interface ActivityTaskStartedEventAttributes { - identity?: string; - scheduledEventId?: number; - } - - export interface ActivityTaskCompletedEventAttributes { - result?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskFailedEventAttributes { - reason?: string; - details?: string; - scheduledEventId?: number; - startedEventId?: number; - } - - export interface ActivityTaskTimedOutEventAttributes { - timeoutType?: string; - scheduledEventId?: number; - startedEventId?: number; - details?: string; - } - - export interface ActivityTaskCanceledEventAttributes { - details?: string; - scheduledEventId?: number; - startedEventId?: number; - latestCancelRequestedEventId?: number; - } - - export interface ActivityTaskCancelRequestedEventAttributes { - decisionTaskCompletedEventId?: number; - activityId?: string; - } - - export interface WorkflowExecutionSignaledEventAttributes { - signalName?: string; - input?: string; - externalWorkflowExecution?: WorkflowExecution; - externalInitiatedEventId?: number; - } - - export interface MarkerRecordedEventAttributes { - markerName?: string; - details?: string; - decisionTaskCompletedEventId?: number; - } - - export interface TimerStartedEventAttributes { - timerId?: string; - control?: string; - startToFireTimeout?: string; - decisionTaskCompletedEventId?: number; - } - - export interface TimerFiredEventAttributes { - timerId?: string; - startedEventId?: number; - } - - export interface TimerCanceledEventAttributes { - timerId?: string; - startedEventId?: number; - decisionTaskCompletedEventId?: number; - } - - export interface StartChildWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - workflowType?: WorkflowType; - control?: string; - input?: string; - executionStartToCloseTimeout?: string; - taskList?: TaskList; - decisionTaskCompletedEventId?: number; - childPolicy?: string; - taskStartToCloseTimeout?: string; - tagList?: string[]; - } - - export interface ChildWorkflowExecutionStartedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - initiatedEventId?: number; - } - - export interface ChildWorkflowExecutionCompletedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - result?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionFailedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - reason?: string; - details?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionTimedOutEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - timeoutType?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionCanceledEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - details?: string; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface ChildWorkflowExecutionTerminatedEventAttributes { - workflowExecution?: WorkflowExecution; - workflowType?: WorkflowType; - initiatedEventId?: number; - startedEventId?: number; - } - - export interface SignalExternalWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - runId?: string; - signalName?: string; - input?: string; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ExternalWorkflowExecutionSignaledEventAttributes { - workflowExecution?: WorkflowExecution; - initiatedEventId?: number; - } - - export interface SignalExternalWorkflowExecutionFailedEventAttributes { - workflowId?: string; - runId?: string; - cause?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ExternalWorkflowExecutionCancelRequestedEventAttributes { - workflowExecution?: WorkflowExecution; - initiatedEventId?: number; - } - - export interface RequestCancelExternalWorkflowExecutionInitiatedEventAttributes { - workflowId?: string; - runId?: string; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface RequestCancelExternalWorkflowExecutionFailedEventAttributes { - workflowId?: string; - runId?: string; - cause?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ScheduleActivityTaskFailedEventAttributes { - activityType?: ActivityType; - activityId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface RequestCancelActivityTaskFailedEventAttributes { - activityId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface StartTimerFailedEventAttributes { - timerId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface CancelTimerFailedEventAttributes { - timerId?: string; - cause?: string; - decisionTaskCompletedEventId?: number; - } - - export interface StartChildWorkflowExecutionFailedEventAttributes { - workflowType?: WorkflowType; - cause?: string; - workflowId?: string; - initiatedEventId?: number; - decisionTaskCompletedEventId?: number; - control?: string; - } - - export interface ActivityTask { - taskToken?: string; - activityId?: string; - startedEventId?: number; - workflowExecution?: WorkflowExecution; - activityType?: ActivityType; - input?: string; - } - - export interface PollForActivityTaskResult { - activityTask?: ActivityTask; - } - - export interface PollForDecisionTaskResult { - decisionTask?: DecisionTask; - } - - export interface StartWorkflowExecutionResult { - run?: Run; - } - - export interface Run { - runId?: string; - } - - } - - export module Sns { - - export interface Client { - config: ClientConfig; - - publicTopic(params: PublishRequest, callback: (err: any, data: PublishResult) => void): void; - createTopic(params: CreateTopicRequest, callback: (err: any, data: CreateTopicResult) => void): void; - deleteTopic(params: DeleteTopicRequest, callback: (err: any, data: any) => void): void; - } - - export interface PublishRequest { - TopicArn?: string; - Message?: string; - MessageStructure?: string; - Subject?: string; - } - - export interface PublishResult { - MessageId?: string; - } - - export interface CreateTopicRequest { - Name?: string; - } - - export interface CreateTopicResult { - TopicArn?: string; - } - - export interface DeleteTopicRequest { - TopicArn?: string; - } - - } - - export module s3 { - - export interface PutObjectRequest { - ACL?: string; - Body?: any; - Bucket: string; - CacheControl?: string; - ContentDisposition?: string; - ContentEncoding?: string; - ContentLanguage?: string; - ContentLength?: string; - ContentMD5?: string; - ContentType?: string; - Expires?: any; - GrantFullControl?: string; - GrantRead?: string; - GrantReadACP?: string; - GrantWriteACP?: string; - Key: string; - Metadata?: string[]; - ServerSideEncryption?: string; - StorageClass?: string; - WebsiteRedirectLocation?: string; - } - - export interface GetObjectRequest { - Bucket: string; - IfMatch?: string; - IfModifiedSince?: any; - IfNoneMatch?: string; - IfUnmodifiedSince?: any; - Key: string; - Range?: string; - ResponseCacheControl?: string; - ResponseContentDisposition?: string; - ResponseContentEncoding?: string; - ResponseContentLanguage?: string; - ResponseContentType?: string; - ResponseExpires?: any; - VersionId?: string; - } - - } - - export module ecs { - export interface CreateServicesParams { - desiredCount: number; - serviceName: string; - taskDefinition: string; - clientToken?: string; - cluster?: string; - deploymentConfiguration?: { - maximumPercent?: number; - minimumHealthyPercent?: number; - }; - loadBalancers?: { - containerName?: string; - containerPort?: number; - loadBalancerName?: string; - }[]; - role?: string; - } - - export interface DescribeServicesParams { - services: string[]; - cluster: string; - } - - export interface DescribeTaskDefinitionParams { - taskDefinition: string; - } - - export interface RegisterTaskDefinitionParams { - containerDefinitions: { - command?: string[], - cpu?: number, - disableNetworking?: boolean, - dnsSearchDomains?: string[], - dnsServers?: string[], - dockerLabels?: any, - dockerSecurityOptions?: string[], - entryPoint?: string[], - environment?: any[], - essential?: boolean, - extraHosts?: { - hostName: string, - ipAddress: string - }[]; - hostname?: string, - image?: string, - links?: string[], - logConfiguration?: { - logDriver: string, - options: any - }[], - memory?: number, - mountPoints?: { - containerPath: string, - readOnly: boolean, - sourceVolume: string - }[]; - name?: string, - portMappings?: { - containerPort?: number, - hostPort?: number, - protocol: string - }[]; - privileged?: boolean, - readonlyRootFilesystem?: boolean, - ulimits?: { - hardLimit: number, - name: string, - softLimit: number - }[]; - user?: string, - volumesFrom?: { - readOnly?: boolean, - sourceContainer?: string - }[], - workingDirectory?: string - }[]; - family: string; - volumes?: { - host: { - sourcePath: string - }, - name: string - }[]; - } - - export interface UpdateServiceParams { - service: string; - cluster?: string; - deploymentConfiguration?: { - maximumPercent: number; - minimumHealthyPercent: number; - }; - desiredCount?: number; - taskDefinition: string; - } - } +declare export class Credentials { + constructor(accessKeyId: string, secretAccessKey: string, sessionToken?: string); + accessKeyId: string; +} + +export interface Logger { + write?: (chunk: any, encoding?: string, callback?: () => void) => void; + log?: (...messages: any[]) => void; +} + +export interface HttpOptions { + proxy?: string; + agent?: any; + timeout?: number; + xhrAsync?: boolean; + xhrWithCredentials?: boolean; +} + +declare export class Endpoint { + constructor(endpoint: string); + + host: string; + hostname: string; + href: string; + port: number; + protocol: string; +} + +export interface Services { + autoscaling?: any; + cloudformation?: any; + cloudfront?: any; + cloudsearch?: any; + cloudsearchdomain?: any; + cloudtrail?: any; + cloudwatch?: any; + cloudwatchlogs?: any; + cognitoidentity?: any; + cognitosync?: any; + datapipeline?: any; + directconnect?: any; + dynamodb?: any; + ec2?: any; + ecs?: any; + elasticache?: any; + elasticbeanstalk?: any; + elastictranscoder?: any; + elb?: any; + emr?: any; + glacier?: any; + httpOptions?: HttpOptions; + iam?: any; + importexport?: any; + kinesis?: any; + opsworks?: any; + rds?: any; + redshift?: any; + route53?: any; + route53domains?: any; + s3?: any; + ses?: any; + simpledb?: any; + sns?: any; + sqs?: any; + storagegateway?: any; + sts?: any; + support?: any; + swf?: any; +} + +export interface ClientConfigPartial extends Services { + credentials?: Credentials; + region?: string; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + logger?: Logger; + maxRedirects?: number; + maxRetries?: number; + paramValidation?: boolean; + s3ForcePathStyle?: boolean; + apiVersion?: any; + apiVersions?: Services; + signatureVersion?: string; + sslEnabled?: boolean; + systemClockOffset?: number; +} + +export interface ClientConfig extends ClientConfigPartial { + update?: (options: ClientConfigPartial, allUnknownKeys?: boolean) => void; + getCredentials?: (callback: (err?: any) => void) => void; + loadFromPath?: (path: string) => void; + credentials: Credentials; + region: string; +} + +declare export class SQS { + constructor(options?: any); + endpoint: Endpoint; + + addPermission(params: SQS.AddPermissionParams, callback: (err: Error, data: any) => void): void; + changeMessageVisibility(params: SQS.ChangeMessageVisibilityParams, callback: (err: Error, data: any) => void): void; + changeMessageVisibilityBatch(params: SQS.ChangeMessageVisibilityBatchParams, callback: (err: Error, data: SQS.ChangeMessageVisibilityBatchResponse) => void): void; + createQueue(params: SQS.CreateQueueParams, callback: (err: Error, data: SQS.CreateQueueResult) => void): void; + deleteMessage(params: SQS.DeleteMessageParams, callback: (err: Error, data: any) => void): void; + deleteMessageBatch(params: SQS.DeleteMessageBatchParams, callback: (err: Error, data: SQS.DeleteMessageBatchResult) => void): void; + deleteQueue(params: { QueueUrl: string; }, callback: (err: Error, data: any) => void): void; + getQueueAttributes(params: SQS.GetQueueAttributesParams, callback: (err: Error, data: SQS.GetQueueAttributesResult) => void): void; + getQueueUrl(params: SQS.GetQueueUrlParams, callback: (err: Error, data: { QueueUrl: string; }) => void): void; + listDeadLetterSourceQueues(params: { QueueUrl: string }, callback: (err: Error, data: { queueUrls: string[] }) => void): void; + listQueues(params: { QueueNamePrefix?: string }, callback: (err: Error, data: { QueueUrls: string[] }) => void): void; + purgeQueue(params: { QueueUrl: string }, callback: (err: Error, data: any) => void): void; + receiveMessage(params: SQS.ReceiveMessageParams, callback: (err: Error, data: SQS.ReceiveMessageResult) => void): void; + removePermission(params: { QueueUrl: string, Label: string }, callback: (err: Error, data: any) => void): void; + sendMessage(params: SQS.SendMessageParams, callback: (err: Error, data: SQS.SendMessageResult) => void): void; + sendMessageBatch(params: SQS.SendMessageBatchParams, callback: (err: Error, data: SQS.SendMessageBatchResult) => void): void; + setQueueAttributes(params: SQS.SetQueueAttributesParams, callback: (err: Error, data: any) => void): void; +} + +declare export class SES { + constructor(options?: any); + public client: Ses.Client; +} + +declare export class SNS { + constructor(options?: any); + public client: Sns.Client; +} + +declare export class SimpleWorkflow { + constructor(options?: any); + public client: Swf.Client; +} + +declare export class S3 { + constructor(options?: any); + putObject(params: s3.PutObjectRequest, callback: (err: any, data: any) => void): void; + getObject(params: s3.GetObjectRequest, callback: (err: any, data: any) => void): void; +} + +declare export class ECS { + constructor(options?: any); + + createService(params: ecs.CreateServicesParams, callback: (err: any, data: any) => void): void; + describeServices(params: ecs.DescribeServicesParams, callback: (err: any, data: any) => void): void; + describeTaskDefinition(params: ecs.DescribeTaskDefinitionParams, callback: (err: any, data: any) => void): void; + registerTaskDefinition(params: ecs.RegisterTaskDefinitionParams, callback: (err: any, data: any) => void): void; + updateService(params: ecs.UpdateServiceParams, callback: (err: any, data: any) => void): void; +} + +declare export class DynamoDB { + constructor(options?: any); +} + +declare export module DynamoDB { + export class DocumentClient { + constructor(options?: any); + } +} + +declare export module SQS { + + export interface SqsOptions { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: Credentials; + credentials?: Credentials; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: boolean; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + httpOptions?: HttpOptions; + apiVersion?: string; + apiVersions?: { [serviceName: string]: string }; + logger?: Logger; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; + } + + export interface AddPermissionParams { + QueueUrl: string; + Label: string; + AWSAccountIds: string[]; + Actions: string[]; + } + + export interface ChangeMessageVisibilityParams { + QueueUrl: string, + ReceiptHandle: string, + VisibilityTimeout: number + } + + export interface ChangeMessageVisibilityBatchParams { + QueueUrl: string, + Entries: { Id: string; ReceiptHandle: string; VisibilityTimeout?: number; }[] + } + + export interface ChangeMessageVisibilityBatchResponse { + Successful: { Id: string }[]; + Failed: BatchResultErrorEntry[]; + } + + export interface SendMessageParams { + QueueUrl: string; + MessageBody: string; + DelaySeconds?: number; + MessageAttributes?: { [name: string]: MessageAttribute; } + } + + export interface ReceiveMessageParams { + QueueUrl: string; + MaxNumberOfMessages?: number; + VisibilityTimeout?: number; + AttributeNames?: string[]; + MessageAttributeNames?: string[]; + WaitTimeSeconds?: number; + } + + export interface DeleteMessageBatchParams { + QueueUrl: string; + Entries: DeleteMessageBatchRequestEntry[]; + } + + export interface DeleteMessageBatchRequestEntry { + Id: string; + ReceiptHandle: string; + } + + export interface DeleteMessageParams { + QueueUrl: string; + ReceiptHandle: string; + } + + export interface SendMessageBatchParams { + QueueUrl: string; + Entries: SendMessageBatchRequestEntry[]; + } + + export interface SendMessageBatchRequestEntry { + Id: string; + MessageBody: string; + DelaySeconds?: number; + MessageAttributes?: { [name: string]: MessageAttribute; } + } + + export interface CreateQueueParams { + QueueName: string; + Attributes: QueueAttributes; + } + + export interface QueueAttributes { + [name: string]: any; + DelaySeconds?: number; + MaximumMessageSize?: number; + MessageRetentionPeriod?: number; + Policy?: any; + ReceiveMessageWaitTimeSeconds?: number; + VisibilityTimeout?: number; + RedrivePolicy?: any; + } + + export interface GetQueueAttributesParams { + QueueUrl: string; + AttributeNames: string[]; + } + + export interface GetQueueAttributesResult { + Attributes: { [name: string]: string }; + } + + export interface GetQueueUrlParams { + QueueName: string; + QueueOwnerAWSAccountId?: string; + } + + export interface SendMessageResult { + MessageId: string; + MD5OfMessageBody: string; + MD5OfMessageAttributes: string; + } + + export interface ReceiveMessageResult { + Messages: Message[]; + } + + export interface Message { + MessageId: string; + ReceiptHandle: string; + MD5OfBody: string; + Body: string; + Attributes: { [name: string]: any }; + MD5OfMessageAttributes: string; + MessageAttributes: { [name: string]: MessageAttribute; } + } + + export interface MessageAttribute { + StringValue?: string; + BinaryValue?: any; //(Buffer, Typed Array, Blob, String) + StringListValues?: string[]; + BinaryListValues?: any[]; + DataType: string; + } + + export interface DeleteMessageBatchResult { + Successful: DeleteMessageBatchResultEntry[]; + Failed: BatchResultErrorEntry[]; + } + + export interface DeleteMessageBatchResultEntry { + Id: string; + } + + export interface BatchResultErrorEntry { + Id: string; + Code: string; + Message?: string; + SenderFault: boolean; + } + + export interface SendMessageBatchResult { + Successful: SendMessageBatchResultEntry[]; + Failed: BatchResultErrorEntry[]; + } + + export interface SendMessageBatchResultEntry { + Id: string; + MessageId: string; + MD5OfMessageBody: string; + MD5OfMessageAttributes: string; + } + + export interface CreateQueueResult { + QueueUrl: string; + } + + export interface SetQueueAttributesParams { + QueueUrl: string; + Attributes: QueueAttributes; + } + +} + +declare export module Ses { + + export interface Client { + config: ClientConfig; + + sendEmail(params: any, callback: (err: any, data: SendEmailResult) => void): void; + } + + export interface SendEmailRequest { + Source: string; + Destination: Destination; + Message: Message; + ReplyToAddresses: string[]; + ReturnPath: string; + } + + export class Destination { + ToAddresses: string[]; + CcAddresses: string[]; + BccAddresses: string[]; + } + + export class Message { + Subject: Content; + Body: Body; + } + + export class Content { + Data: string; + Charset: string; + } + + export class Body { + Text: Content; + Html: Content; + } + + export class SendEmailResult { + MessageId: string; + } + +} + +declare export module Swf { + + export class Client { + //constructor(options?: any); + public config: ClientConfig; + + countClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + countPendingActivityTasks(params: any, callback: (err: any, data: any) => void): void; + countPendingDecisionTasks(params: any, callback: (err: any, data: any) => void): void; + deprecateActivityType(params: any, callback: (err: any, data: any) => void): void; + deprecateDomain(params: any, callback: (err: any, data: any) => void): void; + deprecateWorkflowType(params: any, callback: (err: any, data: any) => void): void; + describeActivityType(params: any, callback: (err: any, data: any) => void): void; + describeDomain(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + describeWorkflowType(params: any, callback: (err: any, data: any) => void): void; + getWorkflowExecutionHistory(params: any, callback: (err: any, data: any) => void): void; + listActivityTypes(params: any, callback: (err: any, data: any) => void): void; + listClosedWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listDomains(params: any, callback: (err: any, data: any) => void): void; + listOpenWorkflowExecutions(params: any, callback: (err: any, data: any) => void): void; + listWorkflowTypes(params: any, callback: (err: any, data: any) => void): void; + pollForActivityTask(params: any, callback: (err: any, data: ActivityTask) => void): void; + pollForDecisionTask(params: any, callback: (err: any, data: DecisionTask) => void): void; + recordActivityTaskHeartbeat(params: any, callback: (err: any, data: any) => void): void; + registerActivityType(params: any, callback: (err: any, data: any) => void): void; + registerDomain(params: any, callback: (err: any, data: any) => void): void; + registerWorkflowType(params: any, callback: (err: any, data: any) => void): void; + requestCancelWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + respondActivityTaskCanceled(params: RespondActivityTaskCanceledRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskCompleted(params: RespondActivityTaskCompletedRequest, callback: (err: any, data: any) => void): void; + respondActivityTaskFailed(params: RespondActivityTaskFailedRequest, callback: (err: any, data: any) => void): void; + respondDecisionTaskCompleted(params: RespondDecisionTaskCompletedRequest, callback: (err: any, data: any) => void): void; + signalWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + startWorkflowExecution(params: any, callback: (err: any, data: StartWorkflowExecutionResult) => void): void; + terminateWorkflowExecution(params: any, callback: (err: any, data: any) => void): void; + } + + export interface PollForActivityTaskRequest { + domain?: string; + taskList?: TaskList; + identity?: string; + } + + export interface TaskList { + name?: string; + } + + export interface PollForDecisionTaskRequest { + domain?: string; + taskList?: TaskList; + identity?: string; + nextPageToken?: string; + maximumPageSize?: number; + reverseOrder?: Boolean; + } + + export interface StartWorkflowExecutionRequest { + domain?: string; + workflowId?: string; + workflowType?: WorkflowType; + taskList?: TaskList; + input?: string; + executionStartToCloseTimeout?: string; + tagList?: string[]; + taskStartToCloseTimeout?: string; + childPolicy?: string; + } + + export interface WorkflowType { + name?: string; + version?: string; + } + + export interface RespondDecisionTaskCompletedRequest { + taskToken?: string; + decisions?: Decision[]; + executionContext?: string; + } + + export interface Decision { + decisionType?: string; + scheduleActivityTaskDecisionAttributes?: ScheduleActivityTaskDecisionAttributes; + requestCancelActivityTaskDecisionAttributes?: RequestCancelActivityTaskDecisionAttributes; + completeWorkflowExecutionDecisionAttributes?: CompleteWorkflowExecutionDecisionAttributes; + failWorkflowExecutionDecisionAttributes?: FailWorkflowExecutionDecisionAttributes; + cancelWorkflowExecutionDecisionAttributes?: CancelWorkflowExecutionDecisionAttributes; + continueAsNewWorkflowExecutionDecisionAttributes?: ContinueAsNewWorkflowExecutionDecisionAttributes; + recordMarkerDecisionAttributes?: RecordMarkerDecisionAttributes; + startTimerDecisionAttributes?: StartTimerDecisionAttributes; + cancelTimerDecisionAttributes?: CancelTimerDecisionAttributes; + signalExternalWorkflowExecutionDecisionAttributes?: SignalExternalWorkflowExecutionDecisionAttributes; + requestCancelExternalWorkflowExecutionDecisionAttributes?: RequestCancelExternalWorkflowExecutionDecisionAttributes; + startChildWorkflowExecutionDecisionAttributes?: StartChildWorkflowExecutionDecisionAttributes; + } + + export interface ScheduleActivityTaskDecisionAttributes { + activityType?: ActivityType; + activityId?: string; + control?: string; + input?: string; + scheduleToCloseTimeout?: string; + taskList?: TaskList; + scheduleToStartTimeout?: string; + startToCloseTimeout?: string; + heartbeatTimeout?: string; + } + + export interface ActivityType { + name?: string; + version?: string; + } + + export interface RequestCancelActivityTaskDecisionAttributes { + activityId?: string; + } + + export interface CompleteWorkflowExecutionDecisionAttributes { + result?: string; + } + + export interface FailWorkflowExecutionDecisionAttributes { + reason?: string; + details?: string; + } + + export interface CancelWorkflowExecutionDecisionAttributes { + details?: string; + } + + export interface ContinueAsNewWorkflowExecutionDecisionAttributes { + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + workflowTypeVersion?: string; + } + + export interface RecordMarkerDecisionAttributes { + markerName?: string; + details?: string; + } + + export interface StartTimerDecisionAttributes { + timerId?: string; + control?: string; + startToFireTimeout?: string; + } + + export interface CancelTimerDecisionAttributes { + timerId?: string; + } + + export interface SignalExternalWorkflowExecutionDecisionAttributes { + workflowId?: string; + runId?: string; + signalName?: string; + input?: string; + control?: string; + } + + export interface RequestCancelExternalWorkflowExecutionDecisionAttributes { + workflowId?: string; + runId?: string; + control?: string; + } + + export interface StartChildWorkflowExecutionDecisionAttributes { + workflowType?: WorkflowType; + workflowId?: string; + control?: string; + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + } + + export interface RespondActivityTaskCompletedRequest { + taskToken?: string; + result?: string; + } + + export interface RespondActivityTaskFailedRequest { + taskToken?: string; + reason?: string; + details?: string; + } + + export interface RespondActivityTaskCanceledRequest { + taskToken?: string; + details?: string; + } + + export interface DecisionTask { + taskToken?: string; + startedEventId?: number; + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + events?: HistoryEvent[]; + nextPageToken?: string; + previousStartedEventId?: number; + } + + export interface WorkflowExecution { + workflowId?: string; + runId?: string; + } + + export interface HistoryEvent { + eventTimestamp?: any; + eventType?: string; + eventId?: number; + workflowExecutionStartedEventAttributes?: WorkflowExecutionStartedEventAttributes; + workflowExecutionCompletedEventAttributes?: WorkflowExecutionCompletedEventAttributes; + completeWorkflowExecutionFailedEventAttributes?: CompleteWorkflowExecutionFailedEventAttributes; + workflowExecutionFailedEventAttributes?: WorkflowExecutionFailedEventAttributes; + failWorkflowExecutionFailedEventAttributes?: FailWorkflowExecutionFailedEventAttributes; + workflowExecutionTimedOutEventAttributes?: WorkflowExecutionTimedOutEventAttributes; + workflowExecutionCanceledEventAttributes?: WorkflowExecutionCanceledEventAttributes; + cancelWorkflowExecutionFailedEventAttributes?: CancelWorkflowExecutionFailedEventAttributes; + workflowExecutionContinuedAsNewEventAttributes?: WorkflowExecutionContinuedAsNewEventAttributes; + continueAsNewWorkflowExecutionFailedEventAttributes?: ContinueAsNewWorkflowExecutionFailedEventAttributes; + workflowExecutionTerminatedEventAttributes?: WorkflowExecutionTerminatedEventAttributes; + workflowExecutionCancelRequestedEventAttributes?: WorkflowExecutionCancelRequestedEventAttributes; + decisionTaskScheduledEventAttributes?: DecisionTaskScheduledEventAttributes; + decisionTaskStartedEventAttributes?: DecisionTaskStartedEventAttributes; + decisionTaskCompletedEventAttributes?: DecisionTaskCompletedEventAttributes; + decisionTaskTimedOutEventAttributes?: DecisionTaskTimedOutEventAttributes; + activityTaskScheduledEventAttributes?: ActivityTaskScheduledEventAttributes; + activityTaskStartedEventAttributes?: ActivityTaskStartedEventAttributes; + activityTaskCompletedEventAttributes?: ActivityTaskCompletedEventAttributes; + activityTaskFailedEventAttributes?: ActivityTaskFailedEventAttributes; + activityTaskTimedOutEventAttributes?: ActivityTaskTimedOutEventAttributes; + activityTaskCanceledEventAttributes?: ActivityTaskCanceledEventAttributes; + activityTaskCancelRequestedEventAttributes?: ActivityTaskCancelRequestedEventAttributes; + workflowExecutionSignaledEventAttributes?: WorkflowExecutionSignaledEventAttributes; + markerRecordedEventAttributes?: MarkerRecordedEventAttributes; + timerStartedEventAttributes?: TimerStartedEventAttributes; + timerFiredEventAttributes?: TimerFiredEventAttributes; + timerCanceledEventAttributes?: TimerCanceledEventAttributes; + startChildWorkflowExecutionInitiatedEventAttributes?: StartChildWorkflowExecutionInitiatedEventAttributes; + childWorkflowExecutionStartedEventAttributes?: ChildWorkflowExecutionStartedEventAttributes; + childWorkflowExecutionCompletedEventAttributes?: ChildWorkflowExecutionCompletedEventAttributes; + childWorkflowExecutionFailedEventAttributes?: ChildWorkflowExecutionFailedEventAttributes; + childWorkflowExecutionTimedOutEventAttributes?: ChildWorkflowExecutionTimedOutEventAttributes; + childWorkflowExecutionCanceledEventAttributes?: ChildWorkflowExecutionCanceledEventAttributes; + childWorkflowExecutionTerminatedEventAttributes?: ChildWorkflowExecutionTerminatedEventAttributes; + signalExternalWorkflowExecutionInitiatedEventAttributes?: SignalExternalWorkflowExecutionInitiatedEventAttributes; + externalWorkflowExecutionSignaledEventAttributes?: ExternalWorkflowExecutionSignaledEventAttributes; + signalExternalWorkflowExecutionFailedEventAttributes?: SignalExternalWorkflowExecutionFailedEventAttributes; + externalWorkflowExecutionCancelRequestedEventAttributes?: ExternalWorkflowExecutionCancelRequestedEventAttributes; + requestCancelExternalWorkflowExecutionInitiatedEventAttributes?: RequestCancelExternalWorkflowExecutionInitiatedEventAttributes; + requestCancelExternalWorkflowExecutionFailedEventAttributes?: RequestCancelExternalWorkflowExecutionFailedEventAttributes; + scheduleActivityTaskFailedEventAttributes?: ScheduleActivityTaskFailedEventAttributes; + requestCancelActivityTaskFailedEventAttributes?: RequestCancelActivityTaskFailedEventAttributes; + startTimerFailedEventAttributes?: StartTimerFailedEventAttributes; + cancelTimerFailedEventAttributes?: CancelTimerFailedEventAttributes; + startChildWorkflowExecutionFailedEventAttributes?: StartChildWorkflowExecutionFailedEventAttributes; + } + + export interface WorkflowExecutionStartedEventAttributes { + input?: string; + executionStartToCloseTimeout?: string; + taskStartToCloseTimeout?: string; + childPolicy?: string; + taskList?: TaskList; + workflowType?: WorkflowType; + tagList?: string[]; + continuedExecutionRunId?: string; + parentWorkflowExecution?: WorkflowExecution; + parentInitiatedEventId?: number; + } + + export interface WorkflowExecutionCompletedEventAttributes { + result?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CompleteWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionFailedEventAttributes { + reason?: string; + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface FailWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionTimedOutEventAttributes { + timeoutType?: string; + childPolicy?: string; + } + + export interface WorkflowExecutionCanceledEventAttributes { + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CancelWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionContinuedAsNewEventAttributes { + input?: string; + decisionTaskCompletedEventId?: number; + newExecutionRunId?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + taskStartToCloseTimeout?: string; + childPolicy?: string; + tagList?: string[]; + workflowType?: WorkflowType; + } + + export interface ContinueAsNewWorkflowExecutionFailedEventAttributes { + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface WorkflowExecutionTerminatedEventAttributes { + reason?: string; + details?: string; + childPolicy?: string; + cause?: string; + } + + export interface WorkflowExecutionCancelRequestedEventAttributes { + externalWorkflowExecution?: WorkflowExecution; + externalInitiatedEventId?: number; + cause?: string; + } + + export interface DecisionTaskScheduledEventAttributes { + taskList?: TaskList; + startToCloseTimeout?: string; + } + + export interface DecisionTaskStartedEventAttributes { + identity?: string; + scheduledEventId?: number; + } + + export interface DecisionTaskCompletedEventAttributes { + executionContext?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface DecisionTaskTimedOutEventAttributes { + timeoutType?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskScheduledEventAttributes { + activityType?: ActivityType; + activityId?: string; + input?: string; + control?: string; + scheduleToStartTimeout?: string; + scheduleToCloseTimeout?: string; + startToCloseTimeout?: string; + taskList?: TaskList; + decisionTaskCompletedEventId?: number; + heartbeatTimeout?: string; + } + + export interface ActivityTaskStartedEventAttributes { + identity?: string; + scheduledEventId?: number; + } + + export interface ActivityTaskCompletedEventAttributes { + result?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskFailedEventAttributes { + reason?: string; + details?: string; + scheduledEventId?: number; + startedEventId?: number; + } + + export interface ActivityTaskTimedOutEventAttributes { + timeoutType?: string; + scheduledEventId?: number; + startedEventId?: number; + details?: string; + } + + export interface ActivityTaskCanceledEventAttributes { + details?: string; + scheduledEventId?: number; + startedEventId?: number; + latestCancelRequestedEventId?: number; + } + + export interface ActivityTaskCancelRequestedEventAttributes { + decisionTaskCompletedEventId?: number; + activityId?: string; + } + + export interface WorkflowExecutionSignaledEventAttributes { + signalName?: string; + input?: string; + externalWorkflowExecution?: WorkflowExecution; + externalInitiatedEventId?: number; + } + + export interface MarkerRecordedEventAttributes { + markerName?: string; + details?: string; + decisionTaskCompletedEventId?: number; + } + + export interface TimerStartedEventAttributes { + timerId?: string; + control?: string; + startToFireTimeout?: string; + decisionTaskCompletedEventId?: number; + } + + export interface TimerFiredEventAttributes { + timerId?: string; + startedEventId?: number; + } + + export interface TimerCanceledEventAttributes { + timerId?: string; + startedEventId?: number; + decisionTaskCompletedEventId?: number; + } + + export interface StartChildWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + workflowType?: WorkflowType; + control?: string; + input?: string; + executionStartToCloseTimeout?: string; + taskList?: TaskList; + decisionTaskCompletedEventId?: number; + childPolicy?: string; + taskStartToCloseTimeout?: string; + tagList?: string[]; + } + + export interface ChildWorkflowExecutionStartedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + initiatedEventId?: number; + } + + export interface ChildWorkflowExecutionCompletedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + result?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionFailedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + reason?: string; + details?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionTimedOutEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + timeoutType?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionCanceledEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + details?: string; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface ChildWorkflowExecutionTerminatedEventAttributes { + workflowExecution?: WorkflowExecution; + workflowType?: WorkflowType; + initiatedEventId?: number; + startedEventId?: number; + } + + export interface SignalExternalWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + runId?: string; + signalName?: string; + input?: string; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ExternalWorkflowExecutionSignaledEventAttributes { + workflowExecution?: WorkflowExecution; + initiatedEventId?: number; + } + + export interface SignalExternalWorkflowExecutionFailedEventAttributes { + workflowId?: string; + runId?: string; + cause?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ExternalWorkflowExecutionCancelRequestedEventAttributes { + workflowExecution?: WorkflowExecution; + initiatedEventId?: number; + } + + export interface RequestCancelExternalWorkflowExecutionInitiatedEventAttributes { + workflowId?: string; + runId?: string; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface RequestCancelExternalWorkflowExecutionFailedEventAttributes { + workflowId?: string; + runId?: string; + cause?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ScheduleActivityTaskFailedEventAttributes { + activityType?: ActivityType; + activityId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface RequestCancelActivityTaskFailedEventAttributes { + activityId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface StartTimerFailedEventAttributes { + timerId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface CancelTimerFailedEventAttributes { + timerId?: string; + cause?: string; + decisionTaskCompletedEventId?: number; + } + + export interface StartChildWorkflowExecutionFailedEventAttributes { + workflowType?: WorkflowType; + cause?: string; + workflowId?: string; + initiatedEventId?: number; + decisionTaskCompletedEventId?: number; + control?: string; + } + + export interface ActivityTask { + taskToken?: string; + activityId?: string; + startedEventId?: number; + workflowExecution?: WorkflowExecution; + activityType?: ActivityType; + input?: string; + } + + export interface PollForActivityTaskResult { + activityTask?: ActivityTask; + } + + export interface PollForDecisionTaskResult { + decisionTask?: DecisionTask; + } + + export interface StartWorkflowExecutionResult { + run?: Run; + } + + export interface Run { + runId?: string; + } + +} + +declare export module Sns { + + export interface Client { + config: ClientConfig; + + publicTopic(params: PublishRequest, callback: (err: any, data: PublishResult) => void): void; + createTopic(params: CreateTopicRequest, callback: (err: any, data: CreateTopicResult) => void): void; + deleteTopic(params: DeleteTopicRequest, callback: (err: any, data: any) => void): void; + } + + export interface PublishRequest { + TopicArn?: string; + Message?: string; + MessageStructure?: string; + Subject?: string; + } + + export interface PublishResult { + MessageId?: string; + } + + export interface CreateTopicRequest { + Name?: string; + } + + export interface CreateTopicResult { + TopicArn?: string; + } + + export interface DeleteTopicRequest { + TopicArn?: string; + } + +} + +declare export module s3 { + + export interface PutObjectRequest { + ACL?: string; + Body?: any; + Bucket: string; + CacheControl?: string; + ContentDisposition?: string; + ContentEncoding?: string; + ContentLanguage?: string; + ContentLength?: string; + ContentMD5?: string; + ContentType?: string; + Expires?: any; + GrantFullControl?: string; + GrantRead?: string; + GrantReadACP?: string; + GrantWriteACP?: string; + Key: string; + Metadata?: string[]; + ServerSideEncryption?: string; + StorageClass?: string; + WebsiteRedirectLocation?: string; + } + + export interface GetObjectRequest { + Bucket: string; + IfMatch?: string; + IfModifiedSince?: any; + IfNoneMatch?: string; + IfUnmodifiedSince?: any; + Key: string; + Range?: string; + ResponseCacheControl?: string; + ResponseContentDisposition?: string; + ResponseContentEncoding?: string; + ResponseContentLanguage?: string; + ResponseContentType?: string; + ResponseExpires?: any; + VersionId?: string; + } + +} + +declare export module ecs { + export interface CreateServicesParams { + desiredCount: number; + serviceName: string; + taskDefinition: string; + clientToken?: string; + cluster?: string; + deploymentConfiguration?: { + maximumPercent?: number; + minimumHealthyPercent?: number; + }; + loadBalancers?: { + containerName?: string; + containerPort?: number; + loadBalancerName?: string; + }[]; + role?: string; + } + + export interface DescribeServicesParams { + services: string[]; + cluster: string; + } + + export interface DescribeTaskDefinitionParams { + taskDefinition: string; + } + + export interface RegisterTaskDefinitionParams { + containerDefinitions: { + command?: string[], + cpu?: number, + disableNetworking?: boolean, + dnsSearchDomains?: string[], + dnsServers?: string[], + dockerLabels?: any, + dockerSecurityOptions?: string[], + entryPoint?: string[], + environment?: any[], + essential?: boolean, + extraHosts?: { + hostName: string, + ipAddress: string + }[]; + hostname?: string, + image?: string, + links?: string[], + logConfiguration?: { + logDriver: string, + options: any + }[], + memory?: number, + mountPoints?: { + containerPath: string, + readOnly: boolean, + sourceVolume: string + }[]; + name?: string, + portMappings?: { + containerPort?: number, + hostPort?: number, + protocol: string + }[]; + privileged?: boolean, + readonlyRootFilesystem?: boolean, + ulimits?: { + hardLimit: number, + name: string, + softLimit: number + }[]; + user?: string, + volumesFrom?: { + readOnly?: boolean, + sourceContainer?: string + }[], + workingDirectory?: string + }[]; + family: string; + volumes?: { + host: { + sourcePath: string + }, + name: string + }[]; + } + + export interface UpdateServiceParams { + service: string; + cluster?: string; + deploymentConfiguration?: { + maximumPercent: number; + minimumHealthyPercent: number; + }; + desiredCount?: number; + taskDefinition: string; + } } diff --git a/azure/azure.d.ts b/azure/azure.d.ts index da2c14871f..ffa545166f 100644 --- a/azure/azure.d.ts +++ b/azure/azure.d.ts @@ -10,1873 +10,1872 @@ /** * TODO */ -declare module "azure" { - import events = require("events"); - import stream = require("stream"); - import url = require("url"); - //#region Services - export class TableService extends BatchServiceClient { - static incorrectTableNameErr: string; - static incorrectCallbackErr: string; - static incorrectTableQuery: string; - static incorrectPartitionErr: string; - - //#region Constructors - - /** - * Creates a new TableService object. - * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. - * - * @constructor - * @extends {ServiceClient} - */ - constructor(); - /** - * Creates a new TableService object. - * Uses a connectionString to connect - * - * @constructor - * @extends {ServiceClient} - * @param {string} connectionString The connection string. - */ - constructor(connectionString: string); - /** - * Creates a new TableService object. - * Uses a storage account and an access key. - * - * @constructor - * @extends {ServiceClient} - * @param {string} storageAccount The storage account or the connection string. - * @param {string} storageAccessKey The storage access key. - * @param {string} host The host address. - * @param {object} authenticationProvider The authentication provider. - */ - constructor(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string); - - //#endregion - - //#region Service Methods - - getServiceProperties(callback: StorageServicePropertiesCallback): void; - getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; - - setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; - setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; - - //#endregion - - //#region Table Methods - - getTable(table: string, callback?: TableRequestCallback): void; - getTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback): void; - - createTable(table: string, callback?: TableRequestCallback): void; - createTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback): void; - - createTableIfNotExists(table: string, callback?: CreateTableIfNotExistsCallback): void; - createTableIfNotExists(table: string, options: TimeoutIntervalOptions, callback?: CreateTableIfNotExistsCallback): void; - - deleteTable(table: string, callback?: DeleteTableCallback): void; - deleteTable(table: string, options: TimeoutIntervalOptions, callback?: DeleteTableCallback): void; - - queryTables(callback?: QueryTablesCallback): void; - queryTables(options: QueryTablesOptions, callback?: QueryTablesCallback): void; - - //#endregion - - //#region Entities Methods - - queryEntity(table: string, partitionKey: string, rowKey: string, callback?: QueryEntityCallback): void; - queryEntity(table: string, partitionKey: string, rowKey: string, options: TimeoutIntervalOptions, callback?: QueryEntityCallback): void; - - queryEntities(tableQuery: TableQuery, callback?: QueryEntitiesCallback): void; - queryEntities(tableQuery: TableQuery, options: TimeoutIntervalOptions, callback?: QueryEntitiesCallback): void; - - insertEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; - insertEntity(tableName: string, entityDescriptor: Entity, options: TimeoutIntervalOptions, callback?: ModifyEntityCallback): void; - - insertOrReplaceEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; - insertOrReplaceEntity(tableName: string, entityDescriptor: Entity, options: TimeoutIntervalOptions, callback?: ModifyEntityCallback): void; - - updateEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; - updateEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: ModifyEntityCallback): void; - - mergeEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; - mergeEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: ModifyEntityCallback): void; - - insertOrMergeEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; - insertOrMergeEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: ModifyEntityCallback): void; - - deleteEntity(tableName: string, entityDescriptor: Entity, callback?: DeleteEntityCallback): void; - deleteEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: DeleteEntityCallback): void; - - //#endregion - } - - export class BlobService extends StorageServiceClient { - singleBlobPutThresholdInBytes: number; - parallelOperationThreadCount: number; - - SpeedSummary: typeof SpeedSummary; - - //#region Constructors - - /** - * Creates a new BlobService object. - * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. - * - * @constructor - * @extends {StorageServiceClient} - */ - constructor(); - - /** - * Creates a new BlobService object. - * Uses a connectionString to connect - * - * @constructor - * @extends {StorageServiceClient} - * @param {string} connectionString The connection string. - */ - constructor(connectionString: string); - - /** - * Creates a new BlobService object. - * Uses a storage account and an access key. - * - * @constructor - * @extends {StorageServiceClient} - * @param {string} storageAccount The storage account or the connection string. - * @param {string} storageAccessKey The storage access key. - * @param {string} host The host address. - * @param {object} sasToken The Shared Access Signature token. - */ - constructor(storageAccount: string, storageAccessKey: string, host?: string, sasToken?: string); - - //#endregion - - //#region Service Methods - - /** - * Gets the properties of a storage account�s Blob service, including Azure Storage Analytics. - */ - getServiceProperties(callback: StorageServicePropertiesCallback): void; - getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; - - /** - * Sets the properties of a storage account�s Blob service, including Azure Storage Analytics. - * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. - */ - setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; - setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; - - //#endregion - - //#region Containers Methods - - /** - * Lists a segment containing a collection of container items under the specified account. - */ - listContainers(callback: ListContainersCallback): void; - listContainers(options: ListContainersOptions, callback: ListContainersCallback): void; - - /** - * Creates a new container under the specified account. - * If a container with the same name already exists, the operation fails. - */ - createContainer(container: string, callback: StorageCallback): void; - createContainer(container: string, options: CreateContainerOptions, callback: StorageCallback): void; - - /** - * Creates a new container under the specified account if the container does not exists. - */ - createContainerIfNotExists(container: string, callback: StorageCallback): void; - createContainerIfNotExists(container: string, options: CreateContainerOptions, callback: StorageCallback): void; - - /** - * Retrieves a container and its properties from a specified account. - */ - getContainerProperties(container: string, callback: StorageCallback): void; - getContainerProperties(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; - - /** - * Returns all user-defined metadata for the container. - */ - getContainerMetadata(container: string, callback: StorageCallback): void; - getContainerMetadata(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; - - /** - * Sets the container's metadata. - */ - setContainerMetadata(container: string, metadata: StorageMetadata, callback: StorageCallback): void; - setContainerMetadata(container: string, metadata: StorageMetadata, options: AccessConditionsOptions, callback: StorageCallback): void; - - /** - * Gets the container's ACL. - */ - getContainerAcl(container: string, callback: StorageCallback): void; - getContainerAcl(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; - - /** - * Updates the container's ACL. - */ - setContainerAcl(container: string, publicAccessLevel: string, callback: StorageCallback): void; - setContainerAcl(container: string, publicAccessLevel: string, options: StorageAclOptions, callback: StorageCallback): void; - - /** - * Marks the specified container for deletion. - * The container and any blobs contained within it are later deleted during garbage collection. - */ - deleteContainer(container: string, callback: StorageCallbackVoid): void; - deleteContainer(container: string, options: LeaseIdOptions, callback: StorageCallbackVoid): void; - - //#endregion - - //#region Blob Methods - - /** - * Lists all of the blobs in the given container. - */ - listBlobs(container: string, callback: ListBlobsCallback): void; - listBlobs(container: string, options: ListBlobsOptions, callback: ListBlobsCallback): void; - - /** - * Returns all user-defined metadata, standard HTTP properties, and system properties for the blob. - * It does not return or modify the content of the blob. - */ - getBlobProperties(container: string, blob: string, callback: StorageCallback): void; - getBlobProperties(container: string, blob: string, options: GetBlobPropertiesOptions, callback: StorageCallback): void; - - /** - * Sets user-defined properties for the specified blob or snapshot. - * It does not return or modify the content of the blob. - */ - setBlobProperties(container: string, blob: string, callback: StorageCallback): void; - setBlobProperties(container: string, blob: string, options: SetBlobPropertiesOptions, callback: StorageCallback): void; - - /** - * Sets user-defined metadata for the specified blob or snapshot as one or more name-value pairs - * It does not return or modify the content of the blob. - */ - setBlobMetadata(container: string, blob: string, metadata: StorageMetadata, callback: StorageCallback): void; - setBlobMetadata(container: string, blob: string, metadata: StorageMetadata, options: GetBlobPropertiesOptions, callback: StorageCallback): void; - - /** - * Provides a stream to read from a blob. - */ - getBlob(container: string, blob: string, callback: StorageCallback): stream.Readable; - getBlob(container: string, blob: string, options: ReadBlobOptions, callback: StorageCallback): stream.Readable; - - /** - * Downloads a blob into a file. - */ - getBlobToFile(container: string, blob: string, localFileName: string, callback: StorageCallback): void; - getBlobToFile(container: string, blob: string, localFileName: string, options: ReadBlobOptions, callback: StorageCallback): void; - - /** - * Downloads a blob into a stream. - */ - getBlobToStream(container: string, blob: string, stream: stream.Writable, callback: StorageCallback): void; - getBlobToStream(container: string, blob: string, stream: stream.Writable, options: ReadBlobOptions, callback: StorageCallback): void; - - /** - * Downloads a blob into a text string. - */ - getBlobToText(container: string, blob: string, callback: GetBlobToTextCallback): void; - getBlobToText(container: string, blob: string, options: ReadBlobOptions, callback: GetBlobToTextCallback): void; - - /** - * Marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. - * If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, - * or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error - * and nothing will be deleted. - * If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included. - */ - deleteBlob(container: string, blob: string, callback: StorageCallback): void; - deleteBlob(container: string, blob: string, options: DeleteBlobOptions, callback: StorageCallback): void; - - /** - * Creates a read-only snapshot of a blob. - */ - createBlobSnapshot(container: string, blob: string, callback: StorageCallback): void; - createBlobSnapshot(container: string, blob: string, options: BlobSnapshotOptions, callback: StorageCallback): void; - - /** - * Starts to copy a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob. - */ - copyBlob(sourceUri: string, targetContainer: string, targetBlob: string, callback: StorageCallback): void; - copyBlob(sourceUri: string, targetContainer: string, targetBlob: string, options: CopyBlobOptions, callback: StorageCallback): void; - - /** - * Creates a read-only snapshot of a blob. - */ - abortCopyBlob(container: string, blob: string, copyId: string, callback: StorageCallbackVoid): void; - abortCopyBlob(container: string, blob: string, copyId: string, options: LeaseIdOptions, callback: StorageCallbackVoid): void; - - /** - * Retrieves a shared access signature token. - */ - generateSharedAccessSignature(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): SharedAccessSignatureResult; - - /** - * Retrieves a blob or container URL. - */ - getBlobUrl(container: string): string; - getBlobUrl(container: string, blob: string): string; - getBlobUrl(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): string; - - /** - * Uploads a blob. - */ - createBlob(container: string, blob: string, blobType: string, callback: StorageCallback): stream.Writable; - createBlob(container: string, blob: string, blobType: string, options: UploadBlockBlobOptions, callback: StorageCallback): stream.Writable; - - //#endregion - - //#region Page Blob Methods - - /** - * Creates a page blob of the specified length. - */ - createPageBlob(container: string, blob: string, length: number, callback: StorageCallbackVoid): void; - createPageBlob(container: string, blob: string, length: number, options: SetBlobPropertiesOptions, callback: StorageCallbackVoid): void; - - /** - * Updates a page blob from a stream. - */ - createBlobPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, callback: StorageCallback): void; - createBlobPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, options: CreatePagesOptions, callback: StorageCallback): void; - - /** - * Updates a page blob from a text string. - */ - createBlobPagesFromText(container: string, blob: string, text: string, rangeStart: number, rangeEnd: number, callback: StorageCallback): void; - createBlobPagesFromText(container: string, blob: string, text: string, rangeStart: number, rangeEnd: number, options: CreatePagesOptions, callback: StorageCallback): void; - - /** - * Lists page ranges. - * Lists all of the page ranges by default, or only the page ranges over a specific range of bytes if rangeStart and rangeEnd are specified. - */ - listBlobRegions(container: string, blob: string, callback: StorageCallback): void; - listBlobRegions(container: string, blob: string, options: PageRangeOptions, callback: StorageCallback): void; - - /** - * Clears a range of pages. - */ - clearBlobPages(container: string, blob: string, rangeStart: number, rangeEnd: number, callback: StorageCallbackVoid): void; - clearBlobPages(container: string, blob: string, rangeStart: number, rangeEnd: number, options: LeaseAccessConditionsOptions, callback: StorageCallbackVoid): void; - - /** - * Resizes a page blob. - */ - resizePageBlob(container: string, blob: string, size: number, callback: StorageCallback): void; - resizePageBlob(container: string, blob: string, size: number, options: LeaseAccessConditionsOptions, callback: StorageCallback): void; - - /** - * Sets the page blob's sequence number. - */ - setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: string, callback: StorageCallback): void; - setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: string, options: AccessConditionsOptions, callback: StorageCallback): void; - - //#endregion - - //#region Block Blob Methods - - /** - * Uploads a block blob from file. - */ - putBlockBlobFromFile(container: string, blob: string, localFileName: string, callback: StorageCallback): SpeedSummary; - putBlockBlobFromFile(container: string, blob: string, localFileName: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; - createBlockBlobFromFile(container: string, blob: string, localFileName: string, callback: StorageCallback): SpeedSummary; - createBlockBlobFromFile(container: string, blob: string, localFileName: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; - - /** - * Uploads a block blob from a stream. - */ - putBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, callback: StorageCallback): SpeedSummary; - putBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; - createBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, callback: StorageCallback): SpeedSummary; - createBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; - - /** - * Uploads a block blob from a text string. - */ - createBlockBlobFromText(container: string, blob: string, text: string, callback: StorageCallback): SpeedSummary; - createBlockBlobFromText(container: string, blob: string, text: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; - - /** - * Creates a new block to be committed as part of a blob. - */ - createBlobBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Stream, streamLength: number, callback: StorageCallbackVoid): void; - createBlobBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Stream, streamLength: number, options: CreateBlockOptions, callback: StorageCallbackVoid): void; - - /** - * Creates a new block to be committed as part of a blob. - */ - createBlobBlockFromText(blockId: string, container: string, blob: string, text: string, callback: StorageCallbackVoid): void; - createBlobBlockFromText(blockId: string, container: string, blob: string, text: string, options: CreateBlockOptions, callback: StorageCallbackVoid): void; - - /** - * Writes a blob by specifying the list of block IDs that make up the blob. - * In order to be written as part of a blob, a block must have been successfully written to the server in a prior - * createBlock operation. - */ - commitBlobBlocks(container: string, blob: string, blockList: BlockList, callback: StorageCallback): void; - commitBlobBlocks(container: string, blob: string, blockList: BlockList, options: CreateBlockOptions, callback: StorageCallback): void; - - /** - * Retrieves the list of blocks that have been uploaded as part of a block blob. - */ - listBlobBlocks(container: string, blob: string, blockListType: string, callback: StorageCallback): void; - listBlobBlocks(container: string, blob: string, blockListType: string, options: GetBlobPropertiesOptions, callback: StorageCallback): void; - - /** - * Generate a random block id prefix. - */ - generateBlockIdPrefix(): string; - /** - * Get a block id according to prefix and block number. - */ - getBlockId(prefix: string, number: number): string; - - //#endregion - - //#region Lease Methods - - /** - * Acquires a new lease. - * If container and blob are specified, acquires a blob lease. - * Otherwise, if only container is specified and blob is null, acquires a container lease. - */ - acquireLease(container: string, blob: string, callback: StorageCallback): void; - acquireLease(container: string, blob: string, options: LeaseOptions, callback: StorageCallback): void; - - /** - * Renews an existing lease. - * If container and blob are specified, renews the blob lease. - * Otherwise, if only container is specified and blob is null, renews the container lease. - */ - renewLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; - renewLease(container: string, blob: string, leaseId: string, options: AccessConditionsOptions, callback: StorageCallback): void; - - /** - * Releases the lease. - * If container and blob are specified, releases the blob lease. - * Otherwise, if only container is specified and blob is null, releases the container lease. - */ - releaseLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; - releaseLease(container: string, blob: string, leaseId: string, options: AccessConditionsOptions, callback: StorageCallback): void; - - /** - * Breaks the lease but ensures that another client cannot acquire a new lease until the current lease period has expired. - * If container and blob are specified, breaks the blob lease. - * Otherwise, if only container is specified and blob is null, breaks the container lease. - */ - breakLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; - breakLease(container: string, blob: string, leaseId: string, options: BreakLeaseOptions, callback: StorageCallback): void; - - //#endregion - } - - export class QueueService extends StorageServiceClient { - authenticationProvider: SharedKey; - - //#region Constructors - - /** - * Creates a new BlobService object. - * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. - * - * @constructor - * @extends {StorageServiceClient} - */ - constructor(); - - /** - * Creates a new BlobService object. - * Uses a connectionString to connect - * - * @constructor - * @extends {StorageServiceClient} - * @param {string} connectionString The connection string. - */ - constructor(connectionString: string); - - /** - * Creates a new BlobService object. - * Uses a storage account and an access key. - * - * @constructor - * @extends {StorageServiceClient} - * @param {string} storageAccount The storage account or the connection string. - * @param {string} storageAccessKey The storage access key. - * @param {string} host The host address. - * @param {object} sasToken The Shared Access Signature token. - */ - constructor(storageAccount: string, storageAccessKey: string, host?: string, sasToken?: string); - - //#endregion - - //#region Service Methods - - /** - * Gets the properties of a storage account�s Blob service, including Azure Storage Analytics. - */ - getServiceProperties(callback: StorageServicePropertiesCallback): void; - getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; - - /** - * Sets the properties of a storage account�s Blob service, including Azure Storage Analytics. - * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. - */ - setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; - setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; - - //#endregion - - //#region Queue Methods - - /** - * Lists all queues under the given account. - */ - listQueues(callback: ListQueuesCallback): void; - listQueues(options: ListQueuesOptions, callback: ListQueuesCallback): void; - - /** - * Creates a new queue under the given account. - */ - createQueue(queue: string, callback: StorageCallback): void; - createQueue(queue: string, options: MetadataOptions, callback: StorageCallback): void; - - /** - * Creates a new queue under the given account if it doesn't exist. - */ - createQueueIfNotExists(queue: string, callback: StorageCallback): void; - createQueueIfNotExists(queue: string, options: MetadataOptions, callback: StorageCallback): void; - - /** - * Permanently deletes the specified queue. - */ - deleteQueue(queue: string, callback: StorageCallback): void; - deleteQueue(queue: string, options: TimeoutIntervalOptions, callback: StorageCallback): void; - - /** - * Returns queue properties, including user-defined metadata. - */ - getQueueMetadata(queue: string, callback: StorageCallback): void; - getQueueMetadata(queue: string, options: TimeoutIntervalOptions, callback: StorageCallback): void; - - /** - * Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. - */ - setQueueMetadata(queue: string, metadata: StorageMetadata, callback: StorageCallback): void; - setQueueMetadata(queue: string, metadata: StorageMetadata, options: TimeoutIntervalOptions, callback: StorageCallback): void; - - //#endregion - - //#region Message Methods - - /** - * Adds a new message to the back of the message queue. A visibility timeout can also be specified to make the message - * invisible until the visibility timeout expires. A message must be in a format that can be included in an XML request - * with UTF-8 encoding. The encoded message can be up to 64KB in size for versions 2011-08-18 and newer, or 8KB in size - * for previous versions. - */ - createMessage(queue: string, messageText: string, callback: StorageCallback): void - createMessage(queue: string, messageText: string, options: CreateQueueMessageOptions, callback: StorageCallback): void - - /** - * Retrieves a message from the queue and makes it invisible to other consumers. - */ - getMessages(queue: string, callback: StorageCallback): void; - getMessages(queue: string, options: GetQueueMessagesOptions, callback: StorageCallback): void; - - /** - * Retrieves a message from the front of the queue, without changing the message visibility. - */ - peekMessages(queue: string, callback: StorageCallback): void; - peekMessages(queue: string, options: PeekQueueMessagesOptions, callback: StorageCallback): void; - - /** - * Deletes a specified message from the queue. - */ - deleteMessage(queue: string, messageId: string, popreceipt: string, callback: StorageCallback): void - deleteMessage(queue: string, messageId: string, popreceipt: string, options: TimeoutIntervalOptions, callback: StorageCallback): void - - /** - * Clears all messages from the queue. - */ - clearMessages(queue: string, callback: StorageCallbackVoid): void; - clearMessages(queue: string, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; - - /** - * Deletes a specified message from the queue. - */ - updateMessage(queue: string, messageId: string, popreceipt: string, visibilitytimeout: number, callback: StorageCallback): void - updateMessage(queue: string, messageId: string, popreceipt: string, visibilitytimeout: number, options: UpdateQueueMessagesOptions, callback: StorageCallback): void - - //#endregion - } - - export class ServiceBusService { - - } - - export class SqlService { - - } - - export class ServiceManagementService { - - } - - export class SqlManagementService { - } - //#endregion - - //#region Service Creators - export function createTableService(): TableService; - export function createTableService(connectionString: string): TableService; - export function createTableService(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string): TableService; - - export function createBlobService(): BlobService; - export function createBlobService(connectionString: string): BlobService; - export function createBlobService(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string): BlobService; - - export function createQueueService(): QueueService; - export function createQueueService(connectionString: string): QueueService; - export function createQueueService(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string): QueueService; - - export function createServiceBusService(): ServiceBusService; - export function createServiceBusService(connectionString: string): ServiceBusService; - export function createServiceBusService(namespace: string, accessKey?: string, issuer?: string, acsNamespace?: string, host?: string, authenticationProvider?: string): ServiceBusService; - - export function createSqlService(serverName: string, administratorLogin: string, administratorLoginPassword: string, host?: string, acsHost?: string, authenticationProvider?: string): SqlService; - - export function createServiceManagementService(subscriptionId: string, authentication: string, hostOptions: string): ServiceManagementService; - - export function createSqlManagementService(subscriptionId: string, authentication: string, hostOptions: string): SqlManagementService; - //#endregion - - //#region RoleEnvironment - - interface RoleEnvironmentInterface extends events.EventEmitter { - incorrectCallbackErr: string; - clientId: string; - VersionEndpointFixedPath: string; - EnvironmentVariables: { - [key: string]: string; - VersionEndpointEnvironmentName: string; - }; - - /** - * Returns a RoleInstance object that represents the role instance - * in which this code is currently executing. - */ - getCurrentRoleInstance(callback: SimpleCallback): void; - - /** - * Returns the deployment ID that uniquely identifies the deployment in - * which this role instance is running. - */ - getDeploymentId(callback: SimpleCallback): void; - - /** - * Indicates whether the role instance is running in the Microsoft Azure - * environment. It is good practice to enclose any code that uses - * service runtime in the isAvailable callback. - */ - isAvailable(callback: SimpleCallback): void; - - /** - * Indicates whether the role instance is running in the development fabric. - */ - isEmulated(callback: SimpleCallback): void; - - /** - * Returns the set of Role objects defined for your service. - * Roles are defined in the service definition file. - */ - getRoles(callback: SimpleCallback>): void; - - /** - * Retrieves the settings in the service configuration file. - * - * A role's configuration settings are defined in the service definition file. - * Values for configuration settings are set in the service configuration file. - * For more information on configuration settings, see the [Service Definition Schema](http://msdn.microsoft.com/en-us/library/windowsazure/ee758711.aspx) - * and [Service Configuration Schema](http://msdn.microsoft.com/en-us/library/windowsazure/ee758710.aspx). - */ - getConfigurationSettings(callback: SimpleCallback>): void; - - /** - * Retrieves the set of named local storage resources, along with the path. - * For example, the DiagnosticStore resource which is defined for every role - * provides a location for runtime diagnostics and logs. - */ - getLocalResources(callback: SimpleCallback>): void; - - /** - * Requests that the current role instance be stopped and restarted. - * - * Before the role instance is recycled, the Microsoft Azure load balancer takes the role instance out of rotation. - * This ensures that no new requests are routed to the instance while it is restarting. - * - * A call to `RequestRecycle` initiates the normal shutdown cycle. Microsoft Azure raises the - * `Stopping` event and calls the `OnStop` method so that you can run the necessary code to - * prepare the instance to be recycled. - */ - requestRecycle(callback: ErrorCallback): void; - - /** - * Sets the status of the role instance. - * - * An instance may indicate that it is in one of two states: Ready or Busy. If an instance's state is Ready, it is - * prepared to receive requests from the load balancer. If the instance's state is Busy, it will not receive - * requests from the load balancer. - */ - setStatus(roleInstanceStatus: string, expirationUtc: Date, callback: ErrorCallback): void; - - /** - * Clears the status of the role instance. - * An instance may indicate that it has completed communicating status by calling this method. - */ - clearStatus(callback: ErrorCallback): void; - } - - export var RoleEnvironment: RoleEnvironmentInterface; +import events = require("events"); +import stream = require("stream"); +import url = require("url"); + +//#region Services +declare export class TableService extends BatchServiceClient { + static incorrectTableNameErr: string; + static incorrectCallbackErr: string; + static incorrectTableQuery: string; + static incorrectPartitionErr: string; + + //#region Constructors + + /** + * Creates a new TableService object. + * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. + * + * @constructor + * @extends {ServiceClient} + */ + constructor(); + /** + * Creates a new TableService object. + * Uses a connectionString to connect + * + * @constructor + * @extends {ServiceClient} + * @param {string} connectionString The connection string. + */ + constructor(connectionString: string); + /** + * Creates a new TableService object. + * Uses a storage account and an access key. + * + * @constructor + * @extends {ServiceClient} + * @param {string} storageAccount The storage account or the connection string. + * @param {string} storageAccessKey The storage access key. + * @param {string} host The host address. + * @param {object} authenticationProvider The authentication provider. + */ + constructor(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string); //#endregion - //#region Export of internal classes - export class WebResource { - rawResponse: boolean; - queryString: Dictionary; + //#region Service Methods - constructor(); + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; - get(path: string): WebResource; - put(path: string): WebResource; - post(path: string): WebResource; - merge(path: string): WebResource; - head(path: string): WebResource; - del(path: string): WebResource; + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; - withProperty(name: string, value: string): WebResource; - withRawResponse(rawResponse: boolean): WebResource; - withHeadersOnly(headersOnly: boolean): WebResource; - withQueryOption(name: string, value: string, defaultValue: string): WebResource; - withQueryOptions(queryOptions: Dictionary): WebResource; - withHeader(name: string, value: string): WebResource; - withHeaders(headers: Dictionary): WebResource; - withBody(body: any): WebResource; - addOptionalMetadataHeaders(metadata: StorageMetadata): WebResource; - - validResponse(statusCode: number): boolean; - pipeInput(inputStream: stream.Stream, destStream: stream.Stream): stream.Stream; - } - - export class ServiceClient extends events.EventEmitter { - static EnvironmentVariables: any; - static DEVSTORE_STORAGE_ACCOUNT: string; - static DEVSTORE_STORAGE_ACCESS_KEY: string; - static DEVSTORE_BLOB_HOST: string; - static DEVSTORE_QUEUE_HOST: string; - static DEVSTORE_TABLE_HOST: string; - static CLOUD_BLOB_HOST: string; - static CLOUD_QUEUE_HOST: string; - static CLOUD_TABLE_HOST: string; - static CLOUD_SERVICEBUS_HOST: string; - static CLOUD_ACCESS_CONTROL_HOST: string; - static CLOUD_SERVICE_MANAGEMENT_HOST: string; - static CLOUD_DATABASE_HOST: string; - static DEFAULT_SERVICEBUS_ISSUER: string; - static DEFAULT_WRAP_NAMESPACE_SUFFIX: string; - static DEFAULT_PROTOCOL: string; - - constructor(host: string, authenticationProvider: any); - - setHost(host: string): void; - performRequest(webResource: WebResource, outputData: string, options: any, callback: Function): void; - performRequestOutputStream(webResource: WebResource, outputStream: any, options: any, callback: Function): void; - performRequestInputStream(webResource: WebResource, outputData: string, inputStream: any, options: any, callback: Function): void; - withFilter(newFilter: Filter): ServiceClient; - parseMetadataHeaders(headers: any): any; - isEmulated(): boolean; - setProxy(proxyUrl: string, proxyPort: number): void; - } - - export class BatchServiceClient extends StorageServiceClient { - operations: any[]; - - constructor(storageAccount: string, storageAccessKey: string, host: string, usePathstyleUri: boolean, authenticationProvider: any); - beginBatch(): void; - isInBatch(): boolean; - rollback(): void; - hasOperations(): boolean; - addOperation(webResource: WebResource, outputData: any): void; - commitBatch(callback: (error: any, operationResponses: any[], response: any) => void): void; - commitBatch(options: any, callback: (error: any, operationResponses: any[], response: any) => void): void; - processResponse(responseObject: any, requestOperations: any[]): any[]; - processOperation(webResource: WebResource, rawResponse: string): any; - } - - export class ServiceManagementClient { - - } - - export class TableQuery { - static select(...fields: string[]): TableQuery; - from(table: string): TableQuery; - whereKeys(partitionKey: string, rowKey: string): TableQuery; - whereNextKeys(partitionKey: string, rowKey: string): TableQuery; - where(condition: string, ...values: string[]): TableQuery; - and(condition: string, ...args: string[]): TableQuery; - or(condition: string, ...args: string[]): TableQuery; - top(integer: number): TableQuery; - toQueryObject(): any; - toPath(): string; - } - - export class BlobResult { - blob: string; - container: string; - - etag: string; - lastModified: string; - contentType: string; - contentEncoding: string; - contentLanguage: string; - contentMD5: string; - cacheControl: string; - contentRange: string; - contentTypeHeader: string; - contentEncodingHeader: string; - contentLanguageHeader: string; - contentMD5Header: string; - cacheControlHeader: string; - contentLength: number; - contentLengthHeader: number; - contentDisposition: string; - contentDispositionHeader: string; - range: string; - rangeHeader: string; - getContentMd5: string; - acceptRanges: string; - blobType: string; - leaseStatus: string; - leaseId: string; - leaseDuration: string; - leaseState: string; - sequenceNumber: string; - copyStatus: string; - copyCompletionTime: string; - copyStatusDescription: string; - copyId: string; - copyProgress: number; - requestId: string; - - metadata: StorageMetadata; - - constructor(); - constructor(container: string); - constructor(container: string, blob: string); - - static parse(blobXml: any): BlobResult; - static setHeadersFromBlob(webResource: WebResource, blob: BlobResult): void; - - getPropertiesFromHeaders(headers: any): void; - } - - export class ContainerResult { - name: string; - publicAccessLevel: string; - - etag: string; - lastModified: string; - leaseStatus: string; - leaseDuration: string; - leaseState: string; - requestId: string; - - metadata: StorageMetadata; - signedIdentifiers: SignedIdentifier[]; - - constructor(); - constructor(name: string); - constructor(name: string, publicAccessLevel: string); - - static parse(containerXml: any): ContainerResult; - - getPropertiesFromHeaders(headers: any): void; - } - - export class LeaseResult { - container: string; - blob: string; - id: string; - time: string; - etag: string; - lastModified: string; - - constructor(); - constructor(container: string); - constructor(container: string, blob: string); - constructor(container: string, blob: string, id: string); - constructor(container: string, blob: string, id: string, time: string); - - getPropertiesFromHeaders(header: any): void; - } - - export class QueueResult { - name: string; - metadata: StorageMetadata; - approximatemessagecount: number; - - constructor(); - constructor(name: string); - constructor(name: string, metadata: StorageMetadata); - - static parse(messageXml: any): QueueResult; - - getPropertiesFromHeaders(headers: any): void; - } - - export class QueueMessageResult { - queue: string; - insertiontime: string; - expirationtime: string; - timenextvisible: string; - messagetext: string; - dequeuecount: string; - messageid: string; - popreceipt: string; - metadata: StorageMetadata; - - constructor(); - constructor(queue: string); - constructor(queue: string, messageid: string); - constructor(queue: string, messageid: string, popreceipt: string); - constructor(queue: string, messageid: string, popreceipt: string, metadata: StorageMetadata); - - static serialize(messageJs: string): string; - static parse(messageXml: any): QueueMessageResult; - - getPropertiesFromHeaders(headers: any): void; - } - - export class SpeedSummary { - name: string; - totalSize: number; - completeSize: number; - - _startTime: Date; - _timeWindowInSeconds: number; - _timeWindow: number; - _totalWindowSize: number; - _speedTracks: number[]; - _speedTrackPtr: number; - - constructor(name: string); - - /** - * Get running seconds - */ - getElapsedSeconds(): string; - getElapsedSeconds(humanReadable: boolean): number; - - /** - * Get complete percentage - */ - getCompletePercent(): number; - getCompletePercent(len: number): number; - - /** - * Get average upload/download speed - */ - getAverageSpeed(): string; - getAverageSpeed(humanReadable: boolean): number; - - /** - * Get internal speed - */ - getSpeed(): string; - getSpeed(humanReadable: boolean): number; - - /** - * Get auto increment function - */ - getSpeed(size: number): (error: Error, value: any) => void; - - /** - * Get total size - */ - getTotalSize(): string; - getTotalSize(humanReadable: boolean): number; - - /** - * Get completed data size - */ - getCompleteSize(): string; - getCompleteSize(humanReadable: boolean): number; - } - - export module Constants { - - } - - export interface Filter { - handle(requestOptions: any, next: Function): void; - } - - export class LinearRetryPolicyFilter implements Filter { - constructor(retryCount?: number, retryInterval?: number); - retryCount: number; - retryInterval: number; - handle(requestOptions: any, next: Function): void; - } - - export class ExponentialRetryPolicyFilter implements Filter { - constructor(retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number); - retryCount: number; - retryInterval: number; - minRetryInterval: number; - maxRetryInterval: number; - handle(requestOptions: any, next: Function): void; - } - - export class HmacSha256Sign { - - } - - export class SharedAccessSignature { - storageAccount: string; - storageAccessKey: string; - permissionSet: string[]; - signer: HmacSha256Sign; - - constructor(storageAccount: string, storageAccessKey: string, permissionSet: string[]) - - /** - * Generates the query string for a shared access signature signing. - */ - generateSignedQueryString(path: string, queryString: Dictionary, resourceType: string, sharedAccessPolicy: SharedAccessPolicy): Dictionary; - - /** - * Signs a request with the signature header. - */ - signRequest(webResource: WebResource, callback: ErrorCallback): void; - - /** - * Generates the shared access signature for a resource. - */ - _generateSignature(path: string, resourceType: string, sharedAccessPolicy: SharedAccessPolicy): string; - - /** - * Generates the query string for a shared access signature signing. - */ - _permissionMatchesRequest(sharedAccessSignature: string, webResource: WebResource, resourceType: string, requiredPermissions: string[]): string; - } - - export class SharedKey { - storageAccount: string; - storageAccessKey: string; - usePathStyleUri: string; - signer: HmacSha256Sign; - - constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); - - /** - * Signs a request with the Authentication header. - */ - signRequest(webResource: WebResource, callback: ErrorCallback): void; - - /** - * Retrieves the webresource's canonicalized resource string. - */ - _getCanonicalizedResource(webResource: WebResource): string; - - /** - * Constructs the Canonicalized Headers string. - * - * To construct the CanonicalizedHeaders portion of the signature string, - * follow these steps: 1. Retrieve all headers for the resource that begin - * with x-ms-, including the x-ms-date header. 2. Convert each HTTP header - * name to lowercase. 3. Sort the headers lexicographically by header name, - * in ascending order. Each header may appear only once in the - * string. 4. Unfold the string by replacing any breaking white space with a - * single space. 5. Trim any white space around the colon in the header. 6. - * Finally, append a new line character to each canonicalized header in the - * resulting list. Construct the CanonicalizedHeaders string by - * concatenating all headers in this list into a single string. - */ - _getCanonicalizedHeaders(webResource: WebResource): string; - } - - export class SharedKeyLite { - storageAccount: string; - storageAccessKey: string; - usePathStyleUri: string; - signer: HmacSha256Sign; - - constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); - - /** - * Signs a request with the Authentication header. - */ - signRequest(webResource: WebResource, callback: ErrorCallback): void; - - /** - * Retrieves the webresource's canonicalized resource string. - */ - _getCanonicalizedResource(webResource: WebResource): string; - - /** - * Constructs the Canonicalized Headers string. - * - * To construct the CanonicalizedHeaders portion of the signature string, - * follow these steps: 1. Retrieve all headers for the resource that begin - * with x-ms-, including the x-ms-date header. 2. Convert each HTTP header - * name to lowercase. 3. Sort the headers lexicographically by header name, - * in ascending order. Each header may appear only once in the - * string. 4. Unfold the string by replacing any breaking white space with a - * single space. 5. Trim any white space around the colon in the header. 6. - * Finally, append a new line character to each canonicalized header in the - * resulting list. Construct the CanonicalizedHeaders string by - * concatenating all headers in this list into a single string. - */ - _getCanonicalizedHeaders(webResource: WebResource): string; - } - - export class SharedKeyTable { - storageAccount: string; - storageAccessKey: string; - usePathStyleUri: string; - signer: HmacSha256Sign; - - constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); - - /** - * Signs a request with the Authentication header. - */ - signRequest(webResource: WebResource, callback: ErrorCallback): void; - - /** - * Retrieves the webresource's canonicalized resource string. - */ - _getCanonicalizedResource(webResource: WebResource): string; - } - - export class SharedKeyLiteTable { - torageAccount: string; - storageAccessKey: string; - usePathStyleUri: string; - signer: HmacSha256Sign; - - constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); - - /** - * Signs a request with the Authentication header. - */ - signRequest(webResource: WebResource, callback: ErrorCallback): void; - - /** - * Retrieves the webresource's canonicalized resource string. - */ - _getCanonicalizedResource(webResource: WebResource): string; - } - - export module ISO8061Date { - /** - * Formats a date into an iso 8061 string. - */ - export function format(date: Date): string; - - /** - * Parses an ISO 8061 date string into a date object. - */ - export function parse(stringDateTime: string): Date; - } - - export class Logger { - level: string; - loggerFunction: (level: string, message: string) => void; - - static LogLevels: { - EMERGENCY: string; - ALERT: string; - CRITICAL: string; - ERROR: string; - WARNING: string; - NOTICE: string; - INFO: string; - DEBUG: string; - }; - static logPriority: string[]; - - log(level: string, message: string): void; - emergency(message: string): void; - alert(message: string): void; - critical(message: string): void; - error(message: string): void; - warning(message: string): void; - notice(message: string): void; - info(message: string): void; - debug(message: string): void; - - defaultLoggerFunction(level: string, message: string): void; - } - - export class ConnectionStringParser { - _value: string; - _pos: number; - _state: string; - - constructor(connectionString: string); - - _parse(options: ConnectionStringParseOptions): Dictionary; - - _extractKey(): string; - _extractString(quote: string): string; - _extractValue(): string; - - _skipWhitespaces(): void; - _skipOperator(operator: string): void; - - static parse(connectionString: string): Dictionary; - } - - export module ServiceSettings { - export var DEFAULT_PROTOCOL: string; - - export class NoMatchError implements Error { - name: string; - message: string; - constr: any; - - constructor(); - constructor(message: string); - constructor(message: string, constr: any); - } - - /** - * Throws an exception if the connection string format does not match any of the - * available formats. - */ - export function noMatchConnectionString(connectionString: string): void; - - /** - * Throws an exception if the settings dont match any of the available formats. - */ - export function noMatchSettings(settings: any): void; - - /** - * Parses the connection string and then validate that the parsed keys belong to - * the validSettingKeys - */ - export function parseAndValidateKeys(connectionString: string, validKeys: string[]): string[]; - - /** - * Creates an anonymous function that acts as predicate to perform a validation. - */ - export function getValidator(requirements: Dictionary, isRequired: boolean, atLeastOne: boolean): ValidatorFunction; - - /** - * Creates a setting value condition that validates it is one of the passed valid values. - */ - export function setting(name: string): string[]; - - /** - * Creates an "at least one" predicate for the provided list of requirements. - */ - export function atLeastOne(...args: any[]): ValidatorFunction; - - /** - * Creates an optional predicate for the provided list of requirements. - */ - export function optional(...args: any[]): ValidatorFunction; - - /** - * Creates an required predicate for the provided list of requirements. - */ - export function allRequired(...args: any[]): ValidatorFunction; - - /** - * Creates a setting value condition using the passed predicate. - */ - export function settingWithFunc(name: string, predicate: Function): Requirement[]; - - /** - * Tests to see if a given list of settings matches a set of filters exactly. - */ - export function matchedSpecification(settings: Dictionary): boolean; - - /** - * Tests to see if a given list of settings matches a set of filters exactly. - */ - export function parseHost(uri: string): url.Url; - } - - export class StorageServiceSettings { - _name: string; - _key: string; - _blobEndpointUri: string; - _queueEndpointUri: string; - _tableEndpointUri: string; - _usePathStyleUri: boolean; - - constructor(name: string, key: string, blobEndpointUri: string, queueEndpointUri: string, tableEndpointUri: string, usePathStyleUri: boolean); - - /** - * Returns a StorageServiceSettings with development storage credentials using - * the specified proxy Uri. - */ - static _getDevelopmentStorageAccount(): StorageServiceSettings; - static _getDevelopmentStorageAccount(proxy: string): StorageServiceSettings; - - /** - * Gets a StorageServiceSettings object that references the development storage - * account. - */ - static getDevelopmentStorageAccountSettings(): StorageServiceSettings; - - /** - * Gets the default service endpoint using the specified protocol and account - * name. - */ - static _getDefaultServiceEndpoint(settings: Dictionary, dns: string): string; - - /** - * Creates StorageServiceSettings object given endpoints uri. - */ - static _createStorageServiceSettings(settings: Dictionary, blobEndpointUri: string, queueEndpointUri: string, tableEndpointUri: string): StorageServiceSettings; - - /** - * Creates a ServiceBusSettings object from a set of settings. - */ - static createFromSettings(settings: Dictionary): StorageServiceSettings; - - /** - * Creates a StorageServiceSettings object from the given connection string. - */ - static createFromConnectionString(connectionString: string): StorageServiceSettings; - - static createExplicitlyOrFromEnvironment(storageAccount: string, storageAccessKey: string, host: string): StorageServiceSettings; - - static isDevelopmentStorage(storageAccount: string, storageAccessKey: string, parsedHost: string): boolean; - - static createFromConfig(config: any): StorageServiceSettings; - - static customizeConfig(config: any): void; - } - - export class ServiceBusSettings { - - } - - export class ServiceManagementSettinsg { - - } - - export module Validate { - /** - * Checks if the given uri is valid or not. - */ - export function isValidUri(uri: string): boolean; - - /** - * Validates that a clusterCreationObject is properly formed. - */ - export function isValidHDInsightCreationObject(clusterCreationObject: ClusterCreationOptions): void; - export function isValidHDInsightCreationObject(clusterCreationObject: ClusterCreationOptions, callback: ErrorCallback): void; - - export function isValidUuid(uuid: string): void; - export function isValidUuid(uuid: string, callback: ErrorCallback): void; - - /** - * Creates a anonymous function that check if a given key is base 64 encoded. - */ - export function isBase64Encoded(key: string): boolean; - - /** - * Validates a function. - */ - export function isValidFunction(functionObject: any, functionName: string): void; - - /** - * Validates that a Service Bus namespace name - * is legally allowable. Does not check availability. - */ - export function namespaceNameIsValid(name: string): boolean; - export function namespaceNameIsValid(name: string, callback: ErrorCallback): boolean; - - /** - * Validates a container name. - */ - export function containerNameIsValid(containerName: string): boolean; - export function containerNameIsValid(containerName: string, callback: ErrorCallback): boolean; - - /** - * Validates a blob name. - */ - export function blobNameIsValid(containerName: string, blob: string): boolean; - export function blobNameIsValid(containerName: string, blob: string, callback: ErrorCallback): boolean; - - /** - * Validates a table name. - */ - export function tableNameIsValid(tableName: string): boolean; - export function tableNameIsValid(tableName: string, callback: ErrorCallback): boolean; - - /** - * Validates a queue name. - */ - export function queueNameIsValid(queueName: string): boolean; - export function queueNameIsValid(queueName: string, callback: ErrorCallback): boolean; - - export function pageRangesAreValid(rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number): boolean; - export function pageRangesAreValid(rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number, callback: ErrorCallback): boolean; - - export function validateArgs(functionName: string, validationRules: Function): boolean; - } - - export module date { - /** - * Generates a Date object which is in the given days from now. - */ - export function daysFromNow(days: number): Date; - - /** - * Generates a Date object which is in the given hours from now. - */ - export function hoursFromNow(hours: number): Date; - - /** - * Generates a Date object which is in the given minutes from now. - */ - export function minutesFromNow(minutes: number): Date; - - /** - * Generates a Date object which is in the given seconds from now. - */ - export function secondsFromNow(seconds: number): Date; - } //#endregion - //#region Non-explicit, undeclared interfaces - export interface WebResponse { - isSuccessful: boolean; - statusCode: number; - body: { - entry: { - id: string; - title: any; - updated: string; - author: { - name: any; - }; - link: any; - category: any; - content: any; - }; - }; - headers: any; - md5: any; - } + //#region Table Methods - //#region Common Interfaces - export interface SimpleCallback { - (error: Error, result: T): void; - } - export interface ErrorCallback { - (error: Error): void; - } - export interface StorageCallbackVoid { - (err: Error, response: WebResponse): void; - } - export interface StorageCallback { - (err: Error, result: T, response: WebResponse): void; - } - export interface StorageServiceStatsCallback extends StorageCallback { } - export interface StorageServicePropertiesCallback extends StorageCallback { } + getTable(table: string, callback?: TableRequestCallback): void; + getTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback): void; - export interface TimeoutIntervalOptions { - locationMode?: string; - timeoutIntervalInMs?: number; - maximumExecutionTimeInMs?: number; - } - export interface MetadataOptions extends TimeoutIntervalOptions { - metadata?: StorageMetadata; - } - export interface StorageAclOptions extends TimeoutIntervalOptions { - leaseId?: string; - signedIdentifiers: SignedIdentifier[] - } + createTable(table: string, callback?: TableRequestCallback): void; + createTable(table: string, options: TimeoutIntervalOptions, callback?: TableRequestCallback): void; - export interface Dictionary { - [key: string]: T; - } - export interface StorageServiceProperties { - Logging: { - Version: number; - Delete: boolean; - Read: boolean; - Write: boolean; - RetentionPolicy: { - Enabled: boolean; - Days: number; - }; - }; - Metrics: { - Version: number; - Enabled: boolean; - IncludeAPIs: boolean; - RetentionPolicy: { - Enabled: boolean; - Days: number; - }; - }; - DefaultServiceVersion: string; - } - export interface StorageServiceStats { - GeoReplication: { - Status: string; - LastSyncTime: Date; - } - } - export interface SignedIdentifier { - Id: string; - AccessPolicy: SharedAccessPolicy; - } - export interface StorageMetadata { + createTableIfNotExists(table: string, callback?: CreateTableIfNotExistsCallback): void; + createTableIfNotExists(table: string, options: TimeoutIntervalOptions, callback?: CreateTableIfNotExistsCallback): void; + + deleteTable(table: string, callback?: DeleteTableCallback): void; + deleteTable(table: string, options: TimeoutIntervalOptions, callback?: DeleteTableCallback): void; + + queryTables(callback?: QueryTablesCallback): void; + queryTables(options: QueryTablesOptions, callback?: QueryTablesCallback): void; + + //#endregion + + //#region Entities Methods + + queryEntity(table: string, partitionKey: string, rowKey: string, callback?: QueryEntityCallback): void; + queryEntity(table: string, partitionKey: string, rowKey: string, options: TimeoutIntervalOptions, callback?: QueryEntityCallback): void; + + queryEntities(tableQuery: TableQuery, callback?: QueryEntitiesCallback): void; + queryEntities(tableQuery: TableQuery, options: TimeoutIntervalOptions, callback?: QueryEntitiesCallback): void; + + insertEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; + insertEntity(tableName: string, entityDescriptor: Entity, options: TimeoutIntervalOptions, callback?: ModifyEntityCallback): void; + + insertOrReplaceEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; + insertOrReplaceEntity(tableName: string, entityDescriptor: Entity, options: TimeoutIntervalOptions, callback?: ModifyEntityCallback): void; + + updateEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; + updateEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: ModifyEntityCallback): void; + + mergeEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; + mergeEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: ModifyEntityCallback): void; + + insertOrMergeEntity(tableName: string, entityDescriptor: Entity, callback?: ModifyEntityCallback): void; + insertOrMergeEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: ModifyEntityCallback): void; + + deleteEntity(tableName: string, entityDescriptor: Entity, callback?: DeleteEntityCallback): void; + deleteEntity(tableName: string, entityDescriptor: Entity, options: UpdateEntityOptions, callback?: DeleteEntityCallback): void; + + //#endregion +} + +declare export class BlobService extends StorageServiceClient { + singleBlobPutThresholdInBytes: number; + parallelOperationThreadCount: number; + + SpeedSummary: typeof SpeedSummary; + + //#region Constructors + + /** + * Creates a new BlobService object. + * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. + * + * @constructor + * @extends {StorageServiceClient} + */ + constructor(); + + /** + * Creates a new BlobService object. + * Uses a connectionString to connect + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} connectionString The connection string. + */ + constructor(connectionString: string); + + /** + * Creates a new BlobService object. + * Uses a storage account and an access key. + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} storageAccount The storage account or the connection string. + * @param {string} storageAccessKey The storage access key. + * @param {string} host The host address. + * @param {object} sasToken The Shared Access Signature token. + */ + constructor(storageAccount: string, storageAccessKey: string, host?: string, sasToken?: string); + + //#endregion + + //#region Service Methods + + /** + * Gets the properties of a storage account�s Blob service, including Azure Storage Analytics. + */ + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; + + /** + * Sets the properties of a storage account�s Blob service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + */ + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Containers Methods + + /** + * Lists a segment containing a collection of container items under the specified account. + */ + listContainers(callback: ListContainersCallback): void; + listContainers(options: ListContainersOptions, callback: ListContainersCallback): void; + + /** + * Creates a new container under the specified account. + * If a container with the same name already exists, the operation fails. + */ + createContainer(container: string, callback: StorageCallback): void; + createContainer(container: string, options: CreateContainerOptions, callback: StorageCallback): void; + + /** + * Creates a new container under the specified account if the container does not exists. + */ + createContainerIfNotExists(container: string, callback: StorageCallback): void; + createContainerIfNotExists(container: string, options: CreateContainerOptions, callback: StorageCallback): void; + + /** + * Retrieves a container and its properties from a specified account. + */ + getContainerProperties(container: string, callback: StorageCallback): void; + getContainerProperties(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Returns all user-defined metadata for the container. + */ + getContainerMetadata(container: string, callback: StorageCallback): void; + getContainerMetadata(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets the container's metadata. + */ + setContainerMetadata(container: string, metadata: StorageMetadata, callback: StorageCallback): void; + setContainerMetadata(container: string, metadata: StorageMetadata, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Gets the container's ACL. + */ + getContainerAcl(container: string, callback: StorageCallback): void; + getContainerAcl(container: string, options: GetContainerPropertiesOptions, callback: StorageCallback): void; + + /** + * Updates the container's ACL. + */ + setContainerAcl(container: string, publicAccessLevel: string, callback: StorageCallback): void; + setContainerAcl(container: string, publicAccessLevel: string, options: StorageAclOptions, callback: StorageCallback): void; + + /** + * Marks the specified container for deletion. + * The container and any blobs contained within it are later deleted during garbage collection. + */ + deleteContainer(container: string, callback: StorageCallbackVoid): void; + deleteContainer(container: string, options: LeaseIdOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Blob Methods + + /** + * Lists all of the blobs in the given container. + */ + listBlobs(container: string, callback: ListBlobsCallback): void; + listBlobs(container: string, options: ListBlobsOptions, callback: ListBlobsCallback): void; + + /** + * Returns all user-defined metadata, standard HTTP properties, and system properties for the blob. + * It does not return or modify the content of the blob. + */ + getBlobProperties(container: string, blob: string, callback: StorageCallback): void; + getBlobProperties(container: string, blob: string, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets user-defined properties for the specified blob or snapshot. + * It does not return or modify the content of the blob. + */ + setBlobProperties(container: string, blob: string, callback: StorageCallback): void; + setBlobProperties(container: string, blob: string, options: SetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Sets user-defined metadata for the specified blob or snapshot as one or more name-value pairs + * It does not return or modify the content of the blob. + */ + setBlobMetadata(container: string, blob: string, metadata: StorageMetadata, callback: StorageCallback): void; + setBlobMetadata(container: string, blob: string, metadata: StorageMetadata, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Provides a stream to read from a blob. + */ + getBlob(container: string, blob: string, callback: StorageCallback): stream.Readable; + getBlob(container: string, blob: string, options: ReadBlobOptions, callback: StorageCallback): stream.Readable; + + /** + * Downloads a blob into a file. + */ + getBlobToFile(container: string, blob: string, localFileName: string, callback: StorageCallback): void; + getBlobToFile(container: string, blob: string, localFileName: string, options: ReadBlobOptions, callback: StorageCallback): void; + + /** + * Downloads a blob into a stream. + */ + getBlobToStream(container: string, blob: string, stream: stream.Writable, callback: StorageCallback): void; + getBlobToStream(container: string, blob: string, stream: stream.Writable, options: ReadBlobOptions, callback: StorageCallback): void; + + /** + * Downloads a blob into a text string. + */ + getBlobToText(container: string, blob: string, callback: GetBlobToTextCallback): void; + getBlobToText(container: string, blob: string, options: ReadBlobOptions, callback: GetBlobToTextCallback): void; + + /** + * Marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. + * If a blob has snapshots, you must delete them when deleting the blob. Using the deleteSnapshots option, you can choose either to delete both the blob and its snapshots, + * or to delete only the snapshots but not the blob itself. If the blob has snapshots, you must include the deleteSnapshots option or the blob service will return an error + * and nothing will be deleted. + * If you are deleting a specific snapshot using the snapshotId option, the deleteSnapshots option must NOT be included. + */ + deleteBlob(container: string, blob: string, callback: StorageCallback): void; + deleteBlob(container: string, blob: string, options: DeleteBlobOptions, callback: StorageCallback): void; + + /** + * Creates a read-only snapshot of a blob. + */ + createBlobSnapshot(container: string, blob: string, callback: StorageCallback): void; + createBlobSnapshot(container: string, blob: string, options: BlobSnapshotOptions, callback: StorageCallback): void; + + /** + * Starts to copy a blob to a destination within the storage account. The Copy Blob operation copies the entire committed blob. + */ + copyBlob(sourceUri: string, targetContainer: string, targetBlob: string, callback: StorageCallback): void; + copyBlob(sourceUri: string, targetContainer: string, targetBlob: string, options: CopyBlobOptions, callback: StorageCallback): void; + + /** + * Creates a read-only snapshot of a blob. + */ + abortCopyBlob(container: string, blob: string, copyId: string, callback: StorageCallbackVoid): void; + abortCopyBlob(container: string, blob: string, copyId: string, options: LeaseIdOptions, callback: StorageCallbackVoid): void; + + /** + * Retrieves a shared access signature token. + */ + generateSharedAccessSignature(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): SharedAccessSignatureResult; + + /** + * Retrieves a blob or container URL. + */ + getBlobUrl(container: string): string; + getBlobUrl(container: string, blob: string): string; + getBlobUrl(container: string, blob: string, sharedAccessPolicy: SharedAccessPolicy): string; + + /** + * Uploads a blob. + */ + createBlob(container: string, blob: string, blobType: string, callback: StorageCallback): stream.Writable; + createBlob(container: string, blob: string, blobType: string, options: UploadBlockBlobOptions, callback: StorageCallback): stream.Writable; + + //#endregion + + //#region Page Blob Methods + + /** + * Creates a page blob of the specified length. + */ + createPageBlob(container: string, blob: string, length: number, callback: StorageCallbackVoid): void; + createPageBlob(container: string, blob: string, length: number, options: SetBlobPropertiesOptions, callback: StorageCallbackVoid): void; + + /** + * Updates a page blob from a stream. + */ + createBlobPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, callback: StorageCallback): void; + createBlobPagesFromStream(container: string, blob: string, readStream: stream.Readable, rangeStart: number, rangeEnd: number, options: CreatePagesOptions, callback: StorageCallback): void; + + /** + * Updates a page blob from a text string. + */ + createBlobPagesFromText(container: string, blob: string, text: string, rangeStart: number, rangeEnd: number, callback: StorageCallback): void; + createBlobPagesFromText(container: string, blob: string, text: string, rangeStart: number, rangeEnd: number, options: CreatePagesOptions, callback: StorageCallback): void; + + /** + * Lists page ranges. + * Lists all of the page ranges by default, or only the page ranges over a specific range of bytes if rangeStart and rangeEnd are specified. + */ + listBlobRegions(container: string, blob: string, callback: StorageCallback): void; + listBlobRegions(container: string, blob: string, options: PageRangeOptions, callback: StorageCallback): void; + + /** + * Clears a range of pages. + */ + clearBlobPages(container: string, blob: string, rangeStart: number, rangeEnd: number, callback: StorageCallbackVoid): void; + clearBlobPages(container: string, blob: string, rangeStart: number, rangeEnd: number, options: LeaseAccessConditionsOptions, callback: StorageCallbackVoid): void; + + /** + * Resizes a page blob. + */ + resizePageBlob(container: string, blob: string, size: number, callback: StorageCallback): void; + resizePageBlob(container: string, blob: string, size: number, options: LeaseAccessConditionsOptions, callback: StorageCallback): void; + + /** + * Sets the page blob's sequence number. + */ + setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: string, callback: StorageCallback): void; + setPageBlobSequenceNumber(container: string, blob: string, sequenceNumberAction: string, sequenceNumber: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + //#endregion + + //#region Block Blob Methods + + /** + * Uploads a block blob from file. + */ + putBlockBlobFromFile(container: string, blob: string, localFileName: string, callback: StorageCallback): SpeedSummary; + putBlockBlobFromFile(container: string, blob: string, localFileName: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + createBlockBlobFromFile(container: string, blob: string, localFileName: string, callback: StorageCallback): SpeedSummary; + createBlockBlobFromFile(container: string, blob: string, localFileName: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Uploads a block blob from a stream. + */ + putBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, callback: StorageCallback): SpeedSummary; + putBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + createBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, callback: StorageCallback): SpeedSummary; + createBlockBlobFromStream(container: string, blob: string, stream: stream.Stream, streamLength: number, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Uploads a block blob from a text string. + */ + createBlockBlobFromText(container: string, blob: string, text: string, callback: StorageCallback): SpeedSummary; + createBlockBlobFromText(container: string, blob: string, text: string, options: UploadBlockBlobOptions, callback: StorageCallback): SpeedSummary; + + /** + * Creates a new block to be committed as part of a blob. + */ + createBlobBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Stream, streamLength: number, callback: StorageCallbackVoid): void; + createBlobBlockFromStream(blockId: string, container: string, blob: string, readStream: stream.Stream, streamLength: number, options: CreateBlockOptions, callback: StorageCallbackVoid): void; + + /** + * Creates a new block to be committed as part of a blob. + */ + createBlobBlockFromText(blockId: string, container: string, blob: string, text: string, callback: StorageCallbackVoid): void; + createBlobBlockFromText(blockId: string, container: string, blob: string, text: string, options: CreateBlockOptions, callback: StorageCallbackVoid): void; + + /** + * Writes a blob by specifying the list of block IDs that make up the blob. + * In order to be written as part of a blob, a block must have been successfully written to the server in a prior + * createBlock operation. + */ + commitBlobBlocks(container: string, blob: string, blockList: BlockList, callback: StorageCallback): void; + commitBlobBlocks(container: string, blob: string, blockList: BlockList, options: CreateBlockOptions, callback: StorageCallback): void; + + /** + * Retrieves the list of blocks that have been uploaded as part of a block blob. + */ + listBlobBlocks(container: string, blob: string, blockListType: string, callback: StorageCallback): void; + listBlobBlocks(container: string, blob: string, blockListType: string, options: GetBlobPropertiesOptions, callback: StorageCallback): void; + + /** + * Generate a random block id prefix. + */ + generateBlockIdPrefix(): string; + /** + * Get a block id according to prefix and block number. + */ + getBlockId(prefix: string, number: number): string; + + //#endregion + + //#region Lease Methods + + /** + * Acquires a new lease. + * If container and blob are specified, acquires a blob lease. + * Otherwise, if only container is specified and blob is null, acquires a container lease. + */ + acquireLease(container: string, blob: string, callback: StorageCallback): void; + acquireLease(container: string, blob: string, options: LeaseOptions, callback: StorageCallback): void; + + /** + * Renews an existing lease. + * If container and blob are specified, renews the blob lease. + * Otherwise, if only container is specified and blob is null, renews the container lease. + */ + renewLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + renewLease(container: string, blob: string, leaseId: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Releases the lease. + * If container and blob are specified, releases the blob lease. + * Otherwise, if only container is specified and blob is null, releases the container lease. + */ + releaseLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + releaseLease(container: string, blob: string, leaseId: string, options: AccessConditionsOptions, callback: StorageCallback): void; + + /** + * Breaks the lease but ensures that another client cannot acquire a new lease until the current lease period has expired. + * If container and blob are specified, breaks the blob lease. + * Otherwise, if only container is specified and blob is null, breaks the container lease. + */ + breakLease(container: string, blob: string, leaseId: string, callback: StorageCallback): void; + breakLease(container: string, blob: string, leaseId: string, options: BreakLeaseOptions, callback: StorageCallback): void; + + //#endregion +} + +declare export class QueueService extends StorageServiceClient { + authenticationProvider: SharedKey; + + //#region Constructors + + /** + * Creates a new BlobService object. + * Uses the AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables. + * + * @constructor + * @extends {StorageServiceClient} + */ + constructor(); + + /** + * Creates a new BlobService object. + * Uses a connectionString to connect + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} connectionString The connection string. + */ + constructor(connectionString: string); + + /** + * Creates a new BlobService object. + * Uses a storage account and an access key. + * + * @constructor + * @extends {StorageServiceClient} + * @param {string} storageAccount The storage account or the connection string. + * @param {string} storageAccessKey The storage access key. + * @param {string} host The host address. + * @param {object} sasToken The Shared Access Signature token. + */ + constructor(storageAccount: string, storageAccessKey: string, host?: string, sasToken?: string); + + //#endregion + + //#region Service Methods + + /** + * Gets the properties of a storage account�s Blob service, including Azure Storage Analytics. + */ + getServiceProperties(callback: StorageServicePropertiesCallback): void; + getServiceProperties(options: TimeoutIntervalOptions, callback: StorageServicePropertiesCallback): void; + + /** + * Sets the properties of a storage account�s Blob service, including Azure Storage Analytics. + * You can also use this operation to set the default request version for all incoming requests that do not have a version specified. + */ + setServiceProperties(serviceProperties: StorageServiceProperties, callback: StorageCallbackVoid): void; + setServiceProperties(serviceProperties: StorageServiceProperties, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + //#endregion + + //#region Queue Methods + + /** + * Lists all queues under the given account. + */ + listQueues(callback: ListQueuesCallback): void; + listQueues(options: ListQueuesOptions, callback: ListQueuesCallback): void; + + /** + * Creates a new queue under the given account. + */ + createQueue(queue: string, callback: StorageCallback): void; + createQueue(queue: string, options: MetadataOptions, callback: StorageCallback): void; + + /** + * Creates a new queue under the given account if it doesn't exist. + */ + createQueueIfNotExists(queue: string, callback: StorageCallback): void; + createQueueIfNotExists(queue: string, options: MetadataOptions, callback: StorageCallback): void; + + /** + * Permanently deletes the specified queue. + */ + deleteQueue(queue: string, callback: StorageCallback): void; + deleteQueue(queue: string, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + /** + * Returns queue properties, including user-defined metadata. + */ + getQueueMetadata(queue: string, callback: StorageCallback): void; + getQueueMetadata(queue: string, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + /** + * Sets user-defined metadata on the specified queue. Metadata is associated with the queue as name-value pairs. + */ + setQueueMetadata(queue: string, metadata: StorageMetadata, callback: StorageCallback): void; + setQueueMetadata(queue: string, metadata: StorageMetadata, options: TimeoutIntervalOptions, callback: StorageCallback): void; + + //#endregion + + //#region Message Methods + + /** + * Adds a new message to the back of the message queue. A visibility timeout can also be specified to make the message + * invisible until the visibility timeout expires. A message must be in a format that can be included in an XML request + * with UTF-8 encoding. The encoded message can be up to 64KB in size for versions 2011-08-18 and newer, or 8KB in size + * for previous versions. + */ + createMessage(queue: string, messageText: string, callback: StorageCallback): void + createMessage(queue: string, messageText: string, options: CreateQueueMessageOptions, callback: StorageCallback): void + + /** + * Retrieves a message from the queue and makes it invisible to other consumers. + */ + getMessages(queue: string, callback: StorageCallback): void; + getMessages(queue: string, options: GetQueueMessagesOptions, callback: StorageCallback): void; + + /** + * Retrieves a message from the front of the queue, without changing the message visibility. + */ + peekMessages(queue: string, callback: StorageCallback): void; + peekMessages(queue: string, options: PeekQueueMessagesOptions, callback: StorageCallback): void; + + /** + * Deletes a specified message from the queue. + */ + deleteMessage(queue: string, messageId: string, popreceipt: string, callback: StorageCallback): void + deleteMessage(queue: string, messageId: string, popreceipt: string, options: TimeoutIntervalOptions, callback: StorageCallback): void + + /** + * Clears all messages from the queue. + */ + clearMessages(queue: string, callback: StorageCallbackVoid): void; + clearMessages(queue: string, options: TimeoutIntervalOptions, callback: StorageCallbackVoid): void; + + /** + * Deletes a specified message from the queue. + */ + updateMessage(queue: string, messageId: string, popreceipt: string, visibilitytimeout: number, callback: StorageCallback): void + updateMessage(queue: string, messageId: string, popreceipt: string, visibilitytimeout: number, options: UpdateQueueMessagesOptions, callback: StorageCallback): void + + //#endregion +} + +declare export class ServiceBusService { + +} + +declare export class SqlService { + +} + +declare export class ServiceManagementService { + +} + +declare export class SqlManagementService { +} +//#endregion + +//#region Service Creators +declare export function createTableService(): TableService; +declare export function createTableService(connectionString: string): TableService; +declare export function createTableService(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string): TableService; + +declare export function createBlobService(): BlobService; +declare export function createBlobService(connectionString: string): BlobService; +declare export function createBlobService(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string): BlobService; + +declare export function createQueueService(): QueueService; +declare export function createQueueService(connectionString: string): QueueService; +declare export function createQueueService(storageAccount: string, storageAccessKey: string, host?: string, authenticationProvider?: string): QueueService; + +declare export function createServiceBusService(): ServiceBusService; +declare export function createServiceBusService(connectionString: string): ServiceBusService; +declare export function createServiceBusService(namespace: string, accessKey?: string, issuer?: string, acsNamespace?: string, host?: string, authenticationProvider?: string): ServiceBusService; + +declare export function createSqlService(serverName: string, administratorLogin: string, administratorLoginPassword: string, host?: string, acsHost?: string, authenticationProvider?: string): SqlService; + +declare export function createServiceManagementService(subscriptionId: string, authentication: string, hostOptions: string): ServiceManagementService; + +declare export function createSqlManagementService(subscriptionId: string, authentication: string, hostOptions: string): SqlManagementService; +//#endregion + +//#region RoleEnvironment + +interface RoleEnvironmentInterface extends events.EventEmitter { + incorrectCallbackErr: string; + clientId: string; + VersionEndpointFixedPath: string; + EnvironmentVariables: { [key: string]: string; - } - export interface ContinuationToken { - nextMarker: string; - targetLocation: string; - } - export interface SharedAccessPolicy { - Id?: string; - AccessPolicy: { - Start?: Date; - Expiry: Date; - Permission?: string; - } - } - //#endregion - //#region TableService Interfaces - export interface TableRequestCallback { - (error: Error, tableResult: { TableName: string; }, response: WebResponse): void; - } + VersionEndpointEnvironmentName: string; + }; - export interface CreateTableIfNotExistsCallback { - (error: Error, created: boolean, response: WebResponse): void; - } + /** + * Returns a RoleInstance object that represents the role instance + * in which this code is currently executing. + */ + getCurrentRoleInstance(callback: SimpleCallback): void; - export interface DeleteTableCallback { - (error: Error, successful: boolean, response: WebResponse): void; - } + /** + * Returns the deployment ID that uniquely identifies the deployment in + * which this role instance is running. + */ + getDeploymentId(callback: SimpleCallback): void; - export interface QueryTablesCallback { - (error: Error, queryTablesResult: TableResult[], resultsContinuation: QueryResultContinuation, response: WebResponse): void; - } + /** + * Indicates whether the role instance is running in the Microsoft Azure + * environment. It is good practice to enclose any code that uses + * service runtime in the isAvailable callback. + */ + isAvailable(callback: SimpleCallback): void; - export interface QueryResultContinuation { - tableService: TableService; - } + /** + * Indicates whether the role instance is running in the development fabric. + */ + isEmulated(callback: SimpleCallback): void; - export interface QueryTablesOptions extends TimeoutIntervalOptions { - nextTableName?: string; - } + /** + * Returns the set of Role objects defined for your service. + * Roles are defined in the service definition file. + */ + getRoles(callback: SimpleCallback>): void; - export interface TableResult { - TableName: string; - } + /** + * Retrieves the settings in the service configuration file. + * + * A role's configuration settings are defined in the service definition file. + * Values for configuration settings are set in the service configuration file. + * For more information on configuration settings, see the [Service Definition Schema](http://msdn.microsoft.com/en-us/library/windowsazure/ee758711.aspx) + * and [Service Configuration Schema](http://msdn.microsoft.com/en-us/library/windowsazure/ee758710.aspx). + */ + getConfigurationSettings(callback: SimpleCallback>): void; - export interface QueryEntityCallback { - (error: Error, entity: Entity, response: WebResponse): void; - } + /** + * Retrieves the set of named local storage resources, along with the path. + * For example, the DiagnosticStore resource which is defined for every role + * provides a location for runtime diagnostics and logs. + */ + getLocalResources(callback: SimpleCallback>): void; - export interface QueryEntitiesCallback { - (error: Error, entities: Entity[], resultContinuation: QueryEntitiesResultContinuation, response: WebResponse): void; - } + /** + * Requests that the current role instance be stopped and restarted. + * + * Before the role instance is recycled, the Microsoft Azure load balancer takes the role instance out of rotation. + * This ensures that no new requests are routed to the instance while it is restarting. + * + * A call to `RequestRecycle` initiates the normal shutdown cycle. Microsoft Azure raises the + * `Stopping` event and calls the `OnStop` method so that you can run the necessary code to + * prepare the instance to be recycled. + */ + requestRecycle(callback: ErrorCallback): void; - export interface QueryEntitiesResultContinuation extends QueryResultContinuation { - tableQuery: TableQuery; - nextPartitionKey: string; - nextRowKey: string; - getNextPage(callback?: QueryEntitiesCallback): void; - hasNextPage(): boolean; - } + /** + * Sets the status of the role instance. + * + * An instance may indicate that it is in one of two states: Ready or Busy. If an instance's state is Ready, it is + * prepared to receive requests from the load balancer. If the instance's state is Busy, it will not receive + * requests from the load balancer. + */ + setStatus(roleInstanceStatus: string, expirationUtc: Date, callback: ErrorCallback): void; - export interface ModifyEntityCallback { - (error: Error, entity: Entity, response: WebResponse): void; - } + /** + * Clears the status of the role instance. + * An instance may indicate that it has completed communicating status by calling this method. + */ + clearStatus(callback: ErrorCallback): void; +} - export interface DeleteEntityCallback { - (error: Error, successful: boolean, response: WebResponse): void; - } +declare export var RoleEnvironment: RoleEnvironmentInterface; - export interface UpdateEntityOptions extends TimeoutIntervalOptions { - checkEtag?: boolean; - } +//#endregion - export interface Entity { - PartitionKey: string; - RowKey: string; - Timestamp?: Date; - etag?: string; - [property: string]: string | number | boolean | Date; - } - //#endregion - //#region BlobService Interfaces - export interface LeaseIdOptions extends TimeoutIntervalOptions { - leaseId?: string; - } - export interface AccessConditionsOptions extends TimeoutIntervalOptions { - accessConditions?: StorageAccessCondition; - } - export interface LeaseAccessConditionsOptions extends LeaseIdOptions { - accessConditions?: StorageAccessCondition; - } +//#region Export of internal classes +declare export class WebResource { + rawResponse: boolean; + queryString: Dictionary; - export interface ListContainersOptions extends TimeoutIntervalOptions { - prefix?: string; - maxresults?: number; - marker: string; - include?: string; - } - export interface ListContainersCallback { - (err: Error, containers: ContainerResult[], continuationToken: ContinuationToken, response: WebResponse): void; - } - export interface CreateContainerOptions extends TimeoutIntervalOptions { - metadata?: StorageMetadata; - publicAccessLevel?: string; - } - export interface GetContainerPropertiesOptions extends TimeoutIntervalOptions { - leaseId?: string; - } - export interface GetContainerMetadataOptions extends GetContainerPropertiesOptions { - accessConditions?: StorageAccessCondition; - } + constructor(); - export interface ListBlobsOptions extends ListContainersOptions { - prefix?: string; - delimiter?: string; - } - export interface ListBlobsCallback { - (err: Error, blobs: BlobResult[], continuationToken: ContinuationToken, response: WebResponse): void; - } - export interface GetBlobPropertiesOptions extends LeaseAccessConditionsOptions { - snapshotId?: string; - } - export interface SetBlobPropertiesOptions extends LeaseAccessConditionsOptions { - contentType?: string; - contentEncoding?: string; - contentLanguage?: string; - contentMD5?: string; - cacheControl?: string; - contentDisposition?: string; - } - export interface ReadBlobOptions extends GetBlobPropertiesOptions { - rangeStart?: string; - rangeEnd?: string; - useTransactionalMD5?: boolean; - disableContentMD5Validation?: boolean; - } - export interface GetBlobToTextCallback { - (err: Error, text: string, result: BlobResult, response: WebResponse): void; - } - export interface DeleteBlobOptions extends GetBlobPropertiesOptions { - deleteSnapshots?: string; - } - export interface BlobSnapshotOptions extends GetBlobPropertiesOptions { - metadata?: StorageMetadata; - } - export interface CopyBlobOptions extends BlobSnapshotOptions { - sourceLeaseId?: string; - sourceAccessConditions: StorageAccessCondition; - } + get(path: string): WebResource; + put(path: string): WebResource; + post(path: string): WebResource; + merge(path: string): WebResource; + head(path: string): WebResource; + del(path: string): WebResource; - export interface UploadBlobOptions extends SetBlobPropertiesOptions { - metadata?: StorageMetadata; - speedSummary?: SpeedSummary; - parallelOperationThreadCount?: number; - storeBlobContentMD5?: boolean; - useTransactionalMD5?: boolean; - } - export interface CreatePagesOptions extends LeaseAccessConditionsOptions { - contentMD5?: string; - useTransactionalMD5?: boolean; - } - export interface PageRangeOptions extends LeaseIdOptions { - snapshotId?: string; - rangeStart?: number; - rangeEnd?: number; - } + withProperty(name: string, value: string): WebResource; + withRawResponse(rawResponse: boolean): WebResource; + withHeadersOnly(headersOnly: boolean): WebResource; + withQueryOption(name: string, value: string, defaultValue: string): WebResource; + withQueryOptions(queryOptions: Dictionary): WebResource; + withHeader(name: string, value: string): WebResource; + withHeaders(headers: Dictionary): WebResource; + withBody(body: any): WebResource; + addOptionalMetadataHeaders(metadata: StorageMetadata): WebResource; - export interface UploadBlockBlobOptions extends UploadBlobOptions { - blockIdPrefix?: string; - } - export interface CreateBlockOptions extends LeaseAccessConditionsOptions { - contentMD5?: string; - useTransactionalMD5?: boolean; - } + validResponse(statusCode: number): boolean; + pipeInput(inputStream: stream.Stream, destStream: stream.Stream): stream.Stream; +} - export interface LeaseOptions extends AccessConditionsOptions { - leaseDuration?: string; - proposedLeaseId?: string; - } - export interface BreakLeaseOptions extends AccessConditionsOptions { - leaseBreakPeriod?: number; - } +declare export class ServiceClient extends events.EventEmitter { + static EnvironmentVariables: any; + static DEVSTORE_STORAGE_ACCOUNT: string; + static DEVSTORE_STORAGE_ACCESS_KEY: string; + static DEVSTORE_BLOB_HOST: string; + static DEVSTORE_QUEUE_HOST: string; + static DEVSTORE_TABLE_HOST: string; + static CLOUD_BLOB_HOST: string; + static CLOUD_QUEUE_HOST: string; + static CLOUD_TABLE_HOST: string; + static CLOUD_SERVICEBUS_HOST: string; + static CLOUD_ACCESS_CONTROL_HOST: string; + static CLOUD_SERVICE_MANAGEMENT_HOST: string; + static CLOUD_DATABASE_HOST: string; + static DEFAULT_SERVICEBUS_ISSUER: string; + static DEFAULT_WRAP_NAMESPACE_SUFFIX: string; + static DEFAULT_PROTOCOL: string; - export interface SharedAccessSignatureResult { - baseUrl: string; - path: string; - queryString: { - se: string; - sp: string; - sr: string; - sv: string; - sig: string; - }; - url: () => string; - } - export interface BlobHeaders { - cacheControl?: string; - contentType?: string; - contentEncoding?: string; - contentLanguage?: string; - contentDisposition?: string; - } - export interface PageRange { - start: number; - end: number; - } - export interface BlockList { - LatestBlocks: string[]; - CommittedBlocks: string[]; - UncommittedBlocks: string[]; - } - export interface StorageAccessCondition { - "If-Modified-Since": Date; - "If-Unmodified-Since": Date; - "If-Match": string; - "If-None-Match": string; - } - //#endregion - //#region QueueService Interfaces - export interface ListQueuesOptions extends TimeoutIntervalOptions { - prefix?: string; - maxresults?: number; - marker: string; - include?: string; - } - export interface ListQueuesCallback { - (err: Error, queues: QueueResult[], continuationToken: ContinuationToken, response: WebResponse): void; - } + constructor(host: string, authenticationProvider: any); - export interface CreateQueueMessageOptions extends TimeoutIntervalOptions { - messagettl?: number; - visibilitytimeout?: number; - } - export interface PeekQueueMessagesOptions extends TimeoutIntervalOptions { - numofmessages?: number; - } - export interface GetQueueMessagesOptions extends PeekQueueMessagesOptions { - peekonly?: boolean; - visibilitytimeout?: number; - } - export interface UpdateQueueMessagesOptions extends TimeoutIntervalOptions { - messagetext?: string; - } - //#endregion + setHost(host: string): void; + performRequest(webResource: WebResource, outputData: string, options: any, callback: Function): void; + performRequestOutputStream(webResource: WebResource, outputStream: any, options: any, callback: Function): void; + performRequestInputStream(webResource: WebResource, outputData: string, inputStream: any, options: any, callback: Function): void; + withFilter(newFilter: Filter): ServiceClient; + parseMetadataHeaders(headers: any): any; + isEmulated(): boolean; + setProxy(proxyUrl: string, proxyPort: number): void; +} - //#region RoleEnvironment Interfaces - export interface Role { +declare export class BatchServiceClient extends StorageServiceClient { + operations: any[]; + + constructor(storageAccount: string, storageAccessKey: string, host: string, usePathstyleUri: boolean, authenticationProvider: any); + beginBatch(): void; + isInBatch(): boolean; + rollback(): void; + hasOperations(): boolean; + addOperation(webResource: WebResource, outputData: any): void; + commitBatch(callback: (error: any, operationResponses: any[], response: any) => void): void; + commitBatch(options: any, callback: (error: any, operationResponses: any[], response: any) => void): void; + processResponse(responseObject: any, requestOperations: any[]): any[]; + processOperation(webResource: WebResource, rawResponse: string): any; +} + +declare export class ServiceManagementClient { + +} + +declare export class TableQuery { + static select(...fields: string[]): TableQuery; + from(table: string): TableQuery; + whereKeys(partitionKey: string, rowKey: string): TableQuery; + whereNextKeys(partitionKey: string, rowKey: string): TableQuery; + where(condition: string, ...values: string[]): TableQuery; + and(condition: string, ...args: string[]): TableQuery; + or(condition: string, ...args: string[]): TableQuery; + top(integer: number): TableQuery; + toQueryObject(): any; + toPath(): string; +} + +declare export class BlobResult { + blob: string; + container: string; + + etag: string; + lastModified: string; + contentType: string; + contentEncoding: string; + contentLanguage: string; + contentMD5: string; + cacheControl: string; + contentRange: string; + contentTypeHeader: string; + contentEncodingHeader: string; + contentLanguageHeader: string; + contentMD5Header: string; + cacheControlHeader: string; + contentLength: number; + contentLengthHeader: number; + contentDisposition: string; + contentDispositionHeader: string; + range: string; + rangeHeader: string; + getContentMd5: string; + acceptRanges: string; + blobType: string; + leaseStatus: string; + leaseId: string; + leaseDuration: string; + leaseState: string; + sequenceNumber: string; + copyStatus: string; + copyCompletionTime: string; + copyStatusDescription: string; + copyId: string; + copyProgress: number; + requestId: string; + + metadata: StorageMetadata; + + constructor(); + constructor(container: string); + constructor(container: string, blob: string); + + static parse(blobXml: any): BlobResult; + static setHeadersFromBlob(webResource: WebResource, blob: BlobResult): void; + + getPropertiesFromHeaders(headers: any): void; +} + +declare export class ContainerResult { + name: string; + publicAccessLevel: string; + + etag: string; + lastModified: string; + leaseStatus: string; + leaseDuration: string; + leaseState: string; + requestId: string; + + metadata: StorageMetadata; + signedIdentifiers: SignedIdentifier[]; + + constructor(); + constructor(name: string); + constructor(name: string, publicAccessLevel: string); + + static parse(containerXml: any): ContainerResult; + + getPropertiesFromHeaders(headers: any): void; +} + +declare export class LeaseResult { + container: string; + blob: string; + id: string; + time: string; + etag: string; + lastModified: string; + + constructor(); + constructor(container: string); + constructor(container: string, blob: string); + constructor(container: string, blob: string, id: string); + constructor(container: string, blob: string, id: string, time: string); + + getPropertiesFromHeaders(header: any): void; +} + +declare export class QueueResult { + name: string; + metadata: StorageMetadata; + approximatemessagecount: number; + + constructor(); + constructor(name: string); + constructor(name: string, metadata: StorageMetadata); + + static parse(messageXml: any): QueueResult; + + getPropertiesFromHeaders(headers: any): void; +} + +declare export class QueueMessageResult { + queue: string; + insertiontime: string; + expirationtime: string; + timenextvisible: string; + messagetext: string; + dequeuecount: string; + messageid: string; + popreceipt: string; + metadata: StorageMetadata; + + constructor(); + constructor(queue: string); + constructor(queue: string, messageid: string); + constructor(queue: string, messageid: string, popreceipt: string); + constructor(queue: string, messageid: string, popreceipt: string, metadata: StorageMetadata); + + static serialize(messageJs: string): string; + static parse(messageXml: any): QueueMessageResult; + + getPropertiesFromHeaders(headers: any): void; +} + +declare export class SpeedSummary { + name: string; + totalSize: number; + completeSize: number; + + _startTime: Date; + _timeWindowInSeconds: number; + _timeWindow: number; + _totalWindowSize: number; + _speedTracks: number[]; + _speedTrackPtr: number; + + constructor(name: string); + + /** + * Get running seconds + */ + getElapsedSeconds(): string; + getElapsedSeconds(humanReadable: boolean): number; + + /** + * Get complete percentage + */ + getCompletePercent(): number; + getCompletePercent(len: number): number; + + /** + * Get average upload/download speed + */ + getAverageSpeed(): string; + getAverageSpeed(humanReadable: boolean): number; + + /** + * Get internal speed + */ + getSpeed(): string; + getSpeed(humanReadable: boolean): number; + + /** + * Get auto increment function + */ + getSpeed(size: number): (error: Error, value: any) => void; + + /** + * Get total size + */ + getTotalSize(): string; + getTotalSize(humanReadable: boolean): number; + + /** + * Get completed data size + */ + getCompleteSize(): string; + getCompleteSize(humanReadable: boolean): number; +} + +declare export module Constants { + +} + +export interface Filter { + handle(requestOptions: any, next: Function): void; +} + +declare export class LinearRetryPolicyFilter implements Filter { + constructor(retryCount?: number, retryInterval?: number); + retryCount: number; + retryInterval: number; + handle(requestOptions: any, next: Function): void; +} + +declare export class ExponentialRetryPolicyFilter implements Filter { + constructor(retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number); + retryCount: number; + retryInterval: number; + minRetryInterval: number; + maxRetryInterval: number; + handle(requestOptions: any, next: Function): void; +} + +declare export class HmacSha256Sign { + +} + +declare export class SharedAccessSignature { + storageAccount: string; + storageAccessKey: string; + permissionSet: string[]; + signer: HmacSha256Sign; + + constructor(storageAccount: string, storageAccessKey: string, permissionSet: string[]) + + /** + * Generates the query string for a shared access signature signing. + */ + generateSignedQueryString(path: string, queryString: Dictionary, resourceType: string, sharedAccessPolicy: SharedAccessPolicy): Dictionary; + + /** + * Signs a request with the signature header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Generates the shared access signature for a resource. + */ + _generateSignature(path: string, resourceType: string, sharedAccessPolicy: SharedAccessPolicy): string; + + /** + * Generates the query string for a shared access signature signing. + */ + _permissionMatchesRequest(sharedAccessSignature: string, webResource: WebResource, resourceType: string, requiredPermissions: string[]): string; +} + +declare export class SharedKey { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; + + /** + * Constructs the Canonicalized Headers string. + * + * To construct the CanonicalizedHeaders portion of the signature string, + * follow these steps: 1. Retrieve all headers for the resource that begin + * with x-ms-, including the x-ms-date header. 2. Convert each HTTP header + * name to lowercase. 3. Sort the headers lexicographically by header name, + * in ascending order. Each header may appear only once in the + * string. 4. Unfold the string by replacing any breaking white space with a + * single space. 5. Trim any white space around the colon in the header. 6. + * Finally, append a new line character to each canonicalized header in the + * resulting list. Construct the CanonicalizedHeaders string by + * concatenating all headers in this list into a single string. + */ + _getCanonicalizedHeaders(webResource: WebResource): string; +} + +declare export class SharedKeyLite { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; + + /** + * Constructs the Canonicalized Headers string. + * + * To construct the CanonicalizedHeaders portion of the signature string, + * follow these steps: 1. Retrieve all headers for the resource that begin + * with x-ms-, including the x-ms-date header. 2. Convert each HTTP header + * name to lowercase. 3. Sort the headers lexicographically by header name, + * in ascending order. Each header may appear only once in the + * string. 4. Unfold the string by replacing any breaking white space with a + * single space. 5. Trim any white space around the colon in the header. 6. + * Finally, append a new line character to each canonicalized header in the + * resulting list. Construct the CanonicalizedHeaders string by + * concatenating all headers in this list into a single string. + */ + _getCanonicalizedHeaders(webResource: WebResource): string; +} + +declare export class SharedKeyTable { + storageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; +} + +declare export class SharedKeyLiteTable { + torageAccount: string; + storageAccessKey: string; + usePathStyleUri: string; + signer: HmacSha256Sign; + + constructor(storageAccount: string, storageAccessKey: string, usePathStyleUri: boolean); + + /** + * Signs a request with the Authentication header. + */ + signRequest(webResource: WebResource, callback: ErrorCallback): void; + + /** + * Retrieves the webresource's canonicalized resource string. + */ + _getCanonicalizedResource(webResource: WebResource): string; +} + +declare export module ISO8061Date { + /** + * Formats a date into an iso 8061 string. + */ + export function format(date: Date): string; + + /** + * Parses an ISO 8061 date string into a date object. + */ + export function parse(stringDateTime: string): Date; +} + +declare export class Logger { + level: string; + loggerFunction: (level: string, message: string) => void; + + static LogLevels: { + EMERGENCY: string; + ALERT: string; + CRITICAL: string; + ERROR: string; + WARNING: string; + NOTICE: string; + INFO: string; + DEBUG: string; + }; + static logPriority: string[]; + + log(level: string, message: string): void; + emergency(message: string): void; + alert(message: string): void; + critical(message: string): void; + error(message: string): void; + warning(message: string): void; + notice(message: string): void; + info(message: string): void; + debug(message: string): void; + + defaultLoggerFunction(level: string, message: string): void; +} + +declare export class ConnectionStringParser { + _value: string; + _pos: number; + _state: string; + + constructor(connectionString: string); + + _parse(options: ConnectionStringParseOptions): Dictionary; + + _extractKey(): string; + _extractString(quote: string): string; + _extractValue(): string; + + _skipWhitespaces(): void; + _skipOperator(operator: string): void; + + static parse(connectionString: string): Dictionary; +} + +declare export module ServiceSettings { + export var DEFAULT_PROTOCOL: string; + + export class NoMatchError implements Error { name: string; - instances: { - [instanceId: string]: RoleInstance; + message: string; + constr: any; + + constructor(); + constructor(message: string); + constructor(message: string, constr: any); + } + + /** + * Throws an exception if the connection string format does not match any of the + * available formats. + */ + export function noMatchConnectionString(connectionString: string): void; + + /** + * Throws an exception if the settings dont match any of the available formats. + */ + export function noMatchSettings(settings: any): void; + + /** + * Parses the connection string and then validate that the parsed keys belong to + * the validSettingKeys + */ + export function parseAndValidateKeys(connectionString: string, validKeys: string[]): string[]; + + /** + * Creates an anonymous function that acts as predicate to perform a validation. + */ + export function getValidator(requirements: Dictionary, isRequired: boolean, atLeastOne: boolean): ValidatorFunction; + + /** + * Creates a setting value condition that validates it is one of the passed valid values. + */ + export function setting(name: string): string[]; + + /** + * Creates an "at least one" predicate for the provided list of requirements. + */ + export function atLeastOne(...args: any[]): ValidatorFunction; + + /** + * Creates an optional predicate for the provided list of requirements. + */ + export function optional(...args: any[]): ValidatorFunction; + + /** + * Creates an required predicate for the provided list of requirements. + */ + export function allRequired(...args: any[]): ValidatorFunction; + + /** + * Creates a setting value condition using the passed predicate. + */ + export function settingWithFunc(name: string, predicate: Function): Requirement[]; + + /** + * Tests to see if a given list of settings matches a set of filters exactly. + */ + export function matchedSpecification(settings: Dictionary): boolean; + + /** + * Tests to see if a given list of settings matches a set of filters exactly. + */ + export function parseHost(uri: string): url.Url; +} + +declare export class StorageServiceSettings { + _name: string; + _key: string; + _blobEndpointUri: string; + _queueEndpointUri: string; + _tableEndpointUri: string; + _usePathStyleUri: boolean; + + constructor(name: string, key: string, blobEndpointUri: string, queueEndpointUri: string, tableEndpointUri: string, usePathStyleUri: boolean); + + /** + * Returns a StorageServiceSettings with development storage credentials using + * the specified proxy Uri. + */ + static _getDevelopmentStorageAccount(): StorageServiceSettings; + static _getDevelopmentStorageAccount(proxy: string): StorageServiceSettings; + + /** + * Gets a StorageServiceSettings object that references the development storage + * account. + */ + static getDevelopmentStorageAccountSettings(): StorageServiceSettings; + + /** + * Gets the default service endpoint using the specified protocol and account + * name. + */ + static _getDefaultServiceEndpoint(settings: Dictionary, dns: string): string; + + /** + * Creates StorageServiceSettings object given endpoints uri. + */ + static _createStorageServiceSettings(settings: Dictionary, blobEndpointUri: string, queueEndpointUri: string, tableEndpointUri: string): StorageServiceSettings; + + /** + * Creates a ServiceBusSettings object from a set of settings. + */ + static createFromSettings(settings: Dictionary): StorageServiceSettings; + + /** + * Creates a StorageServiceSettings object from the given connection string. + */ + static createFromConnectionString(connectionString: string): StorageServiceSettings; + + static createExplicitlyOrFromEnvironment(storageAccount: string, storageAccessKey: string, host: string): StorageServiceSettings; + + static isDevelopmentStorage(storageAccount: string, storageAccessKey: string, parsedHost: string): boolean; + + static createFromConfig(config: any): StorageServiceSettings; + + static customizeConfig(config: any): void; +} + +declare export class ServiceBusSettings { + +} + +declare export class ServiceManagementSettinsg { + +} + +declare export module Validate { + /** + * Checks if the given uri is valid or not. + */ + export function isValidUri(uri: string): boolean; + + /** + * Validates that a clusterCreationObject is properly formed. + */ + export function isValidHDInsightCreationObject(clusterCreationObject: ClusterCreationOptions): void; + export function isValidHDInsightCreationObject(clusterCreationObject: ClusterCreationOptions, callback: ErrorCallback): void; + + export function isValidUuid(uuid: string): void; + export function isValidUuid(uuid: string, callback: ErrorCallback): void; + + /** + * Creates a anonymous function that check if a given key is base 64 encoded. + */ + export function isBase64Encoded(key: string): boolean; + + /** + * Validates a function. + */ + export function isValidFunction(functionObject: any, functionName: string): void; + + /** + * Validates that a Service Bus namespace name + * is legally allowable. Does not check availability. + */ + export function namespaceNameIsValid(name: string): boolean; + export function namespaceNameIsValid(name: string, callback: ErrorCallback): boolean; + + /** + * Validates a container name. + */ + export function containerNameIsValid(containerName: string): boolean; + export function containerNameIsValid(containerName: string, callback: ErrorCallback): boolean; + + /** + * Validates a blob name. + */ + export function blobNameIsValid(containerName: string, blob: string): boolean; + export function blobNameIsValid(containerName: string, blob: string, callback: ErrorCallback): boolean; + + /** + * Validates a table name. + */ + export function tableNameIsValid(tableName: string): boolean; + export function tableNameIsValid(tableName: string, callback: ErrorCallback): boolean; + + /** + * Validates a queue name. + */ + export function queueNameIsValid(queueName: string): boolean; + export function queueNameIsValid(queueName: string, callback: ErrorCallback): boolean; + + export function pageRangesAreValid(rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number): boolean; + export function pageRangesAreValid(rangeStart: number, rangeEnd: number, writeBlockSizeInBytes: number, callback: ErrorCallback): boolean; + + export function validateArgs(functionName: string, validationRules: Function): boolean; +} + +declare export module date { + /** + * Generates a Date object which is in the given days from now. + */ + export function daysFromNow(days: number): Date; + + /** + * Generates a Date object which is in the given hours from now. + */ + export function hoursFromNow(hours: number): Date; + + /** + * Generates a Date object which is in the given minutes from now. + */ + export function minutesFromNow(minutes: number): Date; + + /** + * Generates a Date object which is in the given seconds from now. + */ + export function secondsFromNow(seconds: number): Date; +} +//#endregion + +//#region Non-explicit, undeclared interfaces +export interface WebResponse { + isSuccessful: boolean; + statusCode: number; + body: { + entry: { + id: string; + title: any; + updated: string; + author: { + name: any; + }; + link: any; + category: any; + content: any; }; - } - export interface RoleInstance { - id: string; - faultDomain: string; - updateDomain: string; - endpoints: { - [endpoint: string]: RoleInstanceEndpoint + }; + headers: any; + md5: any; +} + +//#region Common Interfaces +export interface SimpleCallback { + (error: Error, result: T): void; +} +export interface ErrorCallback { + (error: Error): void; +} +export interface StorageCallbackVoid { + (err: Error, response: WebResponse): void; +} +export interface StorageCallback { + (err: Error, result: T, response: WebResponse): void; +} +export interface StorageServiceStatsCallback extends StorageCallback { } +export interface StorageServicePropertiesCallback extends StorageCallback { } + +export interface TimeoutIntervalOptions { + locationMode?: string; + timeoutIntervalInMs?: number; + maximumExecutionTimeInMs?: number; +} +export interface MetadataOptions extends TimeoutIntervalOptions { + metadata?: StorageMetadata; +} +export interface StorageAclOptions extends TimeoutIntervalOptions { + leaseId?: string; + signedIdentifiers: SignedIdentifier[] +} + +export interface Dictionary { + [key: string]: T; +} +export interface StorageServiceProperties { + Logging: { + Version: number; + Delete: boolean; + Read: boolean; + Write: boolean; + RetentionPolicy: { + Enabled: boolean; + Days: number; }; + }; + Metrics: { + Version: number; + Enabled: boolean; + IncludeAPIs: boolean; + RetentionPolicy: { + Enabled: boolean; + Days: number; + }; + }; + DefaultServiceVersion: string; +} +export interface StorageServiceStats { + GeoReplication: { + Status: string; + LastSyncTime: Date; } - export interface RoleInstanceEndpoint { - protocol: string; - address: string; - port: number; +} +export interface SignedIdentifier { + Id: string; + AccessPolicy: SharedAccessPolicy; +} +export interface StorageMetadata { + [key: string]: string; +} +export interface ContinuationToken { + nextMarker: string; + targetLocation: string; +} +export interface SharedAccessPolicy { + Id?: string; + AccessPolicy: { + Start?: Date; + Expiry: Date; + Permission?: string; } - export interface RoleLocalResource { +} +//#endregion +//#region TableService Interfaces +export interface TableRequestCallback { + (error: Error, tableResult: { TableName: string; }, response: WebResponse): void; +} + +export interface CreateTableIfNotExistsCallback { + (error: Error, created: boolean, response: WebResponse): void; +} + +export interface DeleteTableCallback { + (error: Error, successful: boolean, response: WebResponse): void; +} + +export interface QueryTablesCallback { + (error: Error, queryTablesResult: TableResult[], resultsContinuation: QueryResultContinuation, response: WebResponse): void; +} + +export interface QueryResultContinuation { + tableService: TableService; +} + +export interface QueryTablesOptions extends TimeoutIntervalOptions { + nextTableName?: string; +} + +export interface TableResult { + TableName: string; +} + +export interface QueryEntityCallback { + (error: Error, entity: Entity, response: WebResponse): void; +} + +export interface QueryEntitiesCallback { + (error: Error, entities: Entity[], resultContinuation: QueryEntitiesResultContinuation, response: WebResponse): void; +} + +export interface QueryEntitiesResultContinuation extends QueryResultContinuation { + tableQuery: TableQuery; + nextPartitionKey: string; + nextRowKey: string; + getNextPage(callback?: QueryEntitiesCallback): void; + hasNextPage(): boolean; +} + +export interface ModifyEntityCallback { + (error: Error, entity: Entity, response: WebResponse): void; +} + +export interface DeleteEntityCallback { + (error: Error, successful: boolean, response: WebResponse): void; +} + +export interface UpdateEntityOptions extends TimeoutIntervalOptions { + checkEtag?: boolean; +} + +export interface Entity { + PartitionKey: string; + RowKey: string; + Timestamp?: Date; + etag?: string; + [property: string]: string | number | boolean | Date; +} +//#endregion +//#region BlobService Interfaces +export interface LeaseIdOptions extends TimeoutIntervalOptions { + leaseId?: string; +} +export interface AccessConditionsOptions extends TimeoutIntervalOptions { + accessConditions?: StorageAccessCondition; +} +export interface LeaseAccessConditionsOptions extends LeaseIdOptions { + accessConditions?: StorageAccessCondition; +} + +export interface ListContainersOptions extends TimeoutIntervalOptions { + prefix?: string; + maxresults?: number; + marker: string; + include?: string; +} +export interface ListContainersCallback { + (err: Error, containers: ContainerResult[], continuationToken: ContinuationToken, response: WebResponse): void; +} +export interface CreateContainerOptions extends TimeoutIntervalOptions { + metadata?: StorageMetadata; + publicAccessLevel?: string; +} +export interface GetContainerPropertiesOptions extends TimeoutIntervalOptions { + leaseId?: string; +} +export interface GetContainerMetadataOptions extends GetContainerPropertiesOptions { + accessConditions?: StorageAccessCondition; +} + +export interface ListBlobsOptions extends ListContainersOptions { + prefix?: string; + delimiter?: string; +} +export interface ListBlobsCallback { + (err: Error, blobs: BlobResult[], continuationToken: ContinuationToken, response: WebResponse): void; +} +export interface GetBlobPropertiesOptions extends LeaseAccessConditionsOptions { + snapshotId?: string; +} +export interface SetBlobPropertiesOptions extends LeaseAccessConditionsOptions { + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentMD5?: string; + cacheControl?: string; + contentDisposition?: string; +} +export interface ReadBlobOptions extends GetBlobPropertiesOptions { + rangeStart?: string; + rangeEnd?: string; + useTransactionalMD5?: boolean; + disableContentMD5Validation?: boolean; +} +export interface GetBlobToTextCallback { + (err: Error, text: string, result: BlobResult, response: WebResponse): void; +} +export interface DeleteBlobOptions extends GetBlobPropertiesOptions { + deleteSnapshots?: string; +} +export interface BlobSnapshotOptions extends GetBlobPropertiesOptions { + metadata?: StorageMetadata; +} +export interface CopyBlobOptions extends BlobSnapshotOptions { + sourceLeaseId?: string; + sourceAccessConditions: StorageAccessCondition; +} + +export interface UploadBlobOptions extends SetBlobPropertiesOptions { + metadata?: StorageMetadata; + speedSummary?: SpeedSummary; + parallelOperationThreadCount?: number; + storeBlobContentMD5?: boolean; + useTransactionalMD5?: boolean; +} +export interface CreatePagesOptions extends LeaseAccessConditionsOptions { + contentMD5?: string; + useTransactionalMD5?: boolean; +} +export interface PageRangeOptions extends LeaseIdOptions { + snapshotId?: string; + rangeStart?: number; + rangeEnd?: number; +} + +export interface UploadBlockBlobOptions extends UploadBlobOptions { + blockIdPrefix?: string; +} +export interface CreateBlockOptions extends LeaseAccessConditionsOptions { + contentMD5?: string; + useTransactionalMD5?: boolean; +} + +export interface LeaseOptions extends AccessConditionsOptions { + leaseDuration?: string; + proposedLeaseId?: string; +} +export interface BreakLeaseOptions extends AccessConditionsOptions { + leaseBreakPeriod?: number; +} + +export interface SharedAccessSignatureResult { + baseUrl: string; + path: string; + queryString: { + se: string; + sp: string; + sr: string; + sv: string; + sig: string; + }; + url: () => string; +} +export interface BlobHeaders { + cacheControl?: string; + contentType?: string; + contentEncoding?: string; + contentLanguage?: string; + contentDisposition?: string; +} +export interface PageRange { + start: number; + end: number; +} +export interface BlockList { + LatestBlocks: string[]; + CommittedBlocks: string[]; + UncommittedBlocks: string[]; +} +export interface StorageAccessCondition { + "If-Modified-Since": Date; + "If-Unmodified-Since": Date; + "If-Match": string; + "If-None-Match": string; +} +//#endregion +//#region QueueService Interfaces +export interface ListQueuesOptions extends TimeoutIntervalOptions { + prefix?: string; + maxresults?: number; + marker: string; + include?: string; +} +export interface ListQueuesCallback { + (err: Error, queues: QueueResult[], continuationToken: ContinuationToken, response: WebResponse): void; +} + +export interface CreateQueueMessageOptions extends TimeoutIntervalOptions { + messagettl?: number; + visibilitytimeout?: number; +} +export interface PeekQueueMessagesOptions extends TimeoutIntervalOptions { + numofmessages?: number; +} +export interface GetQueueMessagesOptions extends PeekQueueMessagesOptions { + peekonly?: boolean; + visibilitytimeout?: number; +} +export interface UpdateQueueMessagesOptions extends TimeoutIntervalOptions { + messagetext?: string; +} +//#endregion + +//#region RoleEnvironment Interfaces +export interface Role { + name: string; + instances: { + [instanceId: string]: RoleInstance; + }; +} +export interface RoleInstance { + id: string; + faultDomain: string; + updateDomain: string; + endpoints: { + [endpoint: string]: RoleInstanceEndpoint + }; +} +export interface RoleInstanceEndpoint { + protocol: string; + address: string; + port: number; +} +export interface RoleLocalResource { + name: string; + path: string; + maximumSizeInMegabytes: number; +} +//#endregion +//#region ConnectionStringParser Interfaces +export interface ConnectionStringParseOptions { + skipLowerCase: boolean; +} +//#endregion +//#region Validate Interfaces +export interface ClusterCreationOptions { + name: string; + location: string; + defaultStorageAccountName: string; + defaultStorageAccountKey: string; + defaultStorageContainer: string; + user: string; + password: string; + nodes: number; + additionalStorageAccounts?: { name: string; - path: string; - maximumSizeInMegabytes: number; - } - //#endregion - //#region ConnectionStringParser Interfaces - export interface ConnectionStringParseOptions { - skipLowerCase: boolean; - } - //#endregion - //#region Validate Interfaces - export interface ClusterCreationOptions { - name: string; - location: string; - defaultStorageAccountName: string; - defaultStorageAccountKey: string; - defaultStorageContainer: string; + key: string; + }[]; + oozieMetastore?: { + server: string; + database: string; user: string; password: string; - nodes: number; - additionalStorageAccounts?: { - name: string; - key: string; - }[]; - oozieMetastore?: { - server: string; - database: string; - user: string; - password: string; - }; - hiveMetastore?: { - server: string; - database: string; - user: string; - password: string; - }; - } - //#endregion - //#region ServiceSettings Interfaces - export interface Requirement { - SettingName: string; - SettingPredicate: Function; - } - export interface ValidatorFunction { - (userSettings: Dictionary): any; - } - //#endregion - //#endregion - - //#region Un-exported internal classes - class StorageServiceClient extends ServiceClient { - static incorrectStorageAccountErr: string; - static incorrectStorageAccessKeyErr: string; - static getStorageSettings(connectionString: string): StorageServiceSettings; - static getStorageSettings(storageAccount?: string, storageAccessKey?: string, host?: string): StorageServiceSettings; - - apiVersion: string; - usePathStyleUri: string; - - constructor(storageAccount: string, storageAccessKey: string, host: string, usePathStyleUri: boolean, authenticationProvider: any); - } - //#endregion - - export function isEmulated(): boolean; + }; + hiveMetastore?: { + server: string; + database: string; + user: string; + password: string; + }; } +//#endregion +//#region ServiceSettings Interfaces +export interface Requirement { + SettingName: string; + SettingPredicate: Function; +} +export interface ValidatorFunction { + (userSettings: Dictionary): any; +} +//#endregion +//#endregion + +//#region Un-exported internal classes +declare class StorageServiceClient extends ServiceClient { + static incorrectStorageAccountErr: string; + static incorrectStorageAccessKeyErr: string; + static getStorageSettings(connectionString: string): StorageServiceSettings; + static getStorageSettings(storageAccount?: string, storageAccessKey?: string, host?: string): StorageServiceSettings; + + apiVersion: string; + usePathStyleUri: string; + + constructor(storageAccount: string, storageAccessKey: string, host: string, usePathStyleUri: boolean, authenticationProvider: any); +} +//#endregion + +declare export function isEmulated(): boolean; diff --git a/barcode/barcode.d.ts b/barcode/barcode.d.ts index c2ad43eb76..3afdf81b2b 100644 --- a/barcode/barcode.d.ts +++ b/barcode/barcode.d.ts @@ -5,21 +5,20 @@ /// -declare module "barcode" { - interface BarcodeOptions { - data:string|number; - width:number; - height:number; - } - interface BarcodeResult { - getStream(callback:(err:NodeJS.ErrnoException, stream:NodeJS.ReadableStream) => void):void; - saveImage(outputfilePath:string, callback:(err:NodeJS.ErrnoException) => void):void; - getBase64(callback:(err:NodeJS.ErrnoException, base64String:string) => void):void; - } - - function barcode(type:string, options:BarcodeOptions):BarcodeResult; - - export = barcode; +interface BarcodeOptions { + data: string | number; + width: number; + height: number; } + +interface BarcodeResult { + getStream(callback: (err: NodeJS.ErrnoException, stream: NodeJS.ReadableStream) => void): void; + saveImage(outputfilePath: string, callback: (err: NodeJS.ErrnoException) => void): void; + getBase64(callback: (err: NodeJS.ErrnoException, base64String: string) => void): void; +} + +declare function barcode(type: string, options: BarcodeOptions): BarcodeResult; + +export = barcode; diff --git a/basic-auth/basic-auth.d.ts b/basic-auth/basic-auth.d.ts index 911299a6c6..08cbcd1975 100644 --- a/basic-auth/basic-auth.d.ts +++ b/basic-auth/basic-auth.d.ts @@ -5,15 +5,14 @@ /// -declare module "basic-auth" { - function auth(req: Express.Request): auth.BasicAuthResult; - namespace auth { - interface BasicAuthResult { - name: string; - pass: string; - } +declare function auth(req: Express.Request): auth.BasicAuthResult; + +declare namespace auth { + interface BasicAuthResult { + name: string; + pass: string; } - - export = auth; } + +export = auth; diff --git a/batch-stream/batch-stream.d.ts b/batch-stream/batch-stream.d.ts index 5b27050104..30a27f3199 100644 --- a/batch-stream/batch-stream.d.ts +++ b/batch-stream/batch-stream.d.ts @@ -5,20 +5,19 @@ /// -declare module "batch-stream" { - import stream = require('stream'); - interface Options { +import stream = require('stream'); + +interface Options { size?: number; highWaterMark?: number; - } +} - class BatchStream extends stream.Transform { +declare class BatchStream extends stream.Transform { size: number; batch: any[]; constructor(options: Options); - } +} - export = BatchStream; -} \ No newline at end of file +export = BatchStream; diff --git a/bcrypt-nodejs/bcrypt-nodejs.d.ts b/bcrypt-nodejs/bcrypt-nodejs.d.ts index 6df662346a..982efaa60c 100644 --- a/bcrypt-nodejs/bcrypt-nodejs.d.ts +++ b/bcrypt-nodejs/bcrypt-nodejs.d.ts @@ -3,66 +3,65 @@ // Definitions by: David Broder-Rodgers // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "bcrypt-nodejs" { - /** - * Generate a salt synchronously - * @param rounds Number of rounds to process the data for (default - 10) - * @return Generated salt - */ - export function genSaltSync(rounds?: number): string; - /** - * Generate a salt asynchronously - * @param rounds Number of rounds to process the data for (default - 10) - * @param callback Callback with error and resulting salt, to be fired once the salt has been generated - */ - export function genSalt(rounds: number, callback: (error: Error, result: string) => void): void; +/** + * Generate a salt synchronously + * @param rounds Number of rounds to process the data for (default - 10) + * @return Generated salt + */ +declare export function genSaltSync(rounds?: number): string; - /** - * Generate a hash synchronously - * @param data Data to be encrypted - * @param salt Salt to be used in encryption (default - new salt generated with 10 rounds) - * @return Generated hash - */ - export function hashSync(data: string, salt?: string): string; +/** + * Generate a salt asynchronously + * @param rounds Number of rounds to process the data for (default - 10) + * @param callback Callback with error and resulting salt, to be fired once the salt has been generated + */ +declare export function genSalt(rounds: number, callback: (error: Error, result: string) => void): void; - /** - * Generate a hash asynchronously - * @param data Data to be encrypted - * @param salt Salt to be used in encryption - * @param callback Callback with error and hashed result, to be fired once the data has been encrypted - */ - export function hash(data: string, salt: string, callback: (error: Error, result: string) => void): void; +/** + * Generate a hash synchronously + * @param data Data to be encrypted + * @param salt Salt to be used in encryption (default - new salt generated with 10 rounds) + * @return Generated hash + */ +declare export function hashSync(data: string, salt?: string): string; - /** - * Generate a hash asynchronously - * @param data Data to be encrypted - * @param salt Salt to be used in encryption - * @param progressCallback Callback to be fired multiple times during the hash calculation to signify progress - * @param callback Callback with error and hashed result, to be fired once the data has been encrypted - */ - export function hash(data: string, salt: string, progressCallback: () => void, callback: (error: Error, result: string) => void): void; +/** + * Generate a hash asynchronously + * @param data Data to be encrypted + * @param salt Salt to be used in encryption + * @param callback Callback with error and hashed result, to be fired once the data has been encrypted + */ +declare export function hash(data: string, salt: string, callback: (error: Error, result: string) => void): void; - /** - * Compares data with a hash synchronously - * @param data Data to be compared - * @param hash Hash to be compared to - * @return true if matching, false otherwise - */ - export function compareSync(data: string, hash: string): boolean; +/** + * Generate a hash asynchronously + * @param data Data to be encrypted + * @param salt Salt to be used in encryption + * @param progressCallback Callback to be fired multiple times during the hash calculation to signify progress + * @param callback Callback with error and hashed result, to be fired once the data has been encrypted + */ +declare export function hash(data: string, salt: string, progressCallback: () => void, callback: (error: Error, result: string) => void): void; - /** - * Compares data with a hash asynchronously - * @param data Data to be compared - * @param hash Hash to be compared to - * @param callback Callback with error and match result, to be fired once the data has been compared - */ - export function compare(data: string, hash: string, callback: (error: Error, result: boolean) => void): void; +/** + * Compares data with a hash synchronously + * @param data Data to be compared + * @param hash Hash to be compared to + * @return true if matching, false otherwise + */ +declare export function compareSync(data: string, hash: string): boolean; - /** - * Get number of rounds used for hash - * @param hash Hash from which the number of rounds used should be extracted - * @return number of rounds used to encrypt a given hash - */ - export function getRounds(hash: string): number; -} +/** + * Compares data with a hash asynchronously + * @param data Data to be compared + * @param hash Hash to be compared to + * @param callback Callback with error and match result, to be fired once the data has been compared + */ +declare export function compare(data: string, hash: string, callback: (error: Error, result: boolean) => void): void; + +/** + * Get number of rounds used for hash + * @param hash Hash from which the number of rounds used should be extracted + * @return number of rounds used to encrypt a given hash + */ +declare export function getRounds(hash: string): number; diff --git a/bcrypt/bcrypt.d.ts b/bcrypt/bcrypt.d.ts index 38d9604b44..304214cc5d 100644 --- a/bcrypt/bcrypt.d.ts +++ b/bcrypt/bcrypt.d.ts @@ -3,63 +3,62 @@ // Definitions by: Peter Harris // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "bcrypt" { - /** - * @param rounds The cost of processing the data. Default 10. - */ - export function genSaltSync(rounds?: number): string; - /** - * @param rounds The cost of processing the data. Default 10. - * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. - */ - export function genSalt(rounds: number, callback: (err: Error, salt: string) => void): void; - /** - * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. - */ - export function genSalt(callback: (err: Error, salt: string) => void): void; +/** + * @param rounds The cost of processing the data. Default 10. + */ +declare export function genSaltSync(rounds?: number): string; - /** - * @param data The data to be encrypted. - * @param salt The salt to be used in encryption. - */ - export function hashSync(data: any, salt: string): string; - /** - * @param data The data to be encrypted. - * @param rounds A salt will be generated using the rounds specified. - */ - export function hashSync(data: any, rounds: number): string; +/** + * @param rounds The cost of processing the data. Default 10. + * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. + */ +declare export function genSalt(rounds: number, callback: (err: Error, salt: string) => void): void; +/** + * @param callback A callback to be fire once the sald has been generated. Uses eio making it asynchronous. + */ +declare export function genSalt(callback: (err: Error, salt: string) => void): void; - /** - * @param data The data to be encrypted. - * @param salt The salt to be used in encryption. - * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. - */ - export function hash(data: any, salt: string, callback: (err: Error, encrypted: string) => void): void; - /** - * @param data The data to be encrypted. - * @param rounds A salt will be generated using the rounds specified. - * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. - */ - export function hash(data: any, rounds: number, callback: (err: Error, encrypted: string) => void): void; +/** + * @param data The data to be encrypted. + * @param salt The salt to be used in encryption. + */ +declare export function hashSync(data: any, salt: string): string; +/** + * @param data The data to be encrypted. + * @param rounds A salt will be generated using the rounds specified. + */ +declare export function hashSync(data: any, rounds: number): string; - /** - * @param data The data to be encrypted. - * @param encrypted The data to be compared against. - */ - export function compareSync(data: any, encrypted: string): boolean; +/** + * @param data The data to be encrypted. + * @param salt The salt to be used in encryption. + * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. + */ +declare export function hash(data: any, salt: string, callback: (err: Error, encrypted: string) => void): void; +/** + * @param data The data to be encrypted. + * @param rounds A salt will be generated using the rounds specified. + * @param callback A callback to be fired once the data has been encrypted. Uses eio making it asynchronous. + */ +declare export function hash(data: any, rounds: number, callback: (err: Error, encrypted: string) => void): void; - /** - * @param data The data to be encrypted. - * @param encrypted The data to be compared against. - * @param callback A callback to be fire once the data has been compared. Uses eio making it asynchronous. - */ - export function compare(data: any, encrypted: string, callback: (err: Error, same: boolean) => void): void; +/** + * @param data The data to be encrypted. + * @param encrypted The data to be compared against. + */ +declare export function compareSync(data: any, encrypted: string): boolean; - /** - * Return the number of rounds used to encrypt a given hash - * - * @param encrypted Hash from which the number of rounds used should be extracted. - */ - export function getRounds(encrypted: string): number; -} +/** + * @param data The data to be encrypted. + * @param encrypted The data to be compared against. + * @param callback A callback to be fire once the data has been compared. Uses eio making it asynchronous. + */ +declare export function compare(data: any, encrypted: string, callback: (err: Error, same: boolean) => void): void; + +/** + * Return the number of rounds used to encrypt a given hash + * + * @param encrypted Hash from which the number of rounds used should be extracted. + */ +declare export function getRounds(encrypted: string): number; diff --git a/bcryptjs/bcryptjs.d.ts b/bcryptjs/bcryptjs.d.ts index 3d3128d022..896d1c5961 100644 --- a/bcryptjs/bcryptjs.d.ts +++ b/bcryptjs/bcryptjs.d.ts @@ -3,80 +3,79 @@ // Definitions by: Joshua Filby // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "bcryptjs" { - /** - * Sets the pseudo random number generator to use as a fallback if neither node's crypto module nor the Web Crypto API is available. - * Please note: It is highly important that the PRNG used is cryptographically secure and that it is seeded properly! - * @param random Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values. - */ - export function setRandomFallback(random: (random: number) => number[]): void; - /** - * Synchronously generates a salt. - * @param rounds Number of rounds to use, defaults to 10 if omitted - * @return Resulting salt - */ - export function genSaltSync(rounds?: number): string; +/** + * Sets the pseudo random number generator to use as a fallback if neither node's crypto module nor the Web Crypto API is available. + * Please note: It is highly important that the PRNG used is cryptographically secure and that it is seeded properly! + * @param random Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values. + */ +declare export function setRandomFallback(random: (random: number) => number[]): void; - /** - * Asynchronously generates a salt. - * @param callback Callback receiving the error, if any, and the resulting salt - */ - export function genSalt(callback: (err: Error, salt: string) => void): void; +/** + * Synchronously generates a salt. + * @param rounds Number of rounds to use, defaults to 10 if omitted + * @return Resulting salt + */ +declare export function genSaltSync(rounds?: number): string; - /** - * Asynchronously generates a salt. - * @param rounds Number of rounds to use, defaults to 10 if omitted - * @param callback Callback receiving the error, if any, and the resulting salt - */ - export function genSalt(rounds: number, callback: (err: Error, salt: string) => void): void; +/** + * Asynchronously generates a salt. + * @param callback Callback receiving the error, if any, and the resulting salt + */ +declare export function genSalt(callback: (err: Error, salt: string) => void): void; - /** - * Synchronously generates a hash for the given string. - * @param s String to hash - * @param salt Salt length to generate or salt to use, default to 10 - * @return Resulting hash - */ - export function hashSync(s: string, salt?: number | string): string; +/** + * Asynchronously generates a salt. + * @param rounds Number of rounds to use, defaults to 10 if omitted + * @param callback Callback receiving the error, if any, and the resulting salt + */ +declare export function genSalt(rounds: number, callback: (err: Error, salt: string) => void): void; - /** - * Asynchronously generates a hash for the given string. - * @param s String to hash - * @param salt Salt length to generate or salt to use - * @param callback Callback receiving the error, if any, and the resulting hash - * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms. - */ - export function hash(s: string, salt: number | string, callback: (err: Error, hash: string) => void, progressCallback?: (percent: number) => void): void; +/** + * Synchronously generates a hash for the given string. + * @param s String to hash + * @param salt Salt length to generate or salt to use, default to 10 + * @return Resulting hash + */ +declare export function hashSync(s: string, salt?: number | string): string; - /** - * Synchronously tests a string against a hash. - * @param s String to compare - * @param hash Hash to test against - * @return true if matching, otherwise false - */ - export function compareSync(s: string, hash: string): boolean; +/** + * Asynchronously generates a hash for the given string. + * @param s String to hash + * @param salt Salt length to generate or salt to use + * @param callback Callback receiving the error, if any, and the resulting hash + * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms. + */ +declare export function hash(s: string, salt: number | string, callback: (err: Error, hash: string) => void, progressCallback?: (percent: number) => void): void; - /** - * Asynchronously compares the given data against the given hash. - * @param s Data to compare - * @param hash Data to be compared to - * @param callback Callback receiving the error, if any, otherwise the result - * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms. - */ - export function compare(s: string, hash: string, callback: (err: Error, success: boolean) => void, progressCallback?: (percent: number) => void): void; +/** + * Synchronously tests a string against a hash. + * @param s String to compare + * @param hash Hash to test against + * @return true if matching, otherwise false + */ +declare export function compareSync(s: string, hash: string): boolean; - /** - * Gets the number of rounds used to encrypt the specified hash. - * @param hash Hash to extract the used number of rounds from - * @return Number of rounds used - */ - export function getRounds(hash: string): number; +/** + * Asynchronously compares the given data against the given hash. + * @param s Data to compare + * @param hash Data to be compared to + * @param callback Callback receiving the error, if any, otherwise the result + * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms. + */ +declare export function compare(s: string, hash: string, callback: (err: Error, success: boolean) => void, progressCallback?: (percent: number) => void): void; - /** - * Gets the salt portion from a hash. Does not validate the hash. - * @param hash Hash to extract the salt from - * @return Extracted salt part - */ - export function getSalt(hash: string): string; -} +/** + * Gets the number of rounds used to encrypt the specified hash. + * @param hash Hash to extract the used number of rounds from + * @return Number of rounds used + */ +declare export function getRounds(hash: string): number; + +/** + * Gets the salt portion from a hash. Does not validate the hash. + * @param hash Hash to extract the salt from + * @return Extracted salt part + */ +declare export function getSalt(hash: string): string; diff --git a/benchmark/benchmark.d.ts b/benchmark/benchmark.d.ts index c5c257aaaa..01bb379a48 100644 --- a/benchmark/benchmark.d.ts +++ b/benchmark/benchmark.d.ts @@ -3,190 +3,189 @@ // Definitions by: Asana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "benchmark" { - class Benchmark { - static deepClone(value: T): T; - static each(obj: Object | any[], callback: Function, thisArg?: any): void; - static extend(destination: Object, ...sources: Object[]): Object; - static filter(arr: T[], callback: (value: T) => any, thisArg?: any): T[]; - static filter(arr: T[], filter: string, thisArg?: any): T[]; - static forEach(arr: T[], callback: (value: T) => any, thisArg?: any): void; - static formatNumber(num: number): string; - static forOwn(obj: Object, callback: Function, thisArg?: any): void; - static hasKey(obj: Object, key: string): boolean; - static indexOf(arr: T[], value: T, fromIndex?: number): number; - static interpolate(template: string, values: Object): string; - static invoke(benches: Benchmark[], name: string | Object, ...args: any[]): any[]; - static join(obj: Object, separator1?: string, separator2?: string): string; - static map(arr: T[], callback: (value: T) => K, thisArg?: any): K[]; - static pluck(arr: T[], key: string): K[]; - static reduce(arr: T[], callback: (accumulator: K, value: T) => K, thisArg?: any): K; - static options: Benchmark.Options; - static platform: Benchmark.Platform; - static support: Benchmark.Support; - static version: string; +declare class Benchmark { + static deepClone(value: T): T; + static each(obj: Object | any[], callback: Function, thisArg?: any): void; + static extend(destination: Object, ...sources: Object[]): Object; + static filter(arr: T[], callback: (value: T) => any, thisArg?: any): T[]; + static filter(arr: T[], filter: string, thisArg?: any): T[]; + static forEach(arr: T[], callback: (value: T) => any, thisArg?: any): void; + static formatNumber(num: number): string; + static forOwn(obj: Object, callback: Function, thisArg?: any): void; + static hasKey(obj: Object, key: string): boolean; + static indexOf(arr: T[], value: T, fromIndex?: number): number; + static interpolate(template: string, values: Object): string; + static invoke(benches: Benchmark[], name: string | Object, ...args: any[]): any[]; + static join(obj: Object, separator1?: string, separator2?: string): string; + static map(arr: T[], callback: (value: T) => K, thisArg?: any): K[]; + static pluck(arr: T[], key: string): K[]; + static reduce(arr: T[], callback: (accumulator: K, value: T) => K, thisArg?: any): K; - constructor(fn: Function | string, options?: Benchmark.Options); - constructor(name: string, fn: Function | string, options?: Benchmark.Options); - constructor(name: string, options?: Benchmark.Options); - constructor(options: Benchmark.Options); + static options: Benchmark.Options; + static platform: Benchmark.Platform; + static support: Benchmark.Support; + static version: string; - aborted: boolean; - compiled: Function | string; - count: number; - cycles: number; - error: Error; - fn: Function | string; - hz: number; - running: boolean; - setup: Function | string; - teardown: Function | string; + constructor(fn: Function | string, options?: Benchmark.Options); + constructor(name: string, fn: Function | string, options?: Benchmark.Options); + constructor(name: string, options?: Benchmark.Options); + constructor(options: Benchmark.Options); - stats: Benchmark.Stats; - times: Benchmark.Times; + aborted: boolean; + compiled: Function | string; + count: number; + cycles: number; + error: Error; + fn: Function | string; + hz: number; + running: boolean; + setup: Function | string; + teardown: Function | string; - abort(): Benchmark; - clone(options: Benchmark.Options): Benchmark; - compare(benchmark: Benchmark): number; - emit(type: string | Object): any; - listeners(type: string): Function[]; - off(type?: string, listener?: Function): Benchmark; - off(types: string[]): Benchmark; - on(type?: string, listener?: Function): Benchmark; - on(types: string[]): Benchmark; - reset(): Benchmark; - run(options?: Benchmark.Options): Benchmark; + stats: Benchmark.Stats; + times: Benchmark.Times; + + abort(): Benchmark; + clone(options: Benchmark.Options): Benchmark; + compare(benchmark: Benchmark): number; + emit(type: string | Object): any; + listeners(type: string): Function[]; + off(type?: string, listener?: Function): Benchmark; + off(types: string[]): Benchmark; + on(type?: string, listener?: Function): Benchmark; + on(types: string[]): Benchmark; + reset(): Benchmark; + run(options?: Benchmark.Options): Benchmark; + toString(): string; +} + +declare namespace Benchmark { + export interface Options { + async?: boolean; + defer?: boolean; + delay?: number; + id?: string; + initCount?: number; + maxTime?: number; + minSamples?: number; + minTime?: number; + name?: string; + onAbort?: Function; + onComplete?: Function; + onCycle?: Function; + onError?: Function; + onReset?: Function; + onStart?: Function; + setup?: Function | string; + teardown?: Function | string; + fn?: Function | string; + queued?: boolean; + } + + export interface Platform { + description: string; + layout: string; + manufacturer: string; + name: string; + os: string; + prerelease: string; + product: string; + version: string; toString(): string; } - namespace Benchmark { - export interface Options { - async?: boolean; - defer?: boolean; - delay?: number; - id?: string; - initCount?: number; - maxTime?: number; - minSamples?: number; - minTime?: number; - name?: string; - onAbort?: Function; - onComplete?: Function; - onCycle?: Function; - onError?: Function; - onReset?: Function; - onStart?: Function; - setup?: Function | string; - teardown?: Function | string; - fn?: Function | string; - queued?: boolean; - } - - export interface Platform { - description: string; - layout: string; - manufacturer: string; - name: string; - os: string; - prerelease: string; - product: string; - version: string; - toString(): string; - } - - export interface Support { - air: boolean; - argumentsClass: boolean; - browser: boolean; - charByIndex: boolean; - charByOwnIndex: boolean; - decompilation: boolean; - descriptors: boolean; - getAllKeys: boolean; - iteratesOwnFirst: boolean; - java: boolean; - nodeClass: boolean; - timeout: boolean; - } - - export interface Stats { - deviation: number; - mean: number; - moe: number; - rme: number; - sample: any[]; - sem: number; - variance: number; - } - - export interface Times { - cycle: number; - elapsed: number; - period: number; - timeStamp: number; - } - - export class Deferred { - constructor(clone: Benchmark); - - benchmark: Benchmark; - cycles: number; - elapsed: number; - timeStamp: number; - } - - export class Event { - constructor(type: string | Object); - - aborted: boolean; - cancelled: boolean; - currentTarget: Object; - result: any; - target: Object; - timeStamp: number; - type: string; - } - - export class Suite { - static options: { name: string }; - - constructor(name?: string, options?: Options); - - aborted: boolean; - length: number; - running: boolean; - abort(): Suite; - add(name: string, fn: Function | string, options?: Options): Suite; - add(fn: Function | string, options?: Options): Suite; - add(name: string, options?: Options): Suite; - add(options: Options): Suite; - clone(options: Options): Suite; - emit(type: string | Object): any; - filter(callback: Function | string): Suite; - forEach(callback: Function): Suite; - indexOf(value: any): number; - invoke(name: string, ...args: any[]): any[]; - join(separator?: string): string; - listeners(type: string): Function[]; - map(callback: Function): any[]; - off(type?: string, callback?: Function): Benchmark; - off(types: string[]): Benchmark; - on(type?: string, callback?: Function): Benchmark; - on(types: string[]): Benchmark; - pluck(property: string): any[]; - pop(): Function; - push(benchmark: Benchmark): number; - reduce(callback: Function, accumulator: T): T; - reset(): Suite; - reverse(): any[]; - run(options?: Options): Suite; - shift(): Benchmark; - slice(start: number, end: number): any[]; - slice(start: number, deleteCount: number, ...values: any[]): any[]; - unshift(benchmark: Benchmark): number; - } + export interface Support { + air: boolean; + argumentsClass: boolean; + browser: boolean; + charByIndex: boolean; + charByOwnIndex: boolean; + decompilation: boolean; + descriptors: boolean; + getAllKeys: boolean; + iteratesOwnFirst: boolean; + java: boolean; + nodeClass: boolean; + timeout: boolean; } - export = Benchmark; + export interface Stats { + deviation: number; + mean: number; + moe: number; + rme: number; + sample: any[]; + sem: number; + variance: number; + } + + export interface Times { + cycle: number; + elapsed: number; + period: number; + timeStamp: number; + } + + export class Deferred { + constructor(clone: Benchmark); + + benchmark: Benchmark; + cycles: number; + elapsed: number; + timeStamp: number; + } + + export class Event { + constructor(type: string | Object); + + aborted: boolean; + cancelled: boolean; + currentTarget: Object; + result: any; + target: Object; + timeStamp: number; + type: string; + } + + export class Suite { + static options: { name: string }; + + constructor(name?: string, options?: Options); + + aborted: boolean; + length: number; + running: boolean; + abort(): Suite; + add(name: string, fn: Function | string, options?: Options): Suite; + add(fn: Function | string, options?: Options): Suite; + add(name: string, options?: Options): Suite; + add(options: Options): Suite; + clone(options: Options): Suite; + emit(type: string | Object): any; + filter(callback: Function | string): Suite; + forEach(callback: Function): Suite; + indexOf(value: any): number; + invoke(name: string, ...args: any[]): any[]; + join(separator?: string): string; + listeners(type: string): Function[]; + map(callback: Function): any[]; + off(type?: string, callback?: Function): Benchmark; + off(types: string[]): Benchmark; + on(type?: string, callback?: Function): Benchmark; + on(types: string[]): Benchmark; + pluck(property: string): any[]; + pop(): Function; + push(benchmark: Benchmark): number; + reduce(callback: Function, accumulator: T): T; + reset(): Suite; + reverse(): any[]; + run(options?: Options): Suite; + shift(): Benchmark; + slice(start: number, end: number): any[]; + slice(start: number, deleteCount: number, ...values: any[]): any[]; + unshift(benchmark: Benchmark): number; + } } + +export = Benchmark; diff --git a/bitwise-xor/bitwise-xor.d.ts b/bitwise-xor/bitwise-xor.d.ts index 09f104b9af..ef3271e981 100644 --- a/bitwise-xor/bitwise-xor.d.ts +++ b/bitwise-xor/bitwise-xor.d.ts @@ -4,14 +4,12 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare module "bitwise-xor" { - /** - * Bitwise XOR between two Buffers or Strings, returns a Buffer - */ - function xor(b1: Buffer, b2: Buffer): Buffer; - function xor(s1: string, s2: string): Buffer; - export = xor; -} +/** + * Bitwise XOR between two Buffers or Strings, returns a Buffer + */ +declare function xor(b1: Buffer, b2: Buffer): Buffer; +declare function xor(s1: string, s2: string): Buffer; +export = xor; diff --git a/bl/bl.d.ts b/bl/bl.d.ts index b3b97b3983..b0c8628334 100644 --- a/bl/bl.d.ts +++ b/bl/bl.d.ts @@ -5,36 +5,35 @@ /// -declare module 'bl' { - import stream = require('stream'); - class BufferList extends stream.Duplex { - new (callback?:(err:Error, buffer:Buffer) => void): void; +import stream = require('stream'); - append(buffer: Buffer):void; - get(index: number): number; - slice(start?: number, end?: number): Buffer; - copy(dest: Buffer, destStart?: number, srcStart?: number, srcEnd?: number): void; - duplicate(): BufferList; - consume(bytes?: number): void; - toString(encoding?: string, start?: number, end?: number): string; - length: number; +declare class BufferList extends stream.Duplex { + new(callback?: (err: Error, buffer: Buffer) => void): void; - readDoubleBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - } + append(buffer: Buffer): void; + get(index: number): number; + slice(start?: number, end?: number): Buffer; + copy(dest: Buffer, destStart?: number, srcStart?: number, srcEnd?: number): void; + duplicate(): BufferList; + consume(bytes?: number): void; + toString(encoding?: string, start?: number, end?: number): string; + length: number; - export = BufferList; + readDoubleBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; } + +export = BufferList; diff --git a/blue-tape/blue-tape.d.ts b/blue-tape/blue-tape.d.ts index 1216600cab..4a973c1715 100644 --- a/blue-tape/blue-tape.d.ts +++ b/blue-tape/blue-tape.d.ts @@ -6,7 +6,6 @@ /// /// -declare module 'blue-tape' { - import tape = require('tape'); - export = tape; -} + +import tape = require('tape'); +export = tape; diff --git a/bluebird-retry/bluebird-retry.d.ts b/bluebird-retry/bluebird-retry.d.ts index 1210bf3b53..01023ea8b9 100644 --- a/bluebird-retry/bluebird-retry.d.ts +++ b/bluebird-retry/bluebird-retry.d.ts @@ -4,21 +4,20 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare module "bluebird-retry" { - import Promise = require('bluebird'); - function retry(func:(param:T)=>void, options?:retry.Options):Promise; +import Promise = require('bluebird'); - namespace retry { - export interface Options { - interval?:number; - backoff?:number; - max_interval?:number; - timeout?:number; - max_tries?:number; - } +declare function retry(func: (param: T) => void, options?: retry.Options): Promise; - } +declare namespace retry { + export interface Options { + interval?: number; + backoff?: number; + max_interval?: number; + timeout?: number; + max_tries?: number; + } - export = retry; } + +export = retry; diff --git a/blueimp-md5/blueimp-md5.d.ts b/blueimp-md5/blueimp-md5.d.ts index 99880ba0d6..4434c55ab8 100644 --- a/blueimp-md5/blueimp-md5.d.ts +++ b/blueimp-md5/blueimp-md5.d.ts @@ -2,6 +2,5 @@ // Project: https://github.com/blueimp/JavaScript-MD5 // Definitions by: Ray Martone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'blueimp-md5' { - export function md5(value: string, key?: string, raw?: boolean): string; -} + +declare export function md5(value: string, key?: string, raw?: boolean): string; diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 16f639dfaf..64f97e8d33 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -5,15 +5,43 @@ /// -declare module "body-parser" { - import * as express from "express"; +import * as express from "express"; + +/** + * bodyParser: use individual json/urlencoded middlewares + * @deprecated + */ + +declare function bodyParser(options?: { /** - * bodyParser: use individual json/urlencoded middlewares - * @deprecated + * if deflated bodies will be inflated. (default: true) */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * only parse objects and arrays. (default: true) + */ + strict?: boolean; + /** + * passed to JSON.parse(). + */ + receiver?: (key: string, value: any) => any; + /** + * parse extended syntax with the qs module. (default: true) + */ + extended?: boolean; +}): express.RequestHandler; - function bodyParser(options?: { +declare namespace bodyParser { + export function json(options?: { /** * if deflated bodies will be inflated. (default: true) */ @@ -22,6 +50,10 @@ declare module "body-parser" { * maximum request body size. (default: '100kb') */ limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'json') + */ + type?: any; /** * function to verify body content, the parsing can be aborted by throwing an error. */ @@ -34,105 +66,72 @@ declare module "body-parser" { * passed to JSON.parse(). */ receiver?: (key: string, value: any) => any; - /** - * parse extended syntax with the qs module. (default: true) - */ - extended?: boolean; }): express.RequestHandler; - namespace bodyParser { - export function json(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'json') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * only parse objects and arrays. (default: true) - */ - strict?: boolean; - /** - * passed to JSON.parse(). - */ - receiver?: (key: string, value: any) => any; - }): express.RequestHandler; + export function raw(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + }): express.RequestHandler; - export function raw(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - }): express.RequestHandler; + export function text(options?: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'text/plain') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * the default charset to parse as, if not specified in content-type. (default: 'utf-8') + */ + defaultCharset?: string; + }): express.RequestHandler; - export function text(options?: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'text/plain') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * the default charset to parse as, if not specified in content-type. (default: 'utf-8') - */ - defaultCharset?: string; - }): express.RequestHandler; - - export function urlencoded(options: { - /** - * if deflated bodies will be inflated. (default: true) - */ - inflate?: boolean; - /** - * maximum request body size. (default: '100kb') - */ - limit?: any; - /** - * request content-type to parse, passed directly to the type-is library. (default: 'urlencoded') - */ - type?: any; - /** - * function to verify body content, the parsing can be aborted by throwing an error. - */ - verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; - /** - * parse extended syntax with the qs module. - */ - extended: boolean; - }): express.RequestHandler; - } - - export = bodyParser; + export function urlencoded(options: { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * maximum request body size. (default: '100kb') + */ + limit?: any; + /** + * request content-type to parse, passed directly to the type-is library. (default: 'urlencoded') + */ + type?: any; + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void; + /** + * parse extended syntax with the qs module. + */ + extended: boolean; + }): express.RequestHandler; } + +export = bodyParser; diff --git a/bookshelf/bookshelf.d.ts b/bookshelf/bookshelf.d.ts index 74f5e83d4a..bb877c6745 100644 --- a/bookshelf/bookshelf.d.ts +++ b/bookshelf/bookshelf.d.ts @@ -7,308 +7,307 @@ /// /// -declare module 'bookshelf' { - import knex = require('knex'); - import Promise = require('bluebird'); - import Lodash = require('lodash'); - interface Bookshelf extends Bookshelf.Events { - VERSION : string; - knex : knex; - Model : typeof Bookshelf.Model; - Collection : typeof Bookshelf.Collection; +import knex = require('knex'); +import Promise = require('bluebird'); +import Lodash = require('lodash'); - plugin(name: string) : Bookshelf; - transaction(callback : (transaction : knex.Transaction) => T) : Promise; - } +interface Bookshelf extends Bookshelf.Events { + VERSION: string; + knex: knex; + Model: typeof Bookshelf.Model; + Collection: typeof Bookshelf.Collection; - function Bookshelf(knex : knex) : Bookshelf; - - namespace Bookshelf { - abstract class Events { - on(event? : string, callback? : EventFunction, context? : any) : void; - off(event? : string) : void; - trigger(event? : string, ...args : any[]) : void; - triggerThen(name : string, ...args : any[]) : Promise; - once(event : string, callback : EventFunction, context? : any) : void; - } - - interface IModelBase { - /** Should be declared as a getter instead of a plain property. */ - hasTimestamps? : boolean|string[]; - /** Should be declared as a getter instead of a plain property. Should be required, but cannot have abstract properties yet. */ - tableName? : string; - } - - abstract class ModelBase> extends Events> implements IModelBase { - /** If overriding, must use a getter instead of a plain property. */ - idAttribute : string; - - constructor(attributes? : any, options? : ModelOptions); - - clear() : T; - clone() : T; - escape(attribute : string) : string; - format(attributes : any) : any; - get(attribute : string) : any; - has(attribute : string) : boolean; - hasChanged(attribute? : string) : boolean; - isNew() : boolean; - parse(response : any) : any; - previousAttributes() : any; - previous(attribute : string) : any; - related>(relation : string) : R | Collection; - serialize(options? : SerializeOptions) : any; - set(attribute?: {[key : string] : any}, options? : SetOptions) : T; - set(attribute : string, value? : any, options? : SetOptions) : T; - timestamp(options? : TimestampOptions) : any; - toJSON(options? : SerializeOptions) : any; - unset(attribute : string) : T; - - // lodash methods - invert() : R; - keys() : string[]; - omit(predicate? : Lodash.ObjectIterator, thisArg? : any) : R; - omit(...attributes : string[]) : R; - pairs() : any[][]; - pick(predicate? : Lodash.ObjectIterator, thisArg? : any) : R; - pick(...attributes : string[]) : R; - values() : any[]; - } - - class Model> extends ModelBase { - static collection>(models? : T[], options? : CollectionOptions) : Collection; - static count(column? : string, options? : SyncOptions) : Promise; - /** @deprecated use Typescript classes */ - static extend>(prototypeProperties? : any, classProperties? : any) : Function; // should return a type - static fetchAll>() : Promise>; - /** @deprecated should use `new` objects instead. */ - static forge(attributes? : any, options? : ModelOptions) : T; - - belongsTo>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; - belongsToMany>(target : {new(...args : any[]) : R}, table? : string, foreignKey? : string, otherKey? : string) : Collection; - count(column? : string, options? : SyncOptions) : Promise; - destroy(options? : SyncOptions) : Promise; - fetch(options? : FetchOptions) : Promise; - fetchAll(options? : FetchAllOptions) : Promise>; - hasMany>(target : {new(...args : any[]) : R}, foreignKey? : string) : Collection; - hasOne>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; - load(relations : string|string[], options? : LoadOptions) : Promise; - morphMany>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : Collection; - morphOne>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : R; - morphTo(name : string, columnNames? : string[], ...target : typeof Model[]) : T; - morphTo(name : string, ...target : typeof Model[]) : T; - query(...query : string[]) : T; - query(query : {[key : string] : any}) : T; - query(callback : (qb : knex.QueryBuilder) => void) : T; - query() : knex.QueryBuilder; - refresh(options? : FetchOptions) : Promise; - resetQuery() : T; - save(key? : string, val? : string, options? : SaveOptions) : Promise; - save(attrs? : {[key : string] : any}, options? : SaveOptions) : Promise; - through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; - where(properties : {[key : string] : any}) : T; - where(key : string, operatorOrValue : string|number|boolean, valueIfOperator? : string|number|boolean) : T; - } - - abstract class CollectionBase> extends Events { - add(models : T[]|{[key : string] : any}[], options? : CollectionAddOptions) : Collection; - at(index : number) : T; - clone() : Collection; - fetch(options? : CollectionFetchOptions) : Promise>; - findWhere(match : {[key : string] : any}) : T; - get(id : any) : T; - invokeThen(name : string, ...args : any[]) : Promise; - parse(response : any) : any; - pluck(attribute : string) : any[]; - pop() : void; - push(model : any) : Collection; - reduceThen(iterator : (prev : R, cur : T, idx : number, array : T[]) => R, initialValue : R, context : any) : Promise; - remove(model : T, options? : EventOptions) : T; - remove(model : T[], options? : EventOptions) : T[]; - reset(model : any[], options? : CollectionAddOptions) : T[]; - serialize(options? : SerializeOptions) : any; - set(models : T[]|{[key : string] : any}[], options? : CollectionSetOptions) : Collection; - shift(options? : EventOptions) : void; - slice(begin? : number, end? : number) : void; - toJSON(options? : SerializeOptions) : any; - unshift(model : any, options? : CollectionAddOptions) : void; - where(match : {[key : string] : any}, firstOnly : boolean) : T|Collection; - - // lodash methods - all(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - all(predicate? : R) : boolean; - any(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - any(predicate? : R) : boolean; - chain() : Lodash.LoDashExplicitObjectWrapper; - collect(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - collect(predicate? : R) : T[]; - contains(value : any, fromIndex? : number) : boolean; - countBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : Lodash.Dictionary; - countBy(predicate? : R) : Lodash.Dictionary; - detect(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T; - detect(predicate? : R) : T; - difference(...values : T[]) : T[]; - drop(n? : number) : T[]; - each(callback? : Lodash.ListIterator, thisArg? : any) : Lodash.List; - each(callback? : Lodash.DictionaryIterator, thisArg? : any) : Lodash.Dictionary; - each(callback? : Lodash.ObjectIterator, thisArg? : any) : T; - every(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - every(predicate? : R) : boolean; - filter(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - filter(predicate? : R) : T[]; - find(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T; - find(predicate? : R) : T; - first() : T; - foldl(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - foldr(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - forEach(callback? : Lodash.ListIterator, thisArg? : any) : Lodash.List; - forEach(callback? : Lodash.DictionaryIterator, thisArg? : any) : Lodash.Dictionary; - forEach(callback? : Lodash.ObjectIterator, thisArg? : any) : T; - groupBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : Lodash.Dictionary; - groupBy(predicate? : R) : Lodash.Dictionary; - head() : T; - include(value : any, fromIndex? : number) : boolean; - indexOf(value : any, fromIndex? : number) : number; - initial() : T[]; - inject(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - invoke(methodName : string|Function, ...args : any[]) : any; - isEmpty() : boolean; - keys() : string[]; - last() : T; - lastIndexOf(value : any, fromIndex? : number) : number; - map(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - map(predicate? : R) : T[]; - max(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; - max(predicate? : R) : T; - min(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; - min(predicate? : R) : T; - reduce(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - reduceRight(callback? : Lodash.MemoIterator, accumulator? : R, thisArg? : any) : R; - reject(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - reject(predicate? : R) : T[]; - rest() : T[]; - select(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - select(predicate? : R) : T[]; - shuffle() : T[]; - size() : number; - some(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; - some(predicate? : R) : boolean; - sortBy(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - sortBy(predicate? : R) : T[]; - tail() : T[]; - take(n? : number) : T[]; - toArray() : T[]; - without(...values : any[]) : T[]; - } - - class Collection> extends CollectionBase { - /** @deprecated use Typescript classes */ - static extend(prototypeProperties? : any, classProperties? : any) : Function; - /** @deprecated should use `new` objects instead. */ - static forge(attributes? : any, options? : ModelOptions) : T; - - attach(ids : any[], options? : SyncOptions) : Promise>; - count(column? : string, options? : SyncOptions) : Promise; - create(model : {[key : string] : any}, options? : CollectionCreateOptions) : Promise; - detach(ids : any[], options? : SyncOptions) : Promise; - fetchOne(options? : CollectionFetchOneOptions) : Promise; - load(relations : string|string[], options? : SyncOptions) : Promise>; - query(...query : string[]) : Collection; - query(query : {[key : string] : any}) : Collection; - query(callback : (qb : knex.QueryBuilder) => void) : Collection; - query() : knex.QueryBuilder; - resetQuery() : Collection; - through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; - updatePivot(attributes : any, options? : PivotOptions) : Promise; - withPivot(columns : string[]) : Collection; - } - - interface ModelOptions { - tableName? : string; - hasTimestamps? : boolean; - parse? : boolean; - } - - interface LoadOptions extends SyncOptions { - withRelated: string|any|any[]; - } - - interface FetchOptions extends SyncOptions { - require? : boolean; - columns? : string|string[]; - withRelated? : string|any|any[]; - } - - interface FetchAllOptions extends SyncOptions { - require? : boolean; - } - - interface SaveOptions extends SyncOptions { - method? : string; - defaults? : string; - patch? : boolean; - require? : boolean; - } - - interface SerializeOptions { - shallow? : boolean; - omitPivot? : boolean; - } - - interface SetOptions { - unset? : boolean; - } - - interface TimestampOptions { - method? : string; - } - - interface SyncOptions { - transacting? : knex.Transaction; - debug? : boolean; - } - - interface CollectionOptions { - comparator? : boolean|string|((a : T, b : T) => number); - } - - interface CollectionAddOptions extends EventOptions { - at? : number; - merge? : boolean; - } - - interface CollectionFetchOptions { - require? : boolean; - withRelated? : string|string[]; - } - - interface CollectionFetchOneOptions { - require? : boolean; - columns? : string|string[]; - } - - interface CollectionSetOptions extends EventOptions { - add? : boolean; - remove? : boolean; - merge?: boolean; - } - - interface PivotOptions { - query? : Function|any; - require? : boolean; - } - - interface EventOptions { - silent? : boolean; - } - - interface EventFunction { - (model: T, attrs: any, options: any) : Promise|void; - } - - interface CollectionCreateOptions extends ModelOptions, SyncOptions, CollectionAddOptions, SaveOptions {} - } - - export = Bookshelf; + plugin(name: string): Bookshelf; + transaction(callback: (transaction: knex.Transaction) => T): Promise; } + +declare function Bookshelf(knex: knex): Bookshelf; + +declare namespace Bookshelf { + abstract class Events { + on(event?: string, callback?: EventFunction, context?: any): void; + off(event?: string): void; + trigger(event?: string, ...args: any[]): void; + triggerThen(name: string, ...args: any[]): Promise; + once(event: string, callback: EventFunction, context?: any): void; + } + + interface IModelBase { + /** Should be declared as a getter instead of a plain property. */ + hasTimestamps?: boolean | string[]; + /** Should be declared as a getter instead of a plain property. Should be required, but cannot have abstract properties yet. */ + tableName?: string; + } + + abstract class ModelBase> extends Events> implements IModelBase { + /** If overriding, must use a getter instead of a plain property. */ + idAttribute: string; + + constructor(attributes?: any, options?: ModelOptions); + + clear(): T; + clone(): T; + escape(attribute: string): string; + format(attributes: any): any; + get(attribute: string): any; + has(attribute: string): boolean; + hasChanged(attribute?: string): boolean; + isNew(): boolean; + parse(response: any): any; + previousAttributes(): any; + previous(attribute: string): any; + related>(relation: string): R | Collection; + serialize(options?: SerializeOptions): any; + set(attribute?: { [key: string]: any }, options?: SetOptions): T; + set(attribute: string, value?: any, options?: SetOptions): T; + timestamp(options?: TimestampOptions): any; + toJSON(options?: SerializeOptions): any; + unset(attribute: string): T; + + // lodash methods + invert(): R; + keys(): string[]; + omit(predicate?: Lodash.ObjectIterator, thisArg?: any): R; + omit(...attributes: string[]): R; + pairs(): any[][]; + pick(predicate?: Lodash.ObjectIterator, thisArg?: any): R; + pick(...attributes: string[]): R; + values(): any[]; + } + + class Model> extends ModelBase { + static collection>(models?: T[], options?: CollectionOptions): Collection; + static count(column?: string, options?: SyncOptions): Promise; + /** @deprecated use Typescript classes */ + static extend>(prototypeProperties?: any, classProperties?: any): Function; // should return a type + static fetchAll>(): Promise>; + /** @deprecated should use `new` objects instead. */ + static forge(attributes?: any, options?: ModelOptions): T; + + belongsTo>(target: { new (...args: any[]): R }, foreignKey?: string): R; + belongsToMany>(target: { new (...args: any[]): R }, table?: string, foreignKey?: string, otherKey?: string): Collection; + count(column?: string, options?: SyncOptions): Promise; + destroy(options?: SyncOptions): Promise; + fetch(options?: FetchOptions): Promise; + fetchAll(options?: FetchAllOptions): Promise>; + hasMany>(target: { new (...args: any[]): R }, foreignKey?: string): Collection; + hasOne>(target: { new (...args: any[]): R }, foreignKey?: string): R; + load(relations: string | string[], options?: LoadOptions): Promise; + morphMany>(target: { new (...args: any[]): R }, name?: string, columnNames?: string[], morphValue?: string): Collection; + morphOne>(target: { new (...args: any[]): R }, name?: string, columnNames?: string[], morphValue?: string): R; + morphTo(name: string, columnNames?: string[], ...target: typeof Model[]): T; + morphTo(name: string, ...target: typeof Model[]): T; + query(...query: string[]): T; + query(query: { [key: string]: any }): T; + query(callback: (qb: knex.QueryBuilder) => void): T; + query(): knex.QueryBuilder; + refresh(options?: FetchOptions): Promise; + resetQuery(): T; + save(key?: string, val?: string, options?: SaveOptions): Promise; + save(attrs?: { [key: string]: any }, options?: SaveOptions): Promise; + through>(interim: typeof Model, throughForeignKey?: string, otherKey?: string): R | Collection; + where(properties: { [key: string]: any }): T; + where(key: string, operatorOrValue: string | number | boolean, valueIfOperator?: string | number | boolean): T; + } + + abstract class CollectionBase> extends Events { + add(models: T[] | { [key: string]: any }[], options?: CollectionAddOptions): Collection; + at(index: number): T; + clone(): Collection; + fetch(options?: CollectionFetchOptions): Promise>; + findWhere(match: { [key: string]: any }): T; + get(id: any): T; + invokeThen(name: string, ...args: any[]): Promise; + parse(response: any): any; + pluck(attribute: string): any[]; + pop(): void; + push(model: any): Collection; + reduceThen(iterator: (prev: R, cur: T, idx: number, array: T[]) => R, initialValue: R, context: any): Promise; + remove(model: T, options?: EventOptions): T; + remove(model: T[], options?: EventOptions): T[]; + reset(model: any[], options?: CollectionAddOptions): T[]; + serialize(options?: SerializeOptions): any; + set(models: T[] | { [key: string]: any }[], options?: CollectionSetOptions): Collection; + shift(options?: EventOptions): void; + slice(begin?: number, end?: number): void; + toJSON(options?: SerializeOptions): any; + unshift(model: any, options?: CollectionAddOptions): void; + where(match: { [key: string]: any }, firstOnly: boolean): T | Collection; + + // lodash methods + all(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): boolean; + all(predicate?: R): boolean; + any(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): boolean; + any(predicate?: R): boolean; + chain(): Lodash.LoDashExplicitObjectWrapper; + collect(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): T[]; + collect(predicate?: R): T[]; + contains(value: any, fromIndex?: number): boolean; + countBy(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): Lodash.Dictionary; + countBy(predicate?: R): Lodash.Dictionary; + detect(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): T; + detect(predicate?: R): T; + difference(...values: T[]): T[]; + drop(n?: number): T[]; + each(callback?: Lodash.ListIterator, thisArg?: any): Lodash.List; + each(callback?: Lodash.DictionaryIterator, thisArg?: any): Lodash.Dictionary; + each(callback?: Lodash.ObjectIterator, thisArg?: any): T; + every(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): boolean; + every(predicate?: R): boolean; + filter(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): T[]; + filter(predicate?: R): T[]; + find(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): T; + find(predicate?: R): T; + first(): T; + foldl(callback?: Lodash.MemoIterator, accumulator?: R, thisArg?: any): R; + foldr(callback?: Lodash.MemoIterator, accumulator?: R, thisArg?: any): R; + forEach(callback?: Lodash.ListIterator, thisArg?: any): Lodash.List; + forEach(callback?: Lodash.DictionaryIterator, thisArg?: any): Lodash.Dictionary; + forEach(callback?: Lodash.ObjectIterator, thisArg?: any): T; + groupBy(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): Lodash.Dictionary; + groupBy(predicate?: R): Lodash.Dictionary; + head(): T; + include(value: any, fromIndex?: number): boolean; + indexOf(value: any, fromIndex?: number): number; + initial(): T[]; + inject(callback?: Lodash.MemoIterator, accumulator?: R, thisArg?: any): R; + invoke(methodName: string | Function, ...args: any[]): any; + isEmpty(): boolean; + keys(): string[]; + last(): T; + lastIndexOf(value: any, fromIndex?: number): number; + map(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): T[]; + map(predicate?: R): T[]; + max(predicate?: Lodash.ListIterator | string, thisArg?: any): T; + max(predicate?: R): T; + min(predicate?: Lodash.ListIterator | string, thisArg?: any): T; + min(predicate?: R): T; + reduce(callback?: Lodash.MemoIterator, accumulator?: R, thisArg?: any): R; + reduceRight(callback?: Lodash.MemoIterator, accumulator?: R, thisArg?: any): R; + reject(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): T[]; + reject(predicate?: R): T[]; + rest(): T[]; + select(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): T[]; + select(predicate?: R): T[]; + shuffle(): T[]; + size(): number; + some(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): boolean; + some(predicate?: R): boolean; + sortBy(predicate?: Lodash.ListIterator | Lodash.DictionaryIterator | string, thisArg?: any): T[]; + sortBy(predicate?: R): T[]; + tail(): T[]; + take(n?: number): T[]; + toArray(): T[]; + without(...values: any[]): T[]; + } + + class Collection> extends CollectionBase { + /** @deprecated use Typescript classes */ + static extend(prototypeProperties?: any, classProperties?: any): Function; + /** @deprecated should use `new` objects instead. */ + static forge(attributes?: any, options?: ModelOptions): T; + + attach(ids: any[], options?: SyncOptions): Promise>; + count(column?: string, options?: SyncOptions): Promise; + create(model: { [key: string]: any }, options?: CollectionCreateOptions): Promise; + detach(ids: any[], options?: SyncOptions): Promise; + fetchOne(options?: CollectionFetchOneOptions): Promise; + load(relations: string | string[], options?: SyncOptions): Promise>; + query(...query: string[]): Collection; + query(query: { [key: string]: any }): Collection; + query(callback: (qb: knex.QueryBuilder) => void): Collection; + query(): knex.QueryBuilder; + resetQuery(): Collection; + through>(interim: typeof Model, throughForeignKey?: string, otherKey?: string): R | Collection; + updatePivot(attributes: any, options?: PivotOptions): Promise; + withPivot(columns: string[]): Collection; + } + + interface ModelOptions { + tableName?: string; + hasTimestamps?: boolean; + parse?: boolean; + } + + interface LoadOptions extends SyncOptions { + withRelated: string | any | any[]; + } + + interface FetchOptions extends SyncOptions { + require?: boolean; + columns?: string | string[]; + withRelated?: string | any | any[]; + } + + interface FetchAllOptions extends SyncOptions { + require?: boolean; + } + + interface SaveOptions extends SyncOptions { + method?: string; + defaults?: string; + patch?: boolean; + require?: boolean; + } + + interface SerializeOptions { + shallow?: boolean; + omitPivot?: boolean; + } + + interface SetOptions { + unset?: boolean; + } + + interface TimestampOptions { + method?: string; + } + + interface SyncOptions { + transacting?: knex.Transaction; + debug?: boolean; + } + + interface CollectionOptions { + comparator?: boolean | string | ((a: T, b: T) => number); + } + + interface CollectionAddOptions extends EventOptions { + at?: number; + merge?: boolean; + } + + interface CollectionFetchOptions { + require?: boolean; + withRelated?: string | string[]; + } + + interface CollectionFetchOneOptions { + require?: boolean; + columns?: string | string[]; + } + + interface CollectionSetOptions extends EventOptions { + add?: boolean; + remove?: boolean; + merge?: boolean; + } + + interface PivotOptions { + query?: Function | any; + require?: boolean; + } + + interface EventOptions { + silent?: boolean; + } + + interface EventFunction { + (model: T, attrs: any, options: any): Promise | void; + } + + interface CollectionCreateOptions extends ModelOptions, SyncOptions, CollectionAddOptions, SaveOptions { } +} + +export = Bookshelf; diff --git a/boolify-string/boolify-string.d.ts b/boolify-string/boolify-string.d.ts index d4ab286a5e..8d405fe032 100644 --- a/boolify-string/boolify-string.d.ts +++ b/boolify-string/boolify-string.d.ts @@ -2,7 +2,6 @@ // Project: https://github.com/sanemat/node-boolify-string // Definitions by: Tobias Henöckl // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "boolify-string" { - function boolifyString(obj: any): boolean; - export = boolifyString; -} + +declare function boolifyString(obj: any): boolean; +export = boolifyString; diff --git a/bounce.js/bounce.d.ts b/bounce.js/bounce.d.ts index 54fe897638..3e02bfe0e6 100644 --- a/bounce.js/bounce.d.ts +++ b/bounce.js/bounce.d.ts @@ -5,62 +5,61 @@ /// -declare module 'bounce.js' { - export default Bounce - interface Point2D { - x: number - y: number - } +export default Bounce - interface BounceOptions { - from: T - to: T - duration?: number - delay?: number - easing?: string - bounces?: number - stiffness?: number - } - - interface AnimationOptions { - loop?: boolean - remove?: boolean - onComplete?: () => void - } - - interface SerailizedComponent { - type: string - from: T - to: T - duration: number - delay: number - easing: string - bounces: number - stiffness: number - } - - class Bounce { - static FPS: number - static counter: number - - static isSupported(): boolean - - constructor(); - - scale(options: BounceOptions): Bounce - rotate(options: BounceOptions): Bounce - translate(options: BounceOptions): Bounce - skew(options: BounceOptions): Bounce - - serialize(): SerailizedComponent[] - deserialize(serailized: SerailizedComponent[]): Bounce - - applyTo(element: Element, options?: AnimationOptions): void - applyTo(elements: Element[], options?: AnimationOptions): void - applyTo(elements: JQuery, options?: AnimationOptions): JQueryPromise - - define(name: string): Bounce - remove(): void - } +interface Point2D { + x: number + y: number +} + +interface BounceOptions { + from: T + to: T + duration?: number + delay?: number + easing?: string + bounces?: number + stiffness?: number +} + +interface AnimationOptions { + loop?: boolean + remove?: boolean + onComplete?: () => void +} + +interface SerailizedComponent { + type: string + from: T + to: T + duration: number + delay: number + easing: string + bounces: number + stiffness: number +} + +declare class Bounce { + static FPS: number + static counter: number + + static isSupported(): boolean + + constructor(); + + scale(options: BounceOptions): Bounce + rotate(options: BounceOptions): Bounce + translate(options: BounceOptions): Bounce + skew(options: BounceOptions): Bounce + + serialize(): SerailizedComponent[] + deserialize(serailized: SerailizedComponent[]): Bounce + + applyTo(element: Element, options?: AnimationOptions): void + applyTo(elements: Element[], options?: AnimationOptions): void + applyTo(elements: JQuery, options?: AnimationOptions): JQueryPromise + + define(name: string): Bounce + remove(): void } diff --git a/brorand/brorand.d.ts b/brorand/brorand.d.ts index efef9baa3f..f86618c63a 100644 --- a/brorand/brorand.d.ts +++ b/brorand/brorand.d.ts @@ -5,26 +5,25 @@ /// -declare module "brorand" { - type rand = {getByte: () => number}; - interface RandStatic { - new (rand: rand): RandInstance; - } +type rand = { getByte: () => number }; - interface RandInstance { - rand: rand; - generate(len: number): Buffer|Uint8Array; - } - - interface BrorandStatic { - (len: number): Buffer|Uint8Array; - Rand: RandStatic; - } - - namespace Brorand {} - - let Brorand: BrorandStatic; - - export = Brorand; +interface RandStatic { + new (rand: rand): RandInstance; } + +interface RandInstance { + rand: rand; + generate(len: number): Buffer | Uint8Array; +} + +interface BrorandStatic { + (len: number): Buffer | Uint8Array; + Rand: RandStatic; +} + +declare namespace Brorand { } + +declare let Brorand: BrorandStatic; + +export = Brorand; diff --git a/browser-harness/browser-harness.d.ts b/browser-harness/browser-harness.d.ts index c57311b1f8..d9c6116d71 100644 --- a/browser-harness/browser-harness.d.ts +++ b/browser-harness/browser-harness.d.ts @@ -5,129 +5,128 @@ /// -declare module "browser-harness" { - import _events = require('events'); - interface HarnessEvents extends _events.EventEmitter { - once(event: string, listener: (driver: Driver) => void): this; - once(event: 'ready', listener: (driver: Driver) => void): this; +import _events = require('events'); - on(event: string, listener: (driver: Driver) => void): this; - on(event: 'ready', listener: (driver: Driver) => void): this; - } +interface HarnessEvents extends _events.EventEmitter { + once(event: string, listener: (driver: Driver) => void): this; + once(event: 'ready', listener: (driver: Driver) => void): this; - interface DriverEvents extends _events.EventEmitter { - once(event: string, listener: (text: string) => void): this; - once(event: 'console.log', listener: (text: string) => void): this; - once(event: 'console.warn', listener: (text: string) => void): this; - once(event: 'console.error', listener: (text: string) => void): this; - once(event: 'window.onerror', listener: (text: string) => void): this; - - on(event: string, listener: (text: string) => void): this; - on(event: 'console.log', listener: (text: string) => void): this; - on(event: 'console.warn', listener: (text: string) => void): this; - on(event: 'console.error', listener: (text: string) => void): this; - on(event: 'window.onerror', listener: (text: string) => void): this; - } - - export interface Driver { - exec(args: { func: Function; args?: any[]}, callback?: Function) : any; - exec(func: Function, callback?: Function) : any; - - setUrl(url: string, callback?: Function); - - waitFor(args: { condition: Function; exec?: Function; timeoutMS?: number }, callback?: Function); - waitFor(condition: Function, callback?: Function); - - findElement(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy; - findElements(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; - - findVisible(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy; - findVisibles(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; - find(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; - - events: DriverEvents; - } - - export interface ElementProxy { - click(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - focus(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - blur(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - val(value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - attr(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - removeAttr(name: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - prop(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - removeProp(name: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - html(value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - text(value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - hasClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - addClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - removeClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - toggleClass(className: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - trigger(event: string, extraParameters?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - triggerHandler(event: string, extraParameters?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - css(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - height(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - innerHeight(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - outerHeight(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - width(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - innerWidth(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - outerWidth(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - offset(value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - position(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - scrollLeft(value?: number, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - scrollTop(value?: number, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - hide(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - show(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - toggle(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - children(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - closest(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - contents(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - find(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - findElements(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - findElement(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - findVisible(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - findVisibles(selector: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - isActionable(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - first(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - has(arg: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - is(arg: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - last(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - next(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - nextAll(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - nextUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - offsetParent(callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - parent(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - parents(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - parentsUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - prev(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - prevAll(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - prevUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - siblings(selector?: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - - data(name: string, value?: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - removeData(name: string, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - - filter(selector: any, callback?: (err: Error, element: ElementProxy) => void) : ElementProxy - } - - export class Browser { - //constructor(args: { type: string; location?: string; args?: string[] }); - constructor(args: { type: string; location?: string; args?: any; }); - - open(harnessUrl: string, serverUrl?: string); - close(); - } - - export function listen(port: number, callback?: Function) - export var events: HarnessEvents; - export var config: { - timeoutMS: number; - retryMS: number; - }; + on(event: string, listener: (driver: Driver) => void): this; + on(event: 'ready', listener: (driver: Driver) => void): this; } + +interface DriverEvents extends _events.EventEmitter { + once(event: string, listener: (text: string) => void): this; + once(event: 'console.log', listener: (text: string) => void): this; + once(event: 'console.warn', listener: (text: string) => void): this; + once(event: 'console.error', listener: (text: string) => void): this; + once(event: 'window.onerror', listener: (text: string) => void): this; + + on(event: string, listener: (text: string) => void): this; + on(event: 'console.log', listener: (text: string) => void): this; + on(event: 'console.warn', listener: (text: string) => void): this; + on(event: 'console.error', listener: (text: string) => void): this; + on(event: 'window.onerror', listener: (text: string) => void): this; +} + +export interface Driver { + exec(args: { func: Function; args?: any[] }, callback?: Function): any; + exec(func: Function, callback?: Function): any; + + setUrl(url: string, callback?: Function); + + waitFor(args: { condition: Function; exec?: Function; timeoutMS?: number }, callback?: Function); + waitFor(condition: Function, callback?: Function); + + findElement(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy; + findElements(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; + + findVisible(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy; + findVisibles(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; + find(selector: string, callback?: (err: Error, elements: ElementProxy) => void): ElementProxy; + + events: DriverEvents; +} + +export interface ElementProxy { + click(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + focus(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + blur(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + val(value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + attr(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + removeAttr(name: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + prop(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + removeProp(name: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + html(value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + text(value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + hasClass(className: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + addClass(className: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + removeClass(className: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + toggleClass(className: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + trigger(event: string, extraParameters?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + triggerHandler(event: string, extraParameters?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + css(name: string, value?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + height(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + innerHeight(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + outerHeight(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + width(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + innerWidth(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + outerWidth(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + offset(value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + position(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + scrollLeft(value?: number, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + scrollTop(value?: number, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + hide(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + show(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + toggle(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + children(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + closest(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + contents(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + find(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + findElements(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + findElement(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + findVisible(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + findVisibles(selector: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + isActionable(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + first(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + has(arg: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + is(arg: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + last(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + next(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + nextAll(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + nextUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + offsetParent(callback?: (err: Error, element: ElementProxy) => void): ElementProxy + parent(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + parents(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + parentsUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + prev(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + prevAll(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + prevUntil(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + siblings(selector?: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + + data(name: string, value?: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + removeData(name: string, callback?: (err: Error, element: ElementProxy) => void): ElementProxy + + filter(selector: any, callback?: (err: Error, element: ElementProxy) => void): ElementProxy +} + +declare export class Browser { + //constructor(args: { type: string; location?: string; args?: string[] }); + constructor(args: { type: string; location?: string; args?: any; }); + + open(harnessUrl: string, serverUrl?: string); + close(); +} + +declare export function listen(port: number, callback?: Function) +declare export var events: HarnessEvents; +declare export var config: { + timeoutMS: number; + retryMS: number; +}; diff --git a/browser-sync/browser-sync.d.ts b/browser-sync/browser-sync.d.ts index 3bc083d1f1..a6740d6d93 100644 --- a/browser-sync/browser-sync.d.ts +++ b/browser-sync/browser-sync.d.ts @@ -7,416 +7,415 @@ /// /// -declare module "browser-sync" { - import chokidar = require("chokidar"); - import fs = require("fs"); - import http = require("http"); - import mm = require("micromatch"); - namespace browserSync { - interface Options { - /** - * Browsersync includes a user-interface that is accessed via a separate port. The UI allows to controls - * all devices, push sync updates and much more. - * - * port - Default: 3001 - * weinre.port - Default: 8080 - * Note: requires at least version 2.0.0 - */ - ui?: UIOptions; - /** - * Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS - * & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob - * patterns. - * Default: false - */ - files?: string | string[]; - /** - * File watching options that get passed along to Chokidar. Check their docs for available options - * Default: undefined - * Note: requires at least version 2.6.0 - */ - watchOptions?: chokidar.WatchOptions; - /** - * Use the built-in static server for basic HTML/JS/CSS websites. - * Default: false - */ - server?: ServerOptions; - /** - * Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site. - * target - Default: undefined - * ws - Default: undefined - * middleware - Default: undefined - * reqHeaders - Default: undefined - * proxyRes - Default: undefined - */ - proxy?: string | boolean | ProxyOptions; - /** - * Use a specific port (instead of the one auto-detected by Browsersync) - * Default: 3000 - */ - port?: number; - /** - * Add additional directories from which static files should be served. - * Should only be used in proxy or snippet mode. - * Default: [] - * Note: requires at least version 2.8.0 - */ - serveStatic?: string[]; - /** - * Enable https for localhost development. - * Note - this is not needed for proxy option as it will be inferred from your target url. - * Note: requires at least version 1.3.0 - */ - https?: boolean; - /** - * Clicks, Scrolls & Form inputs on any device will be mirrored to all others. - * clicks - Default: true - * scroll - Default: true - * forms - Default: true - */ - ghostMode?: GhostOptions | boolean; - /** - * Can be either "info", "debug", "warn", or "silent" - * Default: info - */ - logLevel?: string; - /** - * Change the console logging prefix. Useful if you're creating your own project based on Browsersync - * Default: BS - * Note: requires at least version 1.5.1 - */ - logPrefix?: string; - /** - * Whether or not to log connections - * Default: false - */ - logConnections?: boolean; - /** - * Whether or not to log information about changed files - * Default: false - */ - logFileChanges?: boolean; - /** - * Log the snippet to the console when you're in snippet mode (no proxy/server) - * Default: true - * Note: requires at least version 1.5.2 - */ - logSnippet?: boolean; - /** - * You can control how the snippet is injected onto each page via a custom regex + function. - * You can also provide patterns for certain urls that should be ignored from the snippet injection. - * Note: requires at least version 2.0.0 - */ - snippetOptions?: SnippetOptions; - /** - * Add additional HTML rewriting rules. - * Default: false - * Note: requires at least version 2.4.0 - */ - rewriteRules?: boolean | RewriteRules[]; - /** - * Tunnel the Browsersync server through a random Public URL - * Default: null - */ - tunnel?: string | boolean; - /** - * Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're - * working offline, you can reduce start-up time by setting this option to false - */ - online?: boolean; - /** - * Default: true - * Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. - * Can be true, local, external, ui, ui-external, tunnel or false - */ - open?: string | boolean; - /** - * The browser(s) to open - * Default: default - */ - browser?: string | string[]; - /** - * Requires an internet connection - useful for services such as Typekit as it allows you to configure - * domains such as *.xip.io in your kit settings - * Default: false - */ - xip?: boolean; - /** - * Reload each browser when Browsersync is restarted. - * Default: false - */ - reloadOnRestart?: boolean; - /** - * The small pop-over notifications in the browser are not always needed/wanted. - * Default: true - */ - notify?: boolean; - /** - * scrollProportionally: false // Sync viewports to TOP position - * Default: true - */ - scrollProportionally?: boolean; - /** - * How often to send scroll events - * Default: 0 - */ - scrollThrottle?: number; - /** - * Decide which technique should be used to restore scroll position following a reload. - * Can be window.name or cookie - * Default: 'window.name' - */ - scrollRestoreTechnique?: string; - /** - * Sync the scroll position of any element on the page. Add any amount of CSS selectors - * Default: [] - * Note: requires at least version 2.9.0 - */ - scrollElements?: string[]; - /** - * Default: [] - * Note: requires at least version 2.9.0 - * Sync the scroll position of any element on the page - where any scrolled element will cause - * all others to match scroll position. This is helpful when a breakpoint alters which element - * is actually scrolling - */ - scrollElementMapping?: string[]; - /** - * Time, in milliseconds, to wait before instructing the browser to reload/inject following a file - * change event - * Default: 0 - */ - reloadDelay?: number; - /** - * Restrict the frequency in which browser:reload events can be emitted to connected clients - * Default: 0 - * Note: requires at least version 2.6.0 - */ - reloadDebounce?: number; - /** - * User provided plugins - * Default: [] - * Note: requires at least version 2.6.0 - */ - plugins?: any[]; - /** - * Whether to inject changes (rather than a page refresh) - * Default: true - */ - injectChanges?: boolean; - /** - * The initial path to load - */ - startPath?: string; - /** - * Whether to minify the client script - * Default: true - */ - minify?: boolean; - /** - * Override host detection if you know the correct IP to use - */ - host?: string; - /** - * Send file-change events to the browser - * Default: true - */ - codeSync?: boolean; - /** - * Append timestamps to injected files - * Default: true - */ - timestamps?: boolean; - /** - * Alter the script path for complete control over where the Browsersync Javascript is served - * from. Whatever you return from this function will be used as the script path. - * Note: requires at least version 1.5.0 - */ - scriptPath?: (path: string) => string; - /** - * Configure the Socket.IO path and namespace & domain to avoid collisions. - * path - Default: "/browser-sync/socket.io" - * clientPath - Default: "/browser-sync" - * namespace - Default: "/browser-sync" - * domain - Default: undefined - * port - Default: undefined - * clients.heartbeatTimeout - Default: 5000 - * Note: requires at least version 1.6.2 - */ - socket?: SocketOptions; - middleware?: MiddlewareHandler | MiddlewareHandler[]; - } +import chokidar = require("chokidar"); +import fs = require("fs"); +import http = require("http"); +import mm = require("micromatch"); - interface Hash { - [path: string]: T; - } - - interface UIOptions { - /** set the default port */ - port?: number; - /** set the default weinre port */ - weinre?: { - port?: number; - }; - } - - interface ServerOptions { - /** set base directory */ - baseDir?: string | string[]; - /** enable directory listing */ - directory?: boolean; - /** set index filename */ - index?: string; - /** - * key-value object hash, where the key is the url to match, - * and the value is the folder to serve (relative to your working directory) - */ - routes?: Hash; - /** configure custom middleware */ - middleware?: MiddlewareHandler[]; - } - - interface ProxyOptions { - target?: string; - middleware?: MiddlewareHandler; - ws: boolean; - reqHeaders: (config: any) => Hash; - proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any; - } - - interface MiddlewareHandler { - (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; - } - - interface GhostOptions { - clicks?: boolean; - scroll?: boolean; - forms?: boolean; - } - - interface SnippetOptions { - ignorePaths?: string; - rule?: { match?: RegExp; fn?: (snippet: string, match: string) => any }; - } - - interface SocketOptions { - path?: string; - clientPath?: string; - namespace?: string; - domain?: string; - port?: number; - clients?: { heartbeatTimeout?: number; }; - } - - interface RewriteRules { - match: RegExp; - fn: (match: string) => string; - } - - interface StreamOptions { - once?: boolean; - match?: mm.Pattern | mm.Pattern[]; - } - - interface BrowserSyncStatic extends BrowserSyncInstance { - /** - * Start the Browsersync service. This will launch a server, proxy or start the snippet mode - * depending on your use-case. - */ - (config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; - /** - * Create a Browsersync instance - * @param name an identifier that can used for retrieval later - */ - create(name?: string): BrowserSyncInstance; - /** - * Get a single instance by name. This is useful if you have your build scripts in separate files - * @param name the identifier used for retrieval - */ - get(name: string): BrowserSyncInstance; - /** - * Check if an instance has been created. - * @param name the name of the instance - */ - has(name: string): boolean; - } - - interface BrowserSyncInstance { - /** the name of this instance of browser-sync */ - name: string; - /** - * Start the Browsersync service. This will launch a server, proxy or start the snippet mode - * depending on your use-case. - */ - init(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; - /** - * Reload the browser - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(): void; - /** - * Reload a single file - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(file: string): void; - /** - * Reload multiple files - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(files: string[]): void; - /** - * The reload method will inform all browsers about changed files and will either cause the browser - * to refresh, or inject the files where possible. - */ - reload(options: { stream: boolean }): NodeJS.ReadWriteStream; - /** - * The stream method returns a transform stream and can act once or on many files. - * @param opts Configuration for the stream method - */ - stream(opts?: StreamOptions): NodeJS.ReadWriteStream; - /** - * Helper method for browser notifications - * @param message Can be a simple message such as 'Connected' or HTML - * @param timeout How long the message will remain in the browser. @since 1.3.0 - */ - notify(message: string, timeout?: number): void; - /** - * This method will close any running server, stop file watching & exit the current process. - */ - exit(): void; - /** - * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system - */ - watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any) - : NodeJS.EventEmitter; - /** - * Method to pause file change events - */ - pause(): void; - /** - * Method to resume paused watchers - */ - resume(): void; - /** - * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use - * this to emit your own events, such as changed files, logging etc. - */ - emitter: NodeJS.EventEmitter; - /** - * A simple true/false flag that you can use to determine if there's a currently-running Browsersync instance. - */ - active: boolean; - /** - * A simple true/false flag to determine if the current instance is paused - */ - paused: boolean; - } +declare namespace browserSync { + interface Options { + /** + * Browsersync includes a user-interface that is accessed via a separate port. The UI allows to controls + * all devices, push sync updates and much more. + * + * port - Default: 3001 + * weinre.port - Default: 8080 + * Note: requires at least version 2.0.0 + */ + ui?: UIOptions; + /** + * Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS + * & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob + * patterns. + * Default: false + */ + files?: string | string[]; + /** + * File watching options that get passed along to Chokidar. Check their docs for available options + * Default: undefined + * Note: requires at least version 2.6.0 + */ + watchOptions?: chokidar.WatchOptions; + /** + * Use the built-in static server for basic HTML/JS/CSS websites. + * Default: false + */ + server?: ServerOptions; + /** + * Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site. + * target - Default: undefined + * ws - Default: undefined + * middleware - Default: undefined + * reqHeaders - Default: undefined + * proxyRes - Default: undefined + */ + proxy?: string | boolean | ProxyOptions; + /** + * Use a specific port (instead of the one auto-detected by Browsersync) + * Default: 3000 + */ + port?: number; + /** + * Add additional directories from which static files should be served. + * Should only be used in proxy or snippet mode. + * Default: [] + * Note: requires at least version 2.8.0 + */ + serveStatic?: string[]; + /** + * Enable https for localhost development. + * Note - this is not needed for proxy option as it will be inferred from your target url. + * Note: requires at least version 1.3.0 + */ + https?: boolean; + /** + * Clicks, Scrolls & Form inputs on any device will be mirrored to all others. + * clicks - Default: true + * scroll - Default: true + * forms - Default: true + */ + ghostMode?: GhostOptions | boolean; + /** + * Can be either "info", "debug", "warn", or "silent" + * Default: info + */ + logLevel?: string; + /** + * Change the console logging prefix. Useful if you're creating your own project based on Browsersync + * Default: BS + * Note: requires at least version 1.5.1 + */ + logPrefix?: string; + /** + * Whether or not to log connections + * Default: false + */ + logConnections?: boolean; + /** + * Whether or not to log information about changed files + * Default: false + */ + logFileChanges?: boolean; + /** + * Log the snippet to the console when you're in snippet mode (no proxy/server) + * Default: true + * Note: requires at least version 1.5.2 + */ + logSnippet?: boolean; + /** + * You can control how the snippet is injected onto each page via a custom regex + function. + * You can also provide patterns for certain urls that should be ignored from the snippet injection. + * Note: requires at least version 2.0.0 + */ + snippetOptions?: SnippetOptions; + /** + * Add additional HTML rewriting rules. + * Default: false + * Note: requires at least version 2.4.0 + */ + rewriteRules?: boolean | RewriteRules[]; + /** + * Tunnel the Browsersync server through a random Public URL + * Default: null + */ + tunnel?: string | boolean; + /** + * Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're + * working offline, you can reduce start-up time by setting this option to false + */ + online?: boolean; + /** + * Default: true + * Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. + * Can be true, local, external, ui, ui-external, tunnel or false + */ + open?: string | boolean; + /** + * The browser(s) to open + * Default: default + */ + browser?: string | string[]; + /** + * Requires an internet connection - useful for services such as Typekit as it allows you to configure + * domains such as *.xip.io in your kit settings + * Default: false + */ + xip?: boolean; + /** + * Reload each browser when Browsersync is restarted. + * Default: false + */ + reloadOnRestart?: boolean; + /** + * The small pop-over notifications in the browser are not always needed/wanted. + * Default: true + */ + notify?: boolean; + /** + * scrollProportionally: false // Sync viewports to TOP position + * Default: true + */ + scrollProportionally?: boolean; + /** + * How often to send scroll events + * Default: 0 + */ + scrollThrottle?: number; + /** + * Decide which technique should be used to restore scroll position following a reload. + * Can be window.name or cookie + * Default: 'window.name' + */ + scrollRestoreTechnique?: string; + /** + * Sync the scroll position of any element on the page. Add any amount of CSS selectors + * Default: [] + * Note: requires at least version 2.9.0 + */ + scrollElements?: string[]; + /** + * Default: [] + * Note: requires at least version 2.9.0 + * Sync the scroll position of any element on the page - where any scrolled element will cause + * all others to match scroll position. This is helpful when a breakpoint alters which element + * is actually scrolling + */ + scrollElementMapping?: string[]; + /** + * Time, in milliseconds, to wait before instructing the browser to reload/inject following a file + * change event + * Default: 0 + */ + reloadDelay?: number; + /** + * Restrict the frequency in which browser:reload events can be emitted to connected clients + * Default: 0 + * Note: requires at least version 2.6.0 + */ + reloadDebounce?: number; + /** + * User provided plugins + * Default: [] + * Note: requires at least version 2.6.0 + */ + plugins?: any[]; + /** + * Whether to inject changes (rather than a page refresh) + * Default: true + */ + injectChanges?: boolean; + /** + * The initial path to load + */ + startPath?: string; + /** + * Whether to minify the client script + * Default: true + */ + minify?: boolean; + /** + * Override host detection if you know the correct IP to use + */ + host?: string; + /** + * Send file-change events to the browser + * Default: true + */ + codeSync?: boolean; + /** + * Append timestamps to injected files + * Default: true + */ + timestamps?: boolean; + /** + * Alter the script path for complete control over where the Browsersync Javascript is served + * from. Whatever you return from this function will be used as the script path. + * Note: requires at least version 1.5.0 + */ + scriptPath?: (path: string) => string; + /** + * Configure the Socket.IO path and namespace & domain to avoid collisions. + * path - Default: "/browser-sync/socket.io" + * clientPath - Default: "/browser-sync" + * namespace - Default: "/browser-sync" + * domain - Default: undefined + * port - Default: undefined + * clients.heartbeatTimeout - Default: 5000 + * Note: requires at least version 1.6.2 + */ + socket?: SocketOptions; + middleware?: MiddlewareHandler | MiddlewareHandler[]; } - const browserSync: browserSync.BrowserSyncStatic; - export = browserSync; + interface Hash { + [path: string]: T; + } + + interface UIOptions { + /** set the default port */ + port?: number; + /** set the default weinre port */ + weinre?: { + port?: number; + }; + } + + interface ServerOptions { + /** set base directory */ + baseDir?: string | string[]; + /** enable directory listing */ + directory?: boolean; + /** set index filename */ + index?: string; + /** + * key-value object hash, where the key is the url to match, + * and the value is the folder to serve (relative to your working directory) + */ + routes?: Hash; + /** configure custom middleware */ + middleware?: MiddlewareHandler[]; + } + + interface ProxyOptions { + target?: string; + middleware?: MiddlewareHandler; + ws: boolean; + reqHeaders: (config: any) => Hash; + proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any; + } + + interface MiddlewareHandler { + (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; + } + + interface GhostOptions { + clicks?: boolean; + scroll?: boolean; + forms?: boolean; + } + + interface SnippetOptions { + ignorePaths?: string; + rule?: { match?: RegExp; fn?: (snippet: string, match: string) => any }; + } + + interface SocketOptions { + path?: string; + clientPath?: string; + namespace?: string; + domain?: string; + port?: number; + clients?: { heartbeatTimeout?: number; }; + } + + interface RewriteRules { + match: RegExp; + fn: (match: string) => string; + } + + interface StreamOptions { + once?: boolean; + match?: mm.Pattern | mm.Pattern[]; + } + + interface BrowserSyncStatic extends BrowserSyncInstance { + /** + * Start the Browsersync service. This will launch a server, proxy or start the snippet mode + * depending on your use-case. + */ + (config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; + /** + * Create a Browsersync instance + * @param name an identifier that can used for retrieval later + */ + create(name?: string): BrowserSyncInstance; + /** + * Get a single instance by name. This is useful if you have your build scripts in separate files + * @param name the identifier used for retrieval + */ + get(name: string): BrowserSyncInstance; + /** + * Check if an instance has been created. + * @param name the name of the instance + */ + has(name: string): boolean; + } + + interface BrowserSyncInstance { + /** the name of this instance of browser-sync */ + name: string; + /** + * Start the Browsersync service. This will launch a server, proxy or start the snippet mode + * depending on your use-case. + */ + init(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance; + /** + * Reload the browser + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(): void; + /** + * Reload a single file + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(file: string): void; + /** + * Reload multiple files + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(files: string[]): void; + /** + * The reload method will inform all browsers about changed files and will either cause the browser + * to refresh, or inject the files where possible. + */ + reload(options: { stream: boolean }): NodeJS.ReadWriteStream; + /** + * The stream method returns a transform stream and can act once or on many files. + * @param opts Configuration for the stream method + */ + stream(opts?: StreamOptions): NodeJS.ReadWriteStream; + /** + * Helper method for browser notifications + * @param message Can be a simple message such as 'Connected' or HTML + * @param timeout How long the message will remain in the browser. @since 1.3.0 + */ + notify(message: string, timeout?: number): void; + /** + * This method will close any running server, stop file watching & exit the current process. + */ + exit(): void; + /** + * Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system + */ + watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any) + : NodeJS.EventEmitter; + /** + * Method to pause file change events + */ + pause(): void; + /** + * Method to resume paused watchers + */ + resume(): void; + /** + * The internal Event Emitter used by the running Browsersync instance (if there is one). You can use + * this to emit your own events, such as changed files, logging etc. + */ + emitter: NodeJS.EventEmitter; + /** + * A simple true/false flag that you can use to determine if there's a currently-running Browsersync instance. + */ + active: boolean; + /** + * A simple true/false flag to determine if the current instance is paused + */ + paused: boolean; + } } + +declare const browserSync: browserSync.BrowserSyncStatic; +export = browserSync; diff --git a/bs58/bs58.d.ts b/bs58/bs58.d.ts index 00ebbbfec7..d0fd579cb2 100644 --- a/bs58/bs58.d.ts +++ b/bs58/bs58.d.ts @@ -5,10 +5,9 @@ /// -declare module "bs58" { - namespace base58 {} - let base58: BaseX.BaseConverter; +declare namespace base58 { } - export = base58; -} +declare let base58: BaseX.BaseConverter; + +export = base58; diff --git a/bson/bson.d.ts b/bson/bson.d.ts index c311103ff3..ee835175de 100644 --- a/bson/bson.d.ts +++ b/bson/bson.d.ts @@ -6,128 +6,126 @@ /// -declare module 'bson' { - - namespace bson { - - export module BSONPure { - - export interface DeserializeOptions { - /** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. */ - evalFunctions?: boolean; - /** {Boolean, default:false}, cache evaluated functions for reuse. */ - cacheFunctions?: boolean; - /** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. */ - cacheFunctionsCrc32?: boolean; - /** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. */ - promoteBuffers?: boolean; - } - export class BSON { - /** - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object (ignore). - * @param {Boolean} serializeFunctions serialize the javascript functions (default:false) - * @return {Buffer} returns a TypedArray or Array depending on what your browser supports - */ - serialize(object: any, checkKeys?: boolean, asBuffer?: boolean, serializeFunctions?: boolean): Buffer; - deserialize(buffer: Buffer, options?: DeserializeOptions, isArray?: boolean): any; - } - export interface Binary {} - export interface BinaryStatic { - SUBTYPE_DEFAULT: number; - SUBTYPE_FUNCTION: number; - SUBTYPE_BYTE_ARRAY: number; - SUBTYPE_UUID_OLD: number; - SUBTYPE_UUID: number; - SUBTYPE_MD5: number; - SUBTYPE_USER_DEFINED: number; +declare namespace bson { - new (buffer: Buffer, subType?: number): Binary; - } - export let Binary: BinaryStatic; + export module BSONPure { - export interface Code {} - export interface CodeStatic { - new (code: string | Function, scope?: any): Code; - } - export let Code: CodeStatic; + export interface DeserializeOptions { + /** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. */ + evalFunctions?: boolean; + /** {Boolean, default:false}, cache evaluated functions for reuse. */ + cacheFunctions?: boolean; + /** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. */ + cacheFunctionsCrc32?: boolean; + /** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. */ + promoteBuffers?: boolean; + } + export class BSON { + /** + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object (ignore). + * @param {Boolean} serializeFunctions serialize the javascript functions (default:false) + * @return {Buffer} returns a TypedArray or Array depending on what your browser supports + */ + serialize(object: any, checkKeys?: boolean, asBuffer?: boolean, serializeFunctions?: boolean): Buffer; + deserialize(buffer: Buffer, options?: DeserializeOptions, isArray?: boolean): any; + } - export interface DBRef {} - export interface DBRefStatic { - new (namespace: string, oid: ObjectID, db?: string): DBRef; - } - export let DBRef: DBRefStatic; - export interface Double {} - export interface DoubleStatic { - new (value: number): Double; - } - export let Double: DoubleStatic; + export interface Binary { } + export interface BinaryStatic { + SUBTYPE_DEFAULT: number; + SUBTYPE_FUNCTION: number; + SUBTYPE_BYTE_ARRAY: number; + SUBTYPE_UUID_OLD: number; + SUBTYPE_UUID: number; + SUBTYPE_MD5: number; + SUBTYPE_USER_DEFINED: number; - export interface Long {} - export interface LongStatic { - new (low: number, high: number): Long; - fromInt(i: number): Long; - fromNumber(n: number): Long; - fromBits(lowBits: number, highBits: number): Long; - fromString(s: string, opt_radix?: number): Long; - } - export let Long: LongStatic; + new (buffer: Buffer, subType?: number): Binary; + } + export let Binary: BinaryStatic; - export interface MaxKey {} - export interface MaxKeyStatic { - new (): MaxKey; - } - export let MaxKey: MaxKeyStatic; + export interface Code { } + export interface CodeStatic { + new (code: string | Function, scope?: any): Code; + } + export let Code: CodeStatic; - export interface MinKey {} - export interface MinKeyStatic { - new (): MinKey; - } - export let MinKey: MinKeyStatic; + export interface DBRef { } + export interface DBRefStatic { + new (namespace: string, oid: ObjectID, db?: string): DBRef; + } + export let DBRef: DBRefStatic; - export interface ObjectID {} - export interface ObjectIDStatic { - new (id?: number | string | ObjectID): ObjectID; - createPk(): ObjectID; - createFromTime(time: number): ObjectID; - createFromHexString(hexString: string): ObjectID; - isValid(id: number | string | ObjectID): boolean; - } - export let ObjectID: ObjectIDStatic; - export let ObjectId: ObjectIDStatic; + export interface Double { } + export interface DoubleStatic { + new (value: number): Double; + } + export let Double: DoubleStatic; - export interface BSONRegExp {} - export interface BSONRegExpStatic { - new (pattern: string, options: string): BSONRegExp; - } - export let BSONRegExp: BSONRegExpStatic; + export interface Long { } + export interface LongStatic { + new (low: number, high: number): Long; + fromInt(i: number): Long; + fromNumber(n: number): Long; + fromBits(lowBits: number, highBits: number): Long; + fromString(s: string, opt_radix?: number): Long; + } + export let Long: LongStatic; - export interface Symbol {} - export interface SymbolStatic { - new (value: string): Symbol; - } - export let Symbol: SymbolStatic; + export interface MaxKey { } + export interface MaxKeyStatic { + new (): MaxKey; + } + export let MaxKey: MaxKeyStatic; - export interface Timestamp {} - export interface TimestampStatic { - new (low: number, high: number): Timestamp; - fromInt(i: number): Timestamp; - fromNumber(n: number): Timestamp; - fromBits(lowBits: number, highBits: number): Timestamp; - fromString(s: string, opt_radix?: number): Timestamp; - } - export let Timestamp: TimestampStatic; + export interface MinKey { } + export interface MinKeyStatic { + new (): MinKey; + } + export let MinKey: MinKeyStatic; - } + export interface ObjectID { } + export interface ObjectIDStatic { + new (id?: number | string | ObjectID): ObjectID; + createPk(): ObjectID; + createFromTime(time: number): ObjectID; + createFromHexString(hexString: string): ObjectID; + isValid(id: number | string | ObjectID): boolean; + } + export let ObjectID: ObjectIDStatic; + export let ObjectId: ObjectIDStatic; - export let BSONNative: typeof BSONPure; + export interface BSONRegExp { } + export interface BSONRegExpStatic { + new (pattern: string, options: string): BSONRegExp; + } + export let BSONRegExp: BSONRegExpStatic; - } + export interface Symbol { } + export interface SymbolStatic { + new (value: string): Symbol; + } + export let Symbol: SymbolStatic; + + export interface Timestamp { } + export interface TimestampStatic { + new (low: number, high: number): Timestamp; + fromInt(i: number): Timestamp; + fromNumber(n: number): Timestamp; + fromBits(lowBits: number, highBits: number): Timestamp; + fromString(s: string, opt_radix?: number): Timestamp; + } + export let Timestamp: TimestampStatic; + + } + + export let BSONNative: typeof BSONPure; - export = bson; } +export = bson; diff --git a/buffer-compare/buffer-compare.d.ts b/buffer-compare/buffer-compare.d.ts index 47bd3fcbec..bd61febdb7 100644 --- a/buffer-compare/buffer-compare.d.ts +++ b/buffer-compare/buffer-compare.d.ts @@ -3,15 +3,14 @@ // Definitions by: Ilya Mochalov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "buffer-compare" { - interface List { - [index: number]: any; - length: number - } - function compare(cmp: List, to: List): number; - function compare(cmp: T, to: T): number; - function compare(cmp: C, to: T): number; - - export = compare; +interface List { + [index: number]: any; + length: number } + +declare function compare(cmp: List, to: List): number; +declare function compare(cmp: T, to: T): number; +declare function compare(cmp: C, to: T): number; + +export = compare; diff --git a/buffer-equal/buffer-equal.d.ts b/buffer-equal/buffer-equal.d.ts index b3ede1fc1d..34ae5d737e 100644 --- a/buffer-equal/buffer-equal.d.ts +++ b/buffer-equal/buffer-equal.d.ts @@ -5,7 +5,6 @@ /// -declare module 'buffer-equal' { - function bufferEqual(actual:Buffer, expected:Buffer): boolean; - export = bufferEqual; -} + +declare function bufferEqual(actual: Buffer, expected: Buffer): boolean; +export = bufferEqual; diff --git a/buffers/buffers.d.ts b/buffers/buffers.d.ts index e2ca5c2708..d817ebd407 100644 --- a/buffers/buffers.d.ts +++ b/buffers/buffers.d.ts @@ -5,32 +5,30 @@ /// -declare module "buffers" { - interface BuffersStatics { - new (bufs?: Buffer[]|Buffers): Buffers; - (bufs?: Buffer[]| Buffers): Buffers; - prototype: Buffers; - } - - interface Buffers { - buffers: Buffer[]; - length: number; - - push(...items: Buffer[]): number; - unshift(...items: Buffer[]): number; - slice(i?: number, j?: number): Buffer; - splice(i: number, howMany?: number, ...items: Buffer[]): Buffers; - copy(dst: Buffer, dstStart?: number, start?: number, end?: number): number; - get(i: number): any; - set(i: number, b: any): void; - indexOf(needle: string|Buffer, offset?: number): number; - toBuffer(): Buffer; - toString(encoding?: any, start?: number, end?: number): string; - } - - var Buffers: BuffersStatics; - - export = Buffers; +interface BuffersStatics { + new (bufs?: Buffer[] | Buffers): Buffers; + (bufs?: Buffer[] | Buffers): Buffers; + prototype: Buffers; } + +interface Buffers { + buffers: Buffer[]; + length: number; + + push(...items: Buffer[]): number; + unshift(...items: Buffer[]): number; + slice(i?: number, j?: number): Buffer; + splice(i: number, howMany?: number, ...items: Buffer[]): Buffers; + copy(dst: Buffer, dstStart?: number, start?: number, end?: number): number; + get(i: number): any; + set(i: number, b: any): void; + indexOf(needle: string | Buffer, offset?: number): number; + toBuffer(): Buffer; + toString(encoding?: any, start?: number, end?: number): string; +} + +declare var Buffers: BuffersStatics; + +export = Buffers; diff --git a/bunyan-logentries/bunyan-logentries.d.ts b/bunyan-logentries/bunyan-logentries.d.ts index bc91174dc1..dbd167dfa6 100644 --- a/bunyan-logentries/bunyan-logentries.d.ts +++ b/bunyan-logentries/bunyan-logentries.d.ts @@ -6,12 +6,11 @@ /// /// -declare module "bunyan-logentries" { - import bunyan = require("bunyan"); - interface StreamOptions { +import bunyan = require("bunyan"); + +interface StreamOptions { token: string; - } - - export function createStream(options: StreamOptions): NodeJS.WritableStream; } + +declare export function createStream(options: StreamOptions): NodeJS.WritableStream; diff --git a/bunyan-prettystream/bunyan-prettystream.d.ts b/bunyan-prettystream/bunyan-prettystream.d.ts index 297e63731c..3a4e5a00f4 100644 --- a/bunyan-prettystream/bunyan-prettystream.d.ts +++ b/bunyan-prettystream/bunyan-prettystream.d.ts @@ -5,26 +5,25 @@ /// -declare module "bunyan-prettystream" { - import stream = require("stream"); - class PrettyStream extends stream.Writable { - /** - * @param options.mode Output format, can be either `long`, `short`, or `dev`, - * defaults to `long`. - * @param options.useColor Indicates whether or not output should be colored, - * defaults to `true`. - */ - constructor(options?: { mode?: string; useColor?: boolean }); - /** - * Pipes data from this stream to another. - * - * @param destination Stream to write data to. - * @param options.end Indicates whether `end()` should be called on the `destination` - * stream when this stream emits `end`, defaults to `true`. - * @return The `destination` stream. - */ - pipe(destination: T, options?: { end?: boolean; }): T; - } - export = PrettyStream; -} \ No newline at end of file +import stream = require("stream"); +declare class PrettyStream extends stream.Writable { + /** + * @param options.mode Output format, can be either `long`, `short`, or `dev`, + * defaults to `long`. + * @param options.useColor Indicates whether or not output should be colored, + * defaults to `true`. + */ + constructor(options?: { mode?: string; useColor?: boolean }); + + /** + * Pipes data from this stream to another. + * + * @param destination Stream to write data to. + * @param options.end Indicates whether `end()` should be called on the `destination` + * stream when this stream emits `end`, defaults to `true`. + * @return The `destination` stream. + */ + pipe(destination: T, options?: { end?: boolean; }): T; +} +export = PrettyStream; diff --git a/bunyan/bunyan.d.ts b/bunyan/bunyan.d.ts index dd569301f5..ce7b17ab62 100644 --- a/bunyan/bunyan.d.ts +++ b/bunyan/bunyan.d.ts @@ -5,101 +5,100 @@ /// -declare module "bunyan" { - import { EventEmitter } from 'events'; - class Logger extends EventEmitter { - constructor(options:LoggerOptions); - addStream(stream:Stream):void; - addSerializers(serializers:Serializers):void; - child(options:LoggerOptions, simple?:boolean):Logger; - child(obj:Object, simple?:boolean):Logger; - reopenFileStreams():void; +import { EventEmitter } from 'events'; - level():string|number; - level(value: number | string):void; - levels(name: number | string, value: number | string):void; +declare class Logger extends EventEmitter { + constructor(options: LoggerOptions); + addStream(stream: Stream): void; + addSerializers(serializers: Serializers): void; + child(options: LoggerOptions, simple?: boolean): Logger; + child(obj: Object, simple?: boolean): Logger; + reopenFileStreams(): void; - fields:any; - src:boolean; + level(): string | number; + level(value: number | string): void; + levels(name: number | string, value: number | string): void; - trace(error:Error, format?:any, ...params:any[]):void; - trace(buffer:Buffer, format?:any, ...params:any[]):void; - trace(obj:Object, format?:any, ...params:any[]):void; - trace(format:string, ...params:any[]):void; - debug(error:Error, format?:any, ...params:any[]):void; - debug(buffer:Buffer, format?:any, ...params:any[]):void; - debug(obj:Object, format?:any, ...params:any[]):void; - debug(format:string, ...params:any[]):void; - info(error:Error, format?:any, ...params:any[]):void; - info(buffer:Buffer, format?:any, ...params:any[]):void; - info(obj:Object, format?:any, ...params:any[]):void; - info(format:string, ...params:any[]):void; - warn(error:Error, format?:any, ...params:any[]):void; - warn(buffer:Buffer, format?:any, ...params:any[]):void; - warn(obj:Object, format?:any, ...params:any[]):void; - warn(format:string, ...params:any[]):void; - error(error:Error, format?:any, ...params:any[]):void; - error(buffer:Buffer, format?:any, ...params:any[]):void; - error(obj:Object, format?:any, ...params:any[]):void; - error(format:string, ...params:any[]):void; - fatal(error:Error, format?:any, ...params:any[]):void; - fatal(buffer:Buffer, format?:any, ...params:any[]):void; - fatal(obj:Object, format?:any, ...params:any[]):void; - fatal(format:string, ...params:any[]):void; - } + fields: any; + src: boolean; - interface LoggerOptions { - name: string; - streams?: Stream[]; - level?: string | number; - stream?: NodeJS.WritableStream; - serializers?: Serializers; - src?: boolean; - } - - interface Serializers { - [key:string]: (input:any) => string; - } - - interface Stream { - type?: string; - level?: number | string; - path?: string; - stream?: NodeJS.WritableStream | Stream; - closeOnExit?: boolean; - period?: string; - count?: number; - } - - export var stdSerializers:Serializers; - - export var TRACE:number; - export var DEBUG:number; - export var INFO:number; - export var WARN:number; - export var ERROR:number; - export var FATAL:number; - - export function resolveLevel(value: number | string):number; - - export function createLogger(options:LoggerOptions):Logger; - - class RingBuffer extends EventEmitter { - constructor(options:RingBufferOptions); - - writable:boolean; - records:any[]; - - write(record:any):void; - end(record?:any):void; - destroy():void; - destroySoon():void; - } - - interface RingBufferOptions { - limit?: number; - } - - export function safeCycles():(key:string, value:any) => any; + trace(error: Error, format?: any, ...params: any[]): void; + trace(buffer: Buffer, format?: any, ...params: any[]): void; + trace(obj: Object, format?: any, ...params: any[]): void; + trace(format: string, ...params: any[]): void; + debug(error: Error, format?: any, ...params: any[]): void; + debug(buffer: Buffer, format?: any, ...params: any[]): void; + debug(obj: Object, format?: any, ...params: any[]): void; + debug(format: string, ...params: any[]): void; + info(error: Error, format?: any, ...params: any[]): void; + info(buffer: Buffer, format?: any, ...params: any[]): void; + info(obj: Object, format?: any, ...params: any[]): void; + info(format: string, ...params: any[]): void; + warn(error: Error, format?: any, ...params: any[]): void; + warn(buffer: Buffer, format?: any, ...params: any[]): void; + warn(obj: Object, format?: any, ...params: any[]): void; + warn(format: string, ...params: any[]): void; + error(error: Error, format?: any, ...params: any[]): void; + error(buffer: Buffer, format?: any, ...params: any[]): void; + error(obj: Object, format?: any, ...params: any[]): void; + error(format: string, ...params: any[]): void; + fatal(error: Error, format?: any, ...params: any[]): void; + fatal(buffer: Buffer, format?: any, ...params: any[]): void; + fatal(obj: Object, format?: any, ...params: any[]): void; + fatal(format: string, ...params: any[]): void; } + +interface LoggerOptions { + name: string; + streams?: Stream[]; + level?: string | number; + stream?: NodeJS.WritableStream; + serializers?: Serializers; + src?: boolean; +} + +interface Serializers { + [key: string]: (input: any) => string; +} + +interface Stream { + type?: string; + level?: number | string; + path?: string; + stream?: NodeJS.WritableStream | Stream; + closeOnExit?: boolean; + period?: string; + count?: number; +} + +declare export var stdSerializers: Serializers; + +declare export var TRACE: number; +declare export var DEBUG: number; +declare export var INFO: number; +declare export var WARN: number; +declare export var ERROR: number; +declare export var FATAL: number; + +declare export function resolveLevel(value: number | string): number; + +declare export function createLogger(options: LoggerOptions): Logger; + +declare class RingBuffer extends EventEmitter { + constructor(options: RingBufferOptions); + + writable: boolean; + records: any[]; + + write(record: any): void; + end(record?: any): void; + destroy(): void; + destroySoon(): void; +} + +interface RingBufferOptions { + limit?: number; +} + +declare export function safeCycles(): (key: string, value: any) => any; diff --git a/byline/byline.d.ts b/byline/byline.d.ts index 48ddd2d57a..95f035f06e 100644 --- a/byline/byline.d.ts +++ b/byline/byline.d.ts @@ -5,34 +5,33 @@ /// -declare module "byline" { - import stream = require("stream"); - export interface LineStreamOptions extends stream.TransformOptions { - keepEmptyLines?: boolean; - } +import stream = require("stream"); - export interface LineStream extends stream.Transform { - } - - export interface LineStreamCreatable extends LineStream { - new (options?:LineStreamOptions):LineStream - } - - //TODO is it possible to declare static factory functions without name (directly on the module) - // - // JS: - // // convinience API - // module.exports = function(readStream, options) { - // return module.exports.createStream(readStream, options); - // }; - // - // TS: - // ():LineStream; // same as createStream():LineStream - // (stream:stream.Stream, options?:LineStreamOptions):LineStream; // same as createStream(stream, options?):LineStream - - export function createStream():LineStream; - export function createStream(stream:NodeJS.ReadableStream, options?:LineStreamOptions):LineStream; - - export var LineStream:LineStreamCreatable; +export interface LineStreamOptions extends stream.TransformOptions { + keepEmptyLines?: boolean; } + +export interface LineStream extends stream.Transform { +} + +export interface LineStreamCreatable extends LineStream { + new (options?: LineStreamOptions): LineStream +} + +//TODO is it possible to declare static factory functions without name (directly on the module) +// +// JS: +// // convinience API +// module.exports = function(readStream, options) { +// return module.exports.createStream(readStream, options); +// }; +// +// TS: +// ():LineStream; // same as createStream():LineStream +// (stream:stream.Stream, options?:LineStreamOptions):LineStream; // same as createStream(stream, options?):LineStream + +declare export function createStream(): LineStream; +declare export function createStream(stream: NodeJS.ReadableStream, options?: LineStreamOptions): LineStream; + +declare export var LineStream: LineStreamCreatable; diff --git a/bytes/bytes.d.ts b/bytes/bytes.d.ts index b99ebee7c6..37a25897a0 100644 --- a/bytes/bytes.d.ts +++ b/bytes/bytes.d.ts @@ -3,60 +3,59 @@ // Definitions by: Zhiyuan Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'bytes' { + + +/** + *Convert the given value in bytes into a string. + * + * @param {number} value + * @param {{ + * thousandsSeparator: [string] + * }} [options] bytes options. + * + * @returns {string} + */ +declare function bytes(value: number, options?: { thousandsSeparator: string }): string; + +/** + *Parse string to an integer in bytes. + * + * @param {string} value + * @returns {number} + */ +declare function bytes(value: string): number; + +declare namespace bytes { /** - *Convert the given value in bytes into a string. + * Format the given value in bytes into a string. + * + * If the value is negative, take Math.abs(). If it is a float, + * it is rounded. * * @param {number} value - * @param {{ - * thousandsSeparator: [string] - * }} [options] bytes options. - * - * @returns {string} + * @param {BytesFormatOptions} [options] */ - function bytes(value: number, options?: { thousandsSeparator: string }): string; + + function format(value: number, options?: { thousandsSeparator: string }): string; /** - *Parse string to an integer in bytes. + * Just return the input number value. + * + * @param {number} value + * @return {number} + */ + function parse(value: number): number; + + /** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. * * @param {string} value - * @returns {number} + * @return {number} */ - function bytes(value: string): number; - - namespace bytes { - - /** - * Format the given value in bytes into a string. - * - * If the value is negative, take Math.abs(). If it is a float, - * it is rounded. - * - * @param {number} value - * @param {BytesFormatOptions} [options] - */ - - function format(value: number, options?: { thousandsSeparator: string }): string; - - /** - * Just return the input number value. - * - * @param {number} value - * @return {number} - */ - function parse(value: number): number; - - /** - * Parse the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {string} value - * @return {number} - */ - function parse(value: string): number; - } - - export = bytes; + function parse(value: string): number; } + +export = bytes; diff --git a/callsite/callsite.d.ts b/callsite/callsite.d.ts index ffaa5d7e6f..780ca8b0ab 100644 --- a/callsite/callsite.d.ts +++ b/callsite/callsite.d.ts @@ -3,28 +3,27 @@ // Definitions by: newclear // Definitions: https://github.com/newclear/DefinitelyTyped -declare module "callsite" { - namespace Callsite{ - interface CallSite { - getThis(): any; - getTypeName(): string; - getFunctionName(): string; - getMethodName(): string; - getFileName(): string; - getLineNumber(): number; - getColumnNumber(): number; - getFunction(): Function; - getEvalOrigin(): string; - isNative(): boolean; - isToplevel(): boolean; - isEval(): boolean; - isConstructor(): boolean; - } +declare namespace Callsite { + + interface CallSite { + getThis(): any; + getTypeName(): string; + getFunctionName(): string; + getMethodName(): string; + getFileName(): string; + getLineNumber(): number; + getColumnNumber(): number; + getFunction(): Function; + getEvalOrigin(): string; + isNative(): boolean; + isToplevel(): boolean; + isEval(): boolean; + isConstructor(): boolean; } - - function Callsite(): Callsite.CallSite[]; - - export = Callsite; } + +declare function Callsite(): Callsite.CallSite[]; + +export = Callsite; diff --git a/camel-case/camel-case.d.ts b/camel-case/camel-case.d.ts index e2a4777f21..1345063e82 100644 --- a/camel-case/camel-case.d.ts +++ b/camel-case/camel-case.d.ts @@ -3,7 +3,6 @@ // Definitions by: Sam Saint-Pettersen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "camel-case" { - function camelCase(string: string, locale?: string): string; - export = camelCase; -} + +declare function camelCase(string: string, locale?: string): string; +export = camelCase; diff --git a/camelcase/camelcase.d.ts b/camelcase/camelcase.d.ts index 2edd71948a..79705dd423 100644 --- a/camelcase/camelcase.d.ts +++ b/camelcase/camelcase.d.ts @@ -3,8 +3,7 @@ // Definitions by: Sam Verschueren // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "camelcase" { - function camelcase(...args: string[]): string; - namespace camelcase {} - export = camelcase; -} + +declare function camelcase(...args: string[]): string; +declare namespace camelcase { } +export = camelcase; diff --git a/camo/camo.d.ts b/camo/camo.d.ts index 70f9817ffb..4823480400 100644 --- a/camo/camo.d.ts +++ b/camo/camo.d.ts @@ -3,137 +3,135 @@ // Definitions by: Lucas Matías Ciruzzi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "camo" { - type TypeOrArray = Type | Type[]; - /** - * Supported type constructors for document properties - */ - export type SchemaTypeConstructor = - TypeOrArray | - TypeOrArray | - TypeOrArray | - TypeOrArray | - TypeOrArray | - TypeOrArray; +type TypeOrArray = Type | Type[]; - /** - * Supported types for document properties - */ - export type SchemaType = TypeOrArray; +/** + * Supported type constructors for document properties + */ +export type SchemaTypeConstructor = + TypeOrArray | + TypeOrArray | + TypeOrArray | + TypeOrArray | + TypeOrArray | + TypeOrArray; - /** - * Document property with options - */ - export interface SchemaTypeOptions { - /** - * Type of data - */ - type: SchemaTypeConstructor; - /** - * Default value - */ - default?: Type; - /** - * Min value (only with Number) - */ - min?: number; - /** - * Max value (only with Number) - */ - max?: number; - /** - * Posible options - */ - choices?: Type[]; - /** - * RegEx to match value - */ - match?: RegExp; - /** - * Validation function - * - * @param value Value taken - * @returns true (validation ok) or false (validation wrong) - */ - validate?(value: Type): boolean; - /** - * Unique value (like ids) - */ - unique?: boolean; - /** - * Required field - */ - required?: boolean; - } - - /** - * Document property type or options - */ - export type SchemaTypeExtended = SchemaTypeConstructor | SchemaTypeOptions; - - /** - * Schema passed to Document.create() - */ - interface DocumentSchema { - /** - * Index signature - */ - [property: string]: SchemaType; - /** - * Document id - */ - _id?: string; - } - - /** - * Camo document instance - */ - class DocumentInstance { - public save(): Promise; - public loadOne(): Promise; - public loadMany(): Promise; - public delete(): Promise; - public deleteOne(): Promise; - public deleteMany(): Promise; - public loadOneAndDelete(): Promise; - public count(): Promise; - public preValidate(): Promise; - public postValidate(): Promise; - public preSave(): Promise; - public postSave(): Promise; - public preDelete(): Promise; - public postDelete(): Promise; - } - - /** - * Camo document - */ - export class Document { - /** - * Index signature - */ - [property: string]: SchemaTypeExtended | string | DocumentInstance; - /** - * Static method to define the collection name - * - * @returns The collection name - */ - static collectionName(): string; - /** - * Creates a camo document instance - * - * @returns A camo document instance - */ - static create(schema: Schema): DocumentInstance; - } - - /** - * Connect function - * - * @param uri Connection URI - */ - export function connect (uri: string): Promise; +/** + * Supported types for document properties + */ +export type SchemaType = TypeOrArray; +/** + * Document property with options + */ +export interface SchemaTypeOptions { + /** + * Type of data + */ + type: SchemaTypeConstructor; + /** + * Default value + */ + default?: Type; + /** + * Min value (only with Number) + */ + min?: number; + /** + * Max value (only with Number) + */ + max?: number; + /** + * Posible options + */ + choices?: Type[]; + /** + * RegEx to match value + */ + match?: RegExp; + /** + * Validation function + * + * @param value Value taken + * @returns true (validation ok) or false (validation wrong) + */ + validate?(value: Type): boolean; + /** + * Unique value (like ids) + */ + unique?: boolean; + /** + * Required field + */ + required?: boolean; } + +/** + * Document property type or options + */ +export type SchemaTypeExtended = SchemaTypeConstructor | SchemaTypeOptions; + +/** + * Schema passed to Document.create() + */ +interface DocumentSchema { + /** + * Index signature + */ + [property: string]: SchemaType; + /** + * Document id + */ + _id?: string; +} + +/** + * Camo document instance + */ +declare class DocumentInstance { + public save(): Promise; + public loadOne(): Promise; + public loadMany(): Promise; + public delete(): Promise; + public deleteOne(): Promise; + public deleteMany(): Promise; + public loadOneAndDelete(): Promise; + public count(): Promise; + public preValidate(): Promise; + public postValidate(): Promise; + public preSave(): Promise; + public postSave(): Promise; + public preDelete(): Promise; + public postDelete(): Promise; +} + +/** + * Camo document + */ +declare export class Document { + /** + * Index signature + */ + [property: string]: SchemaTypeExtended | string | DocumentInstance; + /** + * Static method to define the collection name + * + * @returns The collection name + */ + static collectionName(): string; + /** + * Creates a camo document instance + * + * @returns A camo document instance + */ + static create(schema: Schema): DocumentInstance; +} + +/** + * Connect function + * + * @param uri Connection URI + */ +declare export function connect(uri: string): Promise; diff --git a/change-case/change-case.d.ts b/change-case/change-case.d.ts index d432db1c35..80ba8e3bec 100644 --- a/change-case/change-case.d.ts +++ b/change-case/change-case.d.ts @@ -3,37 +3,36 @@ // Definitions by: Asana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "change-case" { - function dot(s: string): string; - function dotCase(s: string): string; - function swap(s: string): string; - function swapCase(s: string): string; - function path(s: string): string; - function pathCase(s: string): string; - function upper(s: string): string; - function upperCase(s: string): string; - function lower(s: string): string; - function lowerCase(s: string): string; - function camel(s: string): string; - function camelCase(s: string): string; - function snake(s: string): string; - function snakeCase(s: string): string; - function title(s: string): string; - function titleCase(s: string): string; - function param(s: string): string; - function paramCase(s: string): string; - function pascal(s: string): string; - function pascalCase(s: string): string; - function constant(s: string): string; - function constantCase(s: string): string; - function sentence(s: string): string; - function sentenceCase(s: string): string; - function isUpper(s: string): boolean; - function isUpperCase(s: string): boolean; - function isLower(s: string): boolean; - function isLowerCase(s: string): boolean; - function ucFirst(s: string): string; - function upperCaseFirst(s: string): string; - function lcFirst(s: string): string; - function lowerCaseFirst(s: string): string; -} + +declare function dot(s: string): string; +declare function dotCase(s: string): string; +declare function swap(s: string): string; +declare function swapCase(s: string): string; +declare function path(s: string): string; +declare function pathCase(s: string): string; +declare function upper(s: string): string; +declare function upperCase(s: string): string; +declare function lower(s: string): string; +declare function lowerCase(s: string): string; +declare function camel(s: string): string; +declare function camelCase(s: string): string; +declare function snake(s: string): string; +declare function snakeCase(s: string): string; +declare function title(s: string): string; +declare function titleCase(s: string): string; +declare function param(s: string): string; +declare function paramCase(s: string): string; +declare function pascal(s: string): string; +declare function pascalCase(s: string): string; +declare function constant(s: string): string; +declare function constantCase(s: string): string; +declare function sentence(s: string): string; +declare function sentenceCase(s: string): string; +declare function isUpper(s: string): boolean; +declare function isUpperCase(s: string): boolean; +declare function isLower(s: string): boolean; +declare function isLowerCase(s: string): boolean; +declare function ucFirst(s: string): string; +declare function upperCaseFirst(s: string): string; +declare function lcFirst(s: string): string; +declare function lowerCaseFirst(s: string): string; diff --git a/checksum/checksum.d.ts b/checksum/checksum.d.ts index 920164386f..3c3620bbcf 100644 --- a/checksum/checksum.d.ts +++ b/checksum/checksum.d.ts @@ -3,42 +3,41 @@ // Definitions by: Rogier Schouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "checksum" { - namespace checksum { - /** - * Options object for all functions - */ - interface ChecksumOptions { - /** - * Algorithm to use, default 'sha1' - * Can be 'sha1' or 'md5' (see module 'crypto'). - */ - algorithm?: string; - } - /** - * Generate the checksum for a file on disk - * @param filename The file name - * @param callback Callback which is called with the result or an error - */ - function file(filename: string, callback: (error: Error, hash: string) => void): void; - /** - * Generate the checksum for a file on disk - * @param filename The file name - * @param options Options object to indicate hash algo - * @param callback Callback which is called with the result or an error - */ - function file(filename: string, options: ChecksumOptions, callback: (error: Error, hash: string) => void): void; - } +declare namespace checksum { + /** + * Options object for all functions + */ + interface ChecksumOptions { + /** + * Algorithm to use, default 'sha1' + * Can be 'sha1' or 'md5' (see module 'crypto'). + */ + algorithm?: string; + } - /** - * Generates a checksum for the given value - * @param value Any value - * @param options Allows to set the algorithm - * @returns Checksum - */ - function checksum(value: any, options?: checksum.ChecksumOptions): string; - - export = checksum; + /** + * Generate the checksum for a file on disk + * @param filename The file name + * @param callback Callback which is called with the result or an error + */ + function file(filename: string, callback: (error: Error, hash: string) => void): void; + /** + * Generate the checksum for a file on disk + * @param filename The file name + * @param options Options object to indicate hash algo + * @param callback Callback which is called with the result or an error + */ + function file(filename: string, options: ChecksumOptions, callback: (error: Error, hash: string) => void): void; } + +/** + * Generates a checksum for the given value + * @param value Any value + * @param options Allows to set the algorithm + * @returns Checksum + */ +declare function checksum(value: any, options?: checksum.ChecksumOptions): string; + +export = checksum; diff --git a/circular-json/circular-json.d.ts b/circular-json/circular-json.d.ts index 343744a690..b724f92577 100644 --- a/circular-json/circular-json.d.ts +++ b/circular-json/circular-json.d.ts @@ -3,13 +3,12 @@ // Definitions by: Jonathan Pevarnek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'circular-json' { - interface ICircularJSON extends JSON { + +interface ICircularJSON extends JSON { parse(text: string, reviver?: (key: any, value: any) => any): any; stringify(value: any, replacer?: ((key: string, value: any) => any) | any[], space?: any, placeholder?: boolean): string; - } - - var CircularJSON: ICircularJSON; - - export = CircularJSON; } + +declare var CircularJSON: ICircularJSON; + +export = CircularJSON; diff --git a/clean-css/clean-css.d.ts b/clean-css/clean-css.d.ts index 752be96571..012977f035 100644 --- a/clean-css/clean-css.d.ts +++ b/clean-css/clean-css.d.ts @@ -3,107 +3,106 @@ // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'clean-css' { - namespace CleanCSS { + +declare namespace CleanCSS { interface Options { - // Set to false to disable advanced optimizations - selector & property merging, reduction, etc. - advanced?: boolean; + // Set to false to disable advanced optimizations - selector & property merging, reduction, etc. + advanced?: boolean; - // Set to false to disable aggressive merging of properties. - aggressiveMerging?: boolean; + // Set to false to disable aggressive merging of properties. + aggressiveMerging?: boolean; - // Turns on benchmarking mode measuring time spent on cleaning up (run npm run bench to see example) - benchmark?: boolean; + // Turns on benchmarking mode measuring time spent on cleaning up (run npm run bench to see example) + benchmark?: boolean; - // Enables compatibility mode - compatibility?: Object; + // Enables compatibility mode + compatibility?: Object; - // Set to true to get minification statistics under stats property (see test/custom-test.js for examples) - debug?: boolean; + // Set to true to get minification statistics under stats property (see test/custom-test.js for examples) + debug?: boolean; - // A hash of options for @import inliner, see test/protocol-imports-test.js for examples, or this comment for a proxy use case. - inliner?: Object; + // A hash of options for @import inliner, see test/protocol-imports-test.js for examples, or this comment for a proxy use case. + inliner?: Object; - // Whether to keep line breaks (default is false) - keepBreaks?: boolean; + // Whether to keep line breaks (default is false) + keepBreaks?: boolean; - // * for keeping all (default), 1 for keeping first one only, 0 for removing all - keepSpecialComments?: string | number; + // * for keeping all (default), 1 for keeping first one only, 0 for removing all + keepSpecialComments?: string | number; - // Whether to merge @media at-rules (default is true) - mediaMerging?: boolean; + // Whether to merge @media at-rules (default is true) + mediaMerging?: boolean; - // Whether to process @import rules - processImport?: boolean; + // Whether to process @import rules + processImport?: boolean; - // A list of @import rules, can be ['all'] (default), ['local'], ['remote'], or a blacklisted path e.g. ['!fonts.googleapis.com'] - processImportFrom?: Array; + // A list of @import rules, can be ['all'] (default), ['local'], ['remote'], or a blacklisted path e.g. ['!fonts.googleapis.com'] + processImportFrom?: Array; - // Set to false to skip URL rebasing - rebase?: boolean; + // Set to false to skip URL rebasing + rebase?: boolean; - // Path to resolve relative @import rules and URLs - relativeTo?: string; + // Path to resolve relative @import rules and URLs + relativeTo?: string; - // Set to false to disable restructuring in advanced optimizations - restructuring?: boolean; + // Set to false to disable restructuring in advanced optimizations + restructuring?: boolean; - // Path to resolve absolute @import rules and rebase relative URLs - root?: string; + // Path to resolve absolute @import rules and rebase relative URLs + root?: string; - // Rounding precision; defaults to 2; -1 disables rounding - roundingPrecision?: number; + // Rounding precision; defaults to 2; -1 disables rounding + roundingPrecision?: number; - // Set to true to enable semantic merging mode which assumes BEM-like content (default is false as it's highly likely this will break your stylesheets - use with caution!) - semanticMerging?: boolean; + // Set to true to enable semantic merging mode which assumes BEM-like content (default is false as it's highly likely this will break your stylesheets - use with caution!) + semanticMerging?: boolean; - // Set to false to skip shorthand compacting (default is true unless sourceMap is set when it's false) - shorthandCompacting?: boolean; + // Set to false to skip shorthand compacting (default is true unless sourceMap is set when it's false) + shorthandCompacting?: boolean; - // Exposes source map under sourceMap property, e.g. new CleanCSS().minify(source).sourceMap (default is false) If input styles are a product of CSS preprocessor (Less, Sass) an input source map can be passed as a string. - sourceMap?: boolean | string; + // Exposes source map under sourceMap property, e.g. new CleanCSS().minify(source).sourceMap (default is false) If input styles are a product of CSS preprocessor (Less, Sass) an input source map can be passed as a string. + sourceMap?: boolean | string; - // Set to true to inline sources inside a source map's sourcesContent field (defaults to false) It is also required to process inlined sources from input source maps. - sourceMapInlineSources?: boolean; + // Set to true to inline sources inside a source map's sourcesContent field (defaults to false) It is also required to process inlined sources from input source maps. + sourceMapInlineSources?: boolean; - // Path to a folder or an output file to which rebase all URLs - target?: string; + // Path to a folder or an output file to which rebase all URLs + target?: string; } interface Output { - // Optimized output CSS as a string - styles: string; + // Optimized output CSS as a string + styles: string; - // Output source map (if requested with sourceMap option) - sourceMap: string; + // Output source map (if requested with sourceMap option) + sourceMap: string; - // A list of errors raised - errors: Array; + // A list of errors raised + errors: Array; - // A list of warnings raised - warnings: Array; + // A list of warnings raised + warnings: Array; - // A hash of statistic information (if requested with debug option) - stats: { - // Original content size (after import inlining) - originalSize: number; + // A hash of statistic information (if requested with debug option) + stats: { + // Original content size (after import inlining) + originalSize: number; - // Optimized content size - minifiedSize: number; + // Optimized content size + minifiedSize: number; - // Time spent on optimizations - timeSpent: number; + // Time spent on optimizations + timeSpent: number; - // A ratio of output size to input size (e.g. 25% if content was reduced from 100 bytes to 75 bytes) - efficiency: number; - }; + // A ratio of output size to input size (e.g. 25% if content was reduced from 100 bytes to 75 bytes) + efficiency: number; + }; } - } +} - class CleanCSS { +declare class CleanCSS { constructor(options?: CleanCSS.Options); minify(sources: string | Array | Object, callback?: (error: any, minified: CleanCSS.Output) => void): CleanCSS.Output; - } - - export = CleanCSS; } + +export = CleanCSS; diff --git a/cli/cli.d.ts b/cli/cli.d.ts index 2283d3d283..c19d2f4925 100644 --- a/cli/cli.d.ts +++ b/cli/cli.d.ts @@ -5,62 +5,61 @@ /// -declare module "cli" { - interface CLI { - app: string; - version: string; - argv: string[]; - argc: number; - options: any; - args: string[]; - command: string; - width: number; - option_width: number; - native: any; - output(message?: any, ...optionalParams: any[]): void; - exit(code: number): void; - no_color: boolean; - enable(...plugins: string[]): CLI; - disable(...plugins: string[]): CLI; - setArgv(argv: string | Array, keepArg0?: boolean): void; - next(): string; - parse(opts?: { [long: string]: { 0: string | boolean, 1: string, 2?: string, 3?: any } }, - commands?: { [name: string]: string } | string[]): any; - autocompleteCommand(command: string): string; - info(msg: string): void; - error(msg: string): void; - ok(msg: string): void; - debug(msg: string): void; - fatal(msg: string): void; - setApp(appName: string, version: string): CLI; - setApp(packageJson: string): CLI; - parsePackageJson(path?: string): void; - setUsage(usage: string): CLI; - getUsage(code?: number): void; - getOptError(expects: string, type: string): string; - getValue(defaultVal: string, validateFunc: (value: any) => any, errMsg: string): void; - getInt(defaultVal: number): number; - getDate(defaultVal: Date): Date; - getFloat(defaultVal: number): number; - getUrl(defautltVal: string, identifier?: string): string; - getEmail(defaultVal: string): string; - getIp(defaultVal: string): string; - getPath(defaultVal: string, identifier?: string): string; - getArrayValue(arr: T[], defaultVal: T): T; - withStdin(callback: (data: string) => void): void; - withStdin(encoding: string, callback: (text: string) => void): void; - withStdinLines(callback: (lines: string[], newline: string) => void): void; - withInput(file: string, encoding: string, callback: (line: string, newline: string, eof: boolean) => void): void; - withInput(file: string, callback: (line: string, newline: string, eof: boolean) => void): void; - withInput(callback: (line: string, newline: string, eof: boolean) => void): void; - toType(object: any): string; - daemon(arg: string, callback: () => void): void; - main(callback: (args: string[], options: any) => void): void; - createServer(...args: any[]): any; - exec(cmd: string, callback?: (lines: string[]) => void, errback?: (err: any, stdout: string) => void): void; - progress(progress: number, decimals?: number, stream?: NodeJS.WritableStream): void; - spinner(prefix?: string | boolean, end?: boolean, stream?: NodeJS.WritableStream): void; - } - const cli: CLI; - export = cli; + +interface CLI { + app: string; + version: string; + argv: string[]; + argc: number; + options: any; + args: string[]; + command: string; + width: number; + option_width: number; + native: any; + output(message?: any, ...optionalParams: any[]): void; + exit(code: number): void; + no_color: boolean; + enable(...plugins: string[]): CLI; + disable(...plugins: string[]): CLI; + setArgv(argv: string | Array, keepArg0?: boolean): void; + next(): string; + parse(opts?: { [long: string]: { 0: string | boolean, 1: string, 2?: string, 3?: any } }, + commands?: { [name: string]: string } | string[]): any; + autocompleteCommand(command: string): string; + info(msg: string): void; + error(msg: string): void; + ok(msg: string): void; + debug(msg: string): void; + fatal(msg: string): void; + setApp(appName: string, version: string): CLI; + setApp(packageJson: string): CLI; + parsePackageJson(path?: string): void; + setUsage(usage: string): CLI; + getUsage(code?: number): void; + getOptError(expects: string, type: string): string; + getValue(defaultVal: string, validateFunc: (value: any) => any, errMsg: string): void; + getInt(defaultVal: number): number; + getDate(defaultVal: Date): Date; + getFloat(defaultVal: number): number; + getUrl(defautltVal: string, identifier?: string): string; + getEmail(defaultVal: string): string; + getIp(defaultVal: string): string; + getPath(defaultVal: string, identifier?: string): string; + getArrayValue(arr: T[], defaultVal: T): T; + withStdin(callback: (data: string) => void): void; + withStdin(encoding: string, callback: (text: string) => void): void; + withStdinLines(callback: (lines: string[], newline: string) => void): void; + withInput(file: string, encoding: string, callback: (line: string, newline: string, eof: boolean) => void): void; + withInput(file: string, callback: (line: string, newline: string, eof: boolean) => void): void; + withInput(callback: (line: string, newline: string, eof: boolean) => void): void; + toType(object: any): string; + daemon(arg: string, callback: () => void): void; + main(callback: (args: string[], options: any) => void): void; + createServer(...args: any[]): any; + exec(cmd: string, callback?: (lines: string[]) => void, errback?: (err: any, stdout: string) => void): void; + progress(progress: number, decimals?: number, stream?: NodeJS.WritableStream): void; + spinner(prefix?: string | boolean, end?: boolean, stream?: NodeJS.WritableStream): void; } +declare const cli: CLI; +export = cli; diff --git a/clone/clone.d.ts b/clone/clone.d.ts index 79c05cef00..07fb70d94d 100644 --- a/clone/clone.d.ts +++ b/clone/clone.d.ts @@ -6,20 +6,19 @@ /** * See clone JS source for API docs */ -declare module "clone" { + +/** + * @param val the value that you want to clone, any type allowed + * @param circular Call clone with circular set to false if you are certain that obj contains no circular references. This will give better performance if needed. There is no error if undefined or null is passed as obj. + * @param depth to wich the object is to be cloned (optional, defaults to infinity) + */ +declare function clone(val: T, circular?: boolean, depth?: number): T; + +declare namespace clone { /** - * @param val the value that you want to clone, any type allowed - * @param circular Call clone with circular set to false if you are certain that obj contains no circular references. This will give better performance if needed. There is no error if undefined or null is passed as obj. - * @param depth to wich the object is to be cloned (optional, defaults to infinity) + * @param obj the object that you want to clone */ - function clone(val: T, circular?: boolean, depth?: number): T; - - namespace clone { - /** - * @param obj the object that you want to clone - */ - function clonePrototype(obj: T): T; - } - - export = clone + function clonePrototype(obj: T): T; } + +export = clone diff --git a/closure-compiler/closure-compiler.d.ts b/closure-compiler/closure-compiler.d.ts index 2e875afbdb..9f97f74081 100644 --- a/closure-compiler/closure-compiler.d.ts +++ b/closure-compiler/closure-compiler.d.ts @@ -3,9 +3,8 @@ // Definitions by: Martin Probst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'closure-compiler' { - type Callback = (err: Error, stdout: string, stderr: string) => any; - function compile(src: string, callback: Callback): void; - function compile(src: string, options: {[k: string]: string | string[]}, - callback: Callback): void; -} + +type Callback = (err: Error, stdout: string, stderr: string) => any; +declare function compile(src: string, callback: Callback): void; +declare function compile(src: string, options: { [k: string]: string | string[] }, + callback: Callback): void; diff --git a/coffeeify/coffeeify.d.ts b/coffeeify/coffeeify.d.ts index 05919f901a..6040f06026 100644 --- a/coffeeify/coffeeify.d.ts +++ b/coffeeify/coffeeify.d.ts @@ -5,33 +5,31 @@ /// -declare module "coffeeify" { - import through = require('through'); - namespace coffeeify { - interface Coffeeify { - isCoffee(file: string): boolean; - isLiterate(file: string): boolean; - sourceMap: boolean; - compile(file: string, data: string, callback: Callback): void; - (file: string): through.ThroughStream; - } +import through = require('through'); - interface Callback { - (error: ParseError, compiled: string): void; - } - - interface ParseError extends SyntaxError { - new(error: any, src: string, file: string): ParseError; - message: string; - line: number; - column: number; - annotated: string; - } +declare namespace coffeeify { + interface Coffeeify { + isCoffee(file: string): boolean; + isLiterate(file: string): boolean; + sourceMap: boolean; + compile(file: string, data: string, callback: Callback): void; + (file: string): through.ThroughStream; } - var coffeeify: coffeeify.Coffeeify; + interface Callback { + (error: ParseError, compiled: string): void; + } - export = coffeeify; + interface ParseError extends SyntaxError { + new (error: any, src: string, file: string): ParseError; + message: string; + line: number; + column: number; + annotated: string; + } } +declare var coffeeify: coffeeify.Coffeeify; + +export = coffeeify; diff --git a/compare-version/compare-version.d.ts b/compare-version/compare-version.d.ts index 690d517294..1807abe537 100644 --- a/compare-version/compare-version.d.ts +++ b/compare-version/compare-version.d.ts @@ -4,8 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'compare-version' { - function compare(a: string, b: string): number; - export = compare; -} +declare function compare(a: string, b: string): number; + +export = compare; diff --git a/complex/complex.d.ts b/complex/complex.d.ts index b1ca7c4ac6..0aed9d8d8d 100644 --- a/complex/complex.d.ts +++ b/complex/complex.d.ts @@ -3,236 +3,235 @@ // Definitions by: Aya Morisawa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'complex' { - export default class Complex { - /** - * @param real The real part of the number - * @param im The imaginary part of the number - */ - constructor(real: number, im: number); - /** - * A in line function like Number.from. - * - * Examples: - * var z = Complex.from(2, 4); - * var z = Complex.from(5); - * var z = Complex.from('2+5i'); - * - * @param real A string representation of the number, for example 1+4i - */ - static from(real: string): Complex; +declare export default class Complex { + /** + * @param real The real part of the number + * @param im The imaginary part of the number + */ + constructor(real: number, im: number); - /** - * A in line function like Number.from. - * @param real The real part of the number - * @param im The imaginary part of the number - */ - static from(real: number, im?: number): Complex; + /** + * A in line function like Number.from. + * + * Examples: + * var z = Complex.from(2, 4); + * var z = Complex.from(5); + * var z = Complex.from('2+5i'); + * + * @param real A string representation of the number, for example 1+4i + */ + static from(real: string): Complex; - /** - * Creates a complex instance from a polar representation - * @param r The radius/magnitude of the number - * @param phi The angle/phase of the number - */ - static fromPolar(r: number, phi: number): Complex; + /** + * A in line function like Number.from. + * @param real The real part of the number + * @param im The imaginary part of the number + */ + static from(real: number, im?: number): Complex; - /** - * A instance of the imaginary unit - */ - static i: Complex; + /** + * Creates a complex instance from a polar representation + * @param r The radius/magnitude of the number + * @param phi The angle/phase of the number + */ + static fromPolar(r: number, phi: number): Complex; - /** - * A instance for the real number - */ - static one: Complex; + /** + * A instance of the imaginary unit + */ + static i: Complex; - /** - * Set the real and imaginary properties a and b from a + bi. - * @param real The real part of the number - * @param im The imaginary part of the number - */ - fromRect(real: number, im: number): Complex; + /** + * A instance for the real number + */ + static one: Complex; - /** - * Set the a and b in a + bi from a polar representation. - * @param r The radius/magnitude of the number - * @param phi The angle/phase of the number - */ - fromPolar(r: number, phi: number): Complex; + /** + * Set the real and imaginary properties a and b from a + bi. + * @param real The real part of the number + * @param im The imaginary part of the number + */ + fromRect(real: number, im: number): Complex; - /** - * Set the precision of the numbers. Similar to Number.prototype.toPrecision. Useful before printing the number with the toString method. - * @param k An integer specifying the number of significant digits - */ - toPrecision(k: number): Complex; + /** + * Set the a and b in a + bi from a polar representation. + * @param r The radius/magnitude of the number + * @param phi The angle/phase of the number + */ + fromPolar(r: number, phi: number): Complex; - /** - * Format a number using fixed-point notation. Similar to Number.prototype.toFixed. Useful before printing the number with the toString method. - * @param k The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0. - */ - toFixed(k: number): Complex; + /** + * Set the precision of the numbers. Similar to Number.prototype.toPrecision. Useful before printing the number with the toString method. + * @param k An integer specifying the number of significant digits + */ + toPrecision(k: number): Complex; - /** - * Finalize the instance. The number will not change and any other method call will return a new instance. Very useful when a complex instance should stay constant. For example the Complex.i variable is a finalized instance. - */ - finalize(): Complex; + /** + * Format a number using fixed-point notation. Similar to Number.prototype.toFixed. Useful before printing the number with the toString method. + * @param k The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0. + */ + toFixed(k: number): Complex; - /** - * Calculate the magnitude of the complex number - */ - magnitude(): number; + /** + * Finalize the instance. The number will not change and any other method call will return a new instance. Very useful when a complex instance should stay constant. For example the Complex.i variable is a finalized instance. + */ + finalize(): Complex; - /** - * Alias for magnitude(). Calculate the magnitude of the complex number. - */ - abs(): number; + /** + * Calculate the magnitude of the complex number + */ + magnitude(): number; - /** - * Calculate the angle with respect to the real axis, in radians. - */ - angle(): number; + /** + * Alias for magnitude(). Calculate the magnitude of the complex number. + */ + abs(): number; - /** - * Alias for angle(). Calculate the angle with respect to the real axis, in radians. - */ - arg(): number; + /** + * Calculate the angle with respect to the real axis, in radians. + */ + angle(): number; - /** - * Alias for angle(). Calculate the angle with respect to the real axis, in radians. - */ - phase(): number; + /** + * Alias for angle(). Calculate the angle with respect to the real axis, in radians. + */ + arg(): number; - /** - * Calculate the conjugate of the complex number (multiplies the imaginary part with -1) - */ - conjugate(): Complex; + /** + * Alias for angle(). Calculate the angle with respect to the real axis, in radians. + */ + phase(): number; - /** - * Negate the number (multiplies both the real and imaginary part with -1) - */ - negate(): Complex; + /** + * Calculate the conjugate of the complex number (multiplies the imaginary part with -1) + */ + conjugate(): Complex; - /** - * Multiply the number with a real or complex number - * @param z The number to multiply with - */ - multiply(z: number | Complex): Complex; + /** + * Negate the number (multiplies both the real and imaginary part with -1) + */ + negate(): Complex; - /** - * Alias for multiply(). Multiply the number with a real or complex number - * @param z The number to multiply with - */ - mult(z: number | Complex): Complex; + /** + * Multiply the number with a real or complex number + * @param z The number to multiply with + */ + multiply(z: number | Complex): Complex; - /** - * Divide the number by a real or complex number - * @param z The number to divide by - */ - divide(z: number | Complex): Complex; + /** + * Alias for multiply(). Multiply the number with a real or complex number + * @param z The number to multiply with + */ + mult(z: number | Complex): Complex; - /** - * Alias for divide(). Divide the number by a real or complex number - * @param z The number to divide by - */ - div(z: number | Complex): Complex; + /** + * Divide the number by a real or complex number + * @param z The number to divide by + */ + divide(z: number | Complex): Complex; - /** - * Add a real or complex number - * @param z The number to add - */ - add(z: number | Complex): Complex; + /** + * Alias for divide(). Divide the number by a real or complex number + * @param z The number to divide by + */ + div(z: number | Complex): Complex; - /** - * Subtract a real or complex number - * @param z The number to subtract - */ - subtract(z: number | Complex): Complex; + /** + * Add a real or complex number + * @param z The number to add + */ + add(z: number | Complex): Complex; - /** - * Alias for subtract(). Subtract a real or complex number - * @param z The number to subtract - */ - sub(z: number | Complex): Complex; + /** + * Subtract a real or complex number + * @param z The number to subtract + */ + subtract(z: number | Complex): Complex; - /** - * Return the base to the exponent - * @param z The exponent - */ - pow(z: number | Complex): Complex; + /** + * Alias for subtract(). Subtract a real or complex number + * @param z The number to subtract + */ + sub(z: number | Complex): Complex; - /** - * Return the square root - */ - sqrt(): Complex; + /** + * Return the base to the exponent + * @param z The exponent + */ + pow(z: number | Complex): Complex; - /** - * Return the natural logarithm (base E) - * @param k The actual answer has a multiplicity (ln(z) = ln|z| + arg(z)) where arg(z) can return the same for different angles (every 2*pi), with this argument you can define which answer is required - */ - log(k?: number): Complex; + /** + * Return the square root + */ + sqrt(): Complex; - /** - * Calculate the e^z where the base is E and the exponential the complex number. - */ - exp(): Complex; + /** + * Return the natural logarithm (base E) + * @param k The actual answer has a multiplicity (ln(z) = ln|z| + arg(z)) where arg(z) can return the same for different angles (every 2*pi), with this argument you can define which answer is required + */ + log(k?: number): Complex; - /** - * Calculate the sine of the complex number - */ - sin(): Complex; + /** + * Calculate the e^z where the base is E and the exponential the complex number. + */ + exp(): Complex; - /** - * Calculate the cosine of the complex number - */ - cos(): Complex; + /** + * Calculate the sine of the complex number + */ + sin(): Complex; - /** - * Calculate the tangent of the complex number - */ - tan(): Complex; + /** + * Calculate the cosine of the complex number + */ + cos(): Complex; - /** - * Calculate the hyperbolic sine of the complex number - */ - sinh(): Complex + /** + * Calculate the tangent of the complex number + */ + tan(): Complex; - /** - * Calculate the hyperbolic cosine of the complex number - */ - cosh(): Complex + /** + * Calculate the hyperbolic sine of the complex number + */ + sinh(): Complex - /** - * Calculate the hyperbolic tangent of the complex number - */ - tanh(): Complex + /** + * Calculate the hyperbolic cosine of the complex number + */ + cosh(): Complex - /** - * Return a new Complex instance with the same real and imaginary properties - */ - clone(): Complex; + /** + * Calculate the hyperbolic tangent of the complex number + */ + tanh(): Complex - /** - * Return a string representation of the complex number - * - * Examples: - * new Complex(1, 2).toString(); // 1+2i - * new Complex(0, 1).toString(); // i - * new Complex(4, 0).toString(); // 4 - * new Complex(1, 1).toString(); // 1+i - * 'my Complex Number is: ' + (new Complex(3, 5)); // 'my Complex Number is: 3+5i - */ - toString(): string; + /** + * Return a new Complex instance with the same real and imaginary properties + */ + clone(): Complex; - /** - * Check if the real and imaginary components are equal to the passed in compelex components. - * - * Examples: - * new Complex(1, 4).equals(new Complex(1, 4)); // true - * new Complex(1, 4).equals(new Complex(1, 3)); // false - * - * @param z The complex number to compare with - */ - equals(z: number | Complex): boolean; - } + /** + * Return a string representation of the complex number + * + * Examples: + * new Complex(1, 2).toString(); // 1+2i + * new Complex(0, 1).toString(); // i + * new Complex(4, 0).toString(); // 4 + * new Complex(1, 1).toString(); // 1+i + * 'my Complex Number is: ' + (new Complex(3, 5)); // 'my Complex Number is: 3+5i + */ + toString(): string; + + /** + * Check if the real and imaginary components are equal to the passed in compelex components. + * + * Examples: + * new Complex(1, 4).equals(new Complex(1, 4)); // true + * new Complex(1, 4).equals(new Complex(1, 3)); // false + * + * @param z The complex number to compare with + */ + equals(z: number | Complex): boolean; } diff --git a/compose-function/compose-function.d.ts b/compose-function/compose-function.d.ts index d4f205fd32..a77317c48c 100644 --- a/compose-function/compose-function.d.ts +++ b/compose-function/compose-function.d.ts @@ -3,29 +3,28 @@ // Definitions by: Denis Sokolov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "compose-function" { - // Hardcoded signatures for 2-4 parameters - function f( - f1: (b: B) => C, - f2: (a: A) => B - ): (a: A) => C - function f( - f1: (b: C) => D, - f2: (a: B) => C, - f3: (a: A) => B - ): (a: A) => D - function f( - f1: (b: D) => E, - f2: (a: C) => D, - f3: (a: B) => C, - f4: (a: A) => B - ): (a: A) => E - // Minimal typing for more than 4 parameters - function f( - f1: (a: any) => Result, - ...functions: Function[] - ): (a: any) => Result +// Hardcoded signatures for 2-4 parameters +declare function f( + f1: (b: B) => C, + f2: (a: A) => B +): (a: A) => C +declare function f( + f1: (b: C) => D, + f2: (a: B) => C, + f3: (a: A) => B +): (a: A) => D +declare function f( + f1: (b: D) => E, + f2: (a: C) => D, + f3: (a: B) => C, + f4: (a: A) => B +): (a: A) => E - export = f; -} +// Minimal typing for more than 4 parameters +declare function f( + f1: (a: any) => Result, + ...functions: Function[] +): (a: any) => Result + +export = f; diff --git a/compression/compression.d.ts b/compression/compression.d.ts index 6a444e3f49..29757894c1 100644 --- a/compression/compression.d.ts +++ b/compression/compression.d.ts @@ -5,16 +5,15 @@ /// -declare module "compression" { - import express = require('express'); - namespace e { - interface CompressionOptions { - threshold?: number; - filter?: Function; - } +import express = require('express'); + +declare namespace e { + interface CompressionOptions { + threshold?: number; + filter?: Function; } - - function e(options?: e.CompressionOptions): express.RequestHandler; - export = e; } + +declare function e(options?: e.CompressionOptions): express.RequestHandler; +export = e; diff --git a/confidence/confidence.d.ts b/confidence/confidence.d.ts index 62ad82adb1..fc3a536c50 100644 --- a/confidence/confidence.d.ts +++ b/confidence/confidence.d.ts @@ -9,40 +9,39 @@ * serving values based on object path ('/a/b/c' translates to a.b.c). In addition, * confidence defines special $-prefixed keys used to filter values for a given criteria. */ -declare module 'confidence' { - - export class Store { - - /** - * @constructor - * @param {any} document - the configuration document for this document store - */ - constructor(document?: any); - - /** - * Validates the provided configuration, clears any existing configuration, then loads the configuration where: - * @param {any} document - an object containing a confidence configuration object generated from a parsed JSON document. If the document is invlaid, will throw an error. - */ - load(document: any): void; - /** - * Retrieves a value from the configuration document after applying the provided criteria where: - * @param {string} key - the requested key path. All keys must begin with '/'. '/' returns the the entire document. - * @param {any} criteria - optional object used as criteria for applying filters in the configuration document. Defaults to {}. - * - * @return {any} Returns the value found after applying the criteria. If the key is invalid or not found, returns undefined. - */ - get(key: string, criteria?: any): any; +declare export class Store { + + /** + * @constructor + * @param {any} document - the configuration document for this document store + */ + constructor(document?: any); + + /** + * Validates the provided configuration, clears any existing configuration, then loads the configuration where: + * @param {any} document - an object containing a confidence configuration object generated from a parsed JSON document. If the document is invlaid, will throw an error. + */ + load(document: any): void; - /** - * Retrieves the metadata (if any) from the configuration document after applying the provided criteria where: - * @param {string} key - the requested key path. All keys must begin with '/'. '/' returns the the entire document. - * @param {any} criteria - optional object used as criteria for applying filters in the configuration document. Defaults to {}. - * - * @return {any} Returns the metadata found after applying the criteria. If the key is invalid or not found, or if no metadata is available, returns undefined. - */ - meta(key: string, criteria?: any): any; - } + /** + * Retrieves a value from the configuration document after applying the provided criteria where: + * @param {string} key - the requested key path. All keys must begin with '/'. '/' returns the the entire document. + * @param {any} criteria - optional object used as criteria for applying filters in the configuration document. Defaults to {}. + * + * @return {any} Returns the value found after applying the criteria. If the key is invalid or not found, returns undefined. + */ + get(key: string, criteria?: any): any; + + + /** + * Retrieves the metadata (if any) from the configuration document after applying the provided criteria where: + * @param {string} key - the requested key path. All keys must begin with '/'. '/' returns the the entire document. + * @param {any} criteria - optional object used as criteria for applying filters in the configuration document. Defaults to {}. + * + * @return {any} Returns the metadata found after applying the criteria. If the key is invalid or not found, or if no metadata is available, returns undefined. + */ + meta(key: string, criteria?: any): any; } diff --git a/config/config.d.ts b/config/config.d.ts index f09abdd3f2..a9cb505f0e 100644 --- a/config/config.d.ts +++ b/config/config.d.ts @@ -3,42 +3,41 @@ // Definitions by: Roman Korneev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "config" { - var c: c.IConfig; - namespace c { +declare var c: c.IConfig; - // see https://github.com/lorenwest/node-config/wiki/Using-Config-Utilities - interface IUtil { - // Extend an object (and any object it contains) with one or more objects (and objects contained in them). - extendDeep(mergeInto: any, mergeFrom: any, depth?: number): any; +declare namespace c { - // Return a deep copy of the specified object. - cloneDeep(copyFrom: any, depth?: number): any; + // see https://github.com/lorenwest/node-config/wiki/Using-Config-Utilities + interface IUtil { + // Extend an object (and any object it contains) with one or more objects (and objects contained in them). + extendDeep(mergeInto: any, mergeFrom: any, depth?: number): any; - // Return true if two objects have equal contents. - equalsDeep(object1: any, object2: any, dept?: number): boolean; + // Return a deep copy of the specified object. + cloneDeep(copyFrom: any, depth?: number): any; - // Returns an object containing all elements that differ between two objects. - diffDeep(object1: any, object2: any, depth?: number): any; + // Return true if two objects have equal contents. + equalsDeep(object1: any, object2: any, dept?: number): boolean; - // Make a javascript object property immutable (assuring it cannot be changed from the current value). - makeImmutable(object: any, propertyName?: string, propertyValue?: string): any; + // Returns an object containing all elements that differ between two objects. + diffDeep(object1: any, object2: any, depth?: number): any; - // Make an object property hidden so it doesn't appear when enumerating elements of the object. - makeHidden(object: any, propertyName: string, propertyValue?: string): any; + // Make a javascript object property immutable (assuring it cannot be changed from the current value). + makeImmutable(object: any, propertyName?: string, propertyValue?: string): any; - // Get the current value of a config environment variable - getEnv(varName: string): string; - } + // Make an object property hidden so it doesn't appear when enumerating elements of the object. + makeHidden(object: any, propertyName: string, propertyValue?: string): any; - interface IConfig { - get(setting: string): T; - has(setting: string): boolean; - util: IUtil; - } - } + // Get the current value of a config environment variable + getEnv(varName: string): string; + } - export = c; + interface IConfig { + get(setting: string): T; + has(setting: string): boolean; + util: IUtil; + } } + +export = c; diff --git a/configstore/configstore.d.ts b/configstore/configstore.d.ts index 7ca1bcb9ee..5bd5a79420 100644 --- a/configstore/configstore.d.ts +++ b/configstore/configstore.d.ts @@ -3,36 +3,35 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'configstore' { - /* - Set an item - */ - export function set(key: string, val: any): void; - /* - Get an item - */ - export function get(key: string): any; +/* + Set an item + */ +declare export function set(key: string, val: any): void; - /* - Delete an item - */ - export function del(key: string): void; +/* + Get an item + */ +declare export function get(key: string): any; - /* - Get all items as an object or replace the current config with an object: +/* + Delete an item + */ +declare export function del(key: string): void; - conf.all = { - hello: 'world' - }; - */ - export var all: Object; - /* - Get the item count - */ - export var size: number; - /* - Get the path to the config file. Can be used to show the user where the config file is located or even better open it for them. - */ - export var path: string; -} +/* + Get all items as an object or replace the current config with an object: + + conf.all = { + hello: 'world' + }; + */ +declare export var all: Object; +/* + Get the item count + */ +declare export var size: number; +/* + Get the path to the config file. Can be used to show the user where the config file is located or even better open it for them. + */ +declare export var path: string; diff --git a/connect-livereload/connect-livereload.d.ts b/connect-livereload/connect-livereload.d.ts index c8246e62f1..63524bd93e 100644 --- a/connect-livereload/connect-livereload.d.ts +++ b/connect-livereload/connect-livereload.d.ts @@ -5,34 +5,33 @@ /// -declare module "connect-livereload" { - import { HandleFunction } from "connect"; - function livereload(): HandleFunction; - function livereload(options: livereload.Options): HandleFunction; +import { HandleFunction } from "connect"; - namespace livereload { - export type FileMatcher = string | RegExp; +declare function livereload(): HandleFunction; +declare function livereload(options: livereload.Options): HandleFunction; - export interface Rule { - match: RegExp; - fn: (w: string, s: string) => string; - } +declare namespace livereload { + export type FileMatcher = string | RegExp; - export interface Options { - ignore?: FileMatcher[]; - excludeList?: FileMatcher[]; + export interface Rule { + match: RegExp; + fn: (w: string, s: string) => string; + } - include?: FileMatcher[]; - html?: (val: string) => boolean; - rules?: Rule[]; - disableCompression?: boolean; + export interface Options { + ignore?: FileMatcher[]; + excludeList?: FileMatcher[]; - hostname?: string; - port?: number; - src?: string; - } - } + include?: FileMatcher[]; + html?: (val: string) => boolean; + rules?: Rule[]; + disableCompression?: boolean; - export = livereload; + hostname?: string; + port?: number; + src?: string; + } } + +export = livereload; diff --git a/connect-modrewrite/connect-modrewrite.d.ts b/connect-modrewrite/connect-modrewrite.d.ts index 57e9e842f3..9d4c81fd29 100644 --- a/connect-modrewrite/connect-modrewrite.d.ts +++ b/connect-modrewrite/connect-modrewrite.d.ts @@ -5,8 +5,7 @@ /// -declare module 'connect-modrewrite' { - import express = require('express'); - function modrewrite(rewrites: string[]): express.RequestHandler; - export = modrewrite; -} \ No newline at end of file + +import express = require('express'); +declare function modrewrite(rewrites: string[]): express.RequestHandler; +export = modrewrite; diff --git a/connect-mongo/connect-mongo.d.ts b/connect-mongo/connect-mongo.d.ts index 49f93e2d46..472ae0ddeb 100644 --- a/connect-mongo/connect-mongo.d.ts +++ b/connect-mongo/connect-mongo.d.ts @@ -8,106 +8,105 @@ /// /// -declare module "connect-mongo" { - import * as express from 'express'; - import * as mongoose from 'mongoose'; - import * as mongodb from 'mongodb'; - import * as session from 'express-session'; - function connectMongo(connect: (options?: session.SessionOptions) => express.RequestHandler): connectMongo.MongoStoreFactory; +import * as express from 'express'; +import * as mongoose from 'mongoose'; +import * as mongodb from 'mongodb'; +import * as session from 'express-session'; - namespace connectMongo { +declare function connectMongo(connect: (options?: session.SessionOptions) => express.RequestHandler): connectMongo.MongoStoreFactory; - export interface DefaultOptions{ - /** - * The hostname of the database you are connecting to. - * (Default: '127.0.0.1') - */ - host?: string; +declare namespace connectMongo { - /** - * The port number to connect to. - * (Default: 27017) - */ - port?: string; + export interface DefaultOptions { + /** + * The hostname of the database you are connecting to. + * (Default: '127.0.0.1') + */ + host?: string; - /** - * (Default: false) - */ - autoReconnect?: boolean; + /** + * The port number to connect to. + * (Default: 27017) + */ + port?: string; - /** - * (Default: true) - */ - ssl?: boolean; + /** + * (Default: false) + */ + autoReconnect?: boolean; - /** - * (Default: 1) - */ - w?: number; + /** + * (Default: true) + */ + ssl?: boolean; - /** - * The colletion of the database you are connecting to. - * (Default: sessions) - */ - collection?: string; + /** + * (Default: 1) + */ + w?: number; - /** - * Serialize sessions using JSON.stringify and deserialize them with JSON.parse. - * (Default: true) - */ - stringify?: boolean; + /** + * The colletion of the database you are connecting to. + * (Default: sessions) + */ + collection?: string; - /** - * Default: false - */ - hash?: boolean; + /** + * Serialize sessions using JSON.stringify and deserialize them with JSON.parse. + * (Default: true) + */ + stringify?: boolean; - /** - * Default: 14 days (60 * 60 * 24 * 14) - */ - ttl?: number; + /** + * Default: false + */ + hash?: boolean; - /** - * Automatically remove expired sessions. - * (Default: 'native') - */ - autoRemove?: string; + /** + * Default: 14 days (60 * 60 * 24 * 14) + */ + ttl?: number; - /** - * (Default: 10) - */ - autoRemoveInterval?: number; - } + /** + * Automatically remove expired sessions. + * (Default: 'native') + */ + autoRemove?: string; - export interface MongoUrlOptions extends DefaultOptions { - url: string; - mongoOptions?: mongoose.ConnectionOptions; - } - - export interface MogooseConnectionOptions extends DefaultOptions { - mongooseConnection: mongoose.Connection; - } - - export interface NaitiveMongoOptions extends DefaultOptions { - db: mongodb.Db; - } - - export interface MongoStoreFactory { - new (options: MongoUrlOptions): MongoStore; - new (options: MogooseConnectionOptions): MongoStore; - new (options: NaitiveMongoOptions): MongoStore; - } - - export class MongoStore extends session.Store { - get: (sid: string, callback: (err: any, session: Express.Session) => void) => void; - set: (sid: string, session: Express.Session, callback: (err: any) => void) => void; - destroy: (sid: string, callback: (err: any) => void) => void; - length: (callback: (err: any, length: number) => void) => void; - clear: (callback: (err: any) => void) => void; - touch: (sid: string, session: Express.Session, callback:(err: any) => void) => void; - } + /** + * (Default: 10) + */ + autoRemoveInterval?: number; } - export = connectMongo; + export interface MongoUrlOptions extends DefaultOptions { + url: string; + mongoOptions?: mongoose.ConnectionOptions; + } + + export interface MogooseConnectionOptions extends DefaultOptions { + mongooseConnection: mongoose.Connection; + } + + export interface NaitiveMongoOptions extends DefaultOptions { + db: mongodb.Db; + } + + export interface MongoStoreFactory { + new (options: MongoUrlOptions): MongoStore; + new (options: MogooseConnectionOptions): MongoStore; + new (options: NaitiveMongoOptions): MongoStore; + } + + export class MongoStore extends session.Store { + get: (sid: string, callback: (err: any, session: Express.Session) => void) => void; + set: (sid: string, session: Express.Session, callback: (err: any) => void) => void; + destroy: (sid: string, callback: (err: any) => void) => void; + length: (callback: (err: any, length: number) => void) => void; + clear: (callback: (err: any) => void) => void; + touch: (sid: string, session: Express.Session, callback: (err: any) => void) => void; + } } + +export = connectMongo; diff --git a/connect-slashes/connect-slashes.d.ts b/connect-slashes/connect-slashes.d.ts index 111e29c093..761ce13404 100644 --- a/connect-slashes/connect-slashes.d.ts +++ b/connect-slashes/connect-slashes.d.ts @@ -15,26 +15,25 @@ /// -declare module "connect-slashes" { - import express = require('express'); + +import express = require('express'); + +/** + * @see https://github.com/avinoamr/connect-slashes#usage + */ +declare function slashes(addTrailingSlashes?: boolean, options?: slashes.Options): express.RequestHandler; + +declare namespace slashes { /** - * @see https://github.com/avinoamr/connect-slashes#usage + * Additional settings + * @see https://github.com/avinoamr/connect-slashes#additional-settings */ - function slashes (addTrailingSlashes?: boolean, options?: slashes.Options): express.RequestHandler; - - namespace slashes { - - /** - * Additional settings - * @see https://github.com/avinoamr/connect-slashes#additional-settings - */ - interface Options { - base?: string; - code?: number; - headers?: {[field: string]: string}; - } + interface Options { + base?: string; + code?: number; + headers?: { [field: string]: string }; } - - export = slashes; } + +export = slashes; diff --git a/connect/connect.d.ts b/connect/connect.d.ts index 4ec11f042d..816af03f9b 100644 --- a/connect/connect.d.ts +++ b/connect/connect.d.ts @@ -5,88 +5,87 @@ /// -declare module "connect" { - import * as http from "http"; - /** - * Create a new connect server. - * @public - */ - function createServer(): createServer.Server; +import * as http from "http"; - namespace createServer { - export type ServerHandle = HandleFunction | http.Server; +/** + * Create a new connect server. + * @public + */ +declare function createServer(): createServer.Server; - export type SimpleHandleFunction = (req: http.IncomingMessage, res: http.ServerResponse) => void; - export type NextHandleFunction = (req: http.IncomingMessage, res: http.ServerResponse, next: Function) => void; - export type ErrorHandleFunction = (err: Error, req: http.IncomingMessage, res: http.ServerResponse, next: Function) => void; - export type HandleFunction = SimpleHandleFunction | NextHandleFunction | ErrorHandleFunction; +declare namespace createServer { + export type ServerHandle = HandleFunction | http.Server; - export interface ServerStackItem { - route: string; - handle: ServerHandle; - } + export type SimpleHandleFunction = (req: http.IncomingMessage, res: http.ServerResponse) => void; + export type NextHandleFunction = (req: http.IncomingMessage, res: http.ServerResponse, next: Function) => void; + export type ErrorHandleFunction = (err: Error, req: http.IncomingMessage, res: http.ServerResponse, next: Function) => void; + export type HandleFunction = SimpleHandleFunction | NextHandleFunction | ErrorHandleFunction; - export interface Server extends NodeJS.EventEmitter { - (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void; - - route: string; - stack: ServerStackItem[]; - - /** - * Utilize the given middleware `handle` to the given `route`, - * defaulting to _/_. This "route" is the mount-point for the - * middleware, when given a value other than _/_ the middleware - * is only effective when that segment is present in the request's - * pathname. - * - * For example if we were to mount a function at _/admin_, it would - * be invoked on _/admin_, and _/admin/settings_, however it would - * not be invoked for _/_, or _/posts_. - * - * @public - */ - use(fn: HandleFunction): Server; - use(route: string, fn: HandleFunction): Server; - - /** - * Handle server requests, punting them down - * the middleware stack. - * - * @private - */ - handle(req: http.IncomingMessage, res: http.ServerResponse, next: Function): void; - - /** - * Listen for connections. - * - * This method takes the same arguments - * as node's `http.Server#listen()`. - * - * HTTP and HTTPS: - * - * If you run your application both as HTTP - * and HTTPS you may wrap them individually, - * since your Connect "server" is really just - * a JavaScript `Function`. - * - * var connect = require('connect') - * , http = require('http') - * , https = require('https'); - * - * var app = connect(); - * - * http.createServer(app).listen(80); - * https.createServer(options, app).listen(443); - * - * @api public - */ - listen(port: number, hostname?: string, backlog?: number, callback?: Function): http.Server; - listen(port: number, hostname?: string, callback?: Function): http.Server; - listen(path: string, callback?: Function): http.Server; - listen(handle: any, listeningListener?: Function): http.Server; - } + export interface ServerStackItem { + route: string; + handle: ServerHandle; } - export = createServer; + export interface Server extends NodeJS.EventEmitter { + (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void; + + route: string; + stack: ServerStackItem[]; + + /** + * Utilize the given middleware `handle` to the given `route`, + * defaulting to _/_. This "route" is the mount-point for the + * middleware, when given a value other than _/_ the middleware + * is only effective when that segment is present in the request's + * pathname. + * + * For example if we were to mount a function at _/admin_, it would + * be invoked on _/admin_, and _/admin/settings_, however it would + * not be invoked for _/_, or _/posts_. + * + * @public + */ + use(fn: HandleFunction): Server; + use(route: string, fn: HandleFunction): Server; + + /** + * Handle server requests, punting them down + * the middleware stack. + * + * @private + */ + handle(req: http.IncomingMessage, res: http.ServerResponse, next: Function): void; + + /** + * Listen for connections. + * + * This method takes the same arguments + * as node's `http.Server#listen()`. + * + * HTTP and HTTPS: + * + * If you run your application both as HTTP + * and HTTPS you may wrap them individually, + * since your Connect "server" is really just + * a JavaScript `Function`. + * + * var connect = require('connect') + * , http = require('http') + * , https = require('https'); + * + * var app = connect(); + * + * http.createServer(app).listen(80); + * https.createServer(options, app).listen(443); + * + * @api public + */ + listen(port: number, hostname?: string, backlog?: number, callback?: Function): http.Server; + listen(port: number, hostname?: string, callback?: Function): http.Server; + listen(path: string, callback?: Function): http.Server; + listen(handle: any, listeningListener?: Function): http.Server; + } } + +export = createServer; diff --git a/console-stamp/console-stamp.d.ts b/console-stamp/console-stamp.d.ts index a798dc66cc..ff6571330d 100644 --- a/console-stamp/console-stamp.d.ts +++ b/console-stamp/console-stamp.d.ts @@ -3,44 +3,43 @@ // Definitions by: Eric Byers // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'console-stamp' { - function consoleStamp(console:{}, options?: { - /** - * A string with date format based on Javascript Date Format - */ - pattern?: string - /** - * If true it will show the label (LOG | INFO | WARN | ERROR) - */ - label?: boolean; +declare function consoleStamp(console: {}, options?: { + /** + * A string with date format based on Javascript Date Format + */ + pattern?: string - /** - * An array containing the methods to include in the patch - */ - include?: any; + /** + * If true it will show the label (LOG | INFO | WARN | ERROR) + */ + label?: boolean; - /** - * An array containing the methods to exclude in the patch) - */ - exclude?: any; + /** + * An array containing the methods to include in the patch + */ + include?: any; - /** - * Types can be String, Object (interpreted with util.inspect), or Function. See the test-metadata.js for examples. - * Note that metadata can still be sent as the third parameter (as in vesion 1.6) as a backward compatibillity feature, but this is deprecated. - */ - metadata?: any; + /** + * An array containing the methods to exclude in the patch) + */ + exclude?: any; - /** - * An object representing a color theme. More info https://www.npmjs.com/package/colors - */ - colors?: { - stamp?: any; - label?: any; - metadata?: any; - }; - }): void; + /** + * Types can be String, Object (interpreted with util.inspect), or Function. See the test-metadata.js for examples. + * Note that metadata can still be sent as the third parameter (as in vesion 1.6) as a backward compatibillity feature, but this is deprecated. + */ + metadata?: any; - export = consoleStamp; -} + /** + * An object representing a color theme. More info https://www.npmjs.com/package/colors + */ + colors?: { + stamp?: any; + label?: any; + metadata?: any; + }; +}): void; + +export = consoleStamp; diff --git a/consolidate/consolidate.d.ts b/consolidate/consolidate.d.ts index ff54a83a8e..2d567ce25c 100644 --- a/consolidate/consolidate.d.ts +++ b/consolidate/consolidate.d.ts @@ -8,68 +8,67 @@ /// /// -declare module "consolidate" { - var cons: Consolidate; - export = cons; +declare var cons: Consolidate; - interface Consolidate { - /** - * expose the instance of the engine - */ - requires: Object; +export = cons; - /** - * Clear the cache. - * - * @api public - */ - clearCache(): void; - // template engines - atpl: RendererInterface; - dot: RendererInterface; - dust: RendererInterface; - eco: RendererInterface; - ejs: RendererInterface; - ect: RendererInterface; - haml: RendererInterface; - // TODO figure out how to do haml-coffee - hamlet: RendererInterface; - handlebars: RendererInterface; - hogan: RendererInterface; - htmling: RendererInterface; - jade: RendererInterface; - jazz: RendererInterface; - jqtpl: RendererInterface; - just: RendererInterface; - liquid: RendererInterface; - liquor: RendererInterface; - lodash: RendererInterface; - mote: RendererInterface; - mustache: RendererInterface; - nunjucks: RendererInterface; - qejs: RendererInterface; - ractive: RendererInterface; - react: RendererInterface; - swig: RendererInterface; - templayed: RendererInterface; - toffee: RendererInterface; - underscore: RendererInterface; - walrus: RendererInterface; - whiskers: RendererInterface; - } +interface Consolidate { + /** + * expose the instance of the engine + */ + requires: Object; - interface RendererInterface { - render(path: String, fn: (err: Error, html: String) => any): any; - - render(path: String, options: {cache?: boolean, [otherOptions: string]: any}, fn: (err: Error, html: String) => any): any; - - render(path: String, options?: { cache?: boolean, [otherOptions: string]: any }): Promise; - - (path: String, fn: (err: Error, html: String) => any): any; - - (path: String, options: { cache?: boolean, [otherOptions: string]: any }, fn: (err: Error, html: String) => any): any; - - (path: String, options?: { cache?: boolean, [otherOptions: string]: any }): Promise; - } + /** + * Clear the cache. + * + * @api public + */ + clearCache(): void; + // template engines + atpl: RendererInterface; + dot: RendererInterface; + dust: RendererInterface; + eco: RendererInterface; + ejs: RendererInterface; + ect: RendererInterface; + haml: RendererInterface; + // TODO figure out how to do haml-coffee + hamlet: RendererInterface; + handlebars: RendererInterface; + hogan: RendererInterface; + htmling: RendererInterface; + jade: RendererInterface; + jazz: RendererInterface; + jqtpl: RendererInterface; + just: RendererInterface; + liquid: RendererInterface; + liquor: RendererInterface; + lodash: RendererInterface; + mote: RendererInterface; + mustache: RendererInterface; + nunjucks: RendererInterface; + qejs: RendererInterface; + ractive: RendererInterface; + react: RendererInterface; + swig: RendererInterface; + templayed: RendererInterface; + toffee: RendererInterface; + underscore: RendererInterface; + walrus: RendererInterface; + whiskers: RendererInterface; +} + +interface RendererInterface { + render(path: String, fn: (err: Error, html: String) => any): any; + + render(path: String, options: { cache?: boolean, [otherOptions: string]: any }, fn: (err: Error, html: String) => any): any; + + render(path: String, options?: { cache?: boolean, [otherOptions: string]: any }): Promise; + + (path: String, fn: (err: Error, html: String) => any): any; + + (path: String, options: { cache?: boolean, [otherOptions: string]: any }, fn: (err: Error, html: String) => any): any; + + (path: String, options?: { cache?: boolean, [otherOptions: string]: any }): Promise; } diff --git a/constant-case/constant-case.d.ts b/constant-case/constant-case.d.ts index 2bb635c763..7ae0536e74 100644 --- a/constant-case/constant-case.d.ts +++ b/constant-case/constant-case.d.ts @@ -3,7 +3,6 @@ // Definitions by: Sam Saint-Pettersen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "constant-case" { - function constantCase(string: string, locale?: string): string; - export = constantCase; -} + +declare function constantCase(string: string, locale?: string): string; +export = constantCase; diff --git a/consul/consul.d.ts b/consul/consul.d.ts index 4f46e6a5be..eddc611097 100644 --- a/consul/consul.d.ts +++ b/consul/consul.d.ts @@ -5,1030 +5,1029 @@ /// -declare module "consul" { - - import {IncomingMessage as HttpIncomingMessage} from "http"; - - namespace Consul { - - interface Thenable { - then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; - then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => void): Thenable; - catch(onRejected?: (error: any) => U | Thenable): Thenable; - } - - interface CommonOptions { - consistent?: boolean; - dc?: string; - stale?: boolean; - token?: string; - wait?: string; - wan?: boolean; - - ctx?: NodeJS.EventEmitter; - timeout?: number; - } - - interface Response extends HttpIncomingMessage { - body?: Object|string|Buffer; - } - - interface Callback { - (err?: Error, data?: TData, res?: Response): any; - } - - namespace Acl { - - interface CreateOptions extends CommonOptions { - name?: string; - type?: string; - rules?: string; - } - - interface UpdateOptions extends CommonOptions { - id: string; - name?: string; - type?: string; - rules?: string; - } - - interface DestroyOptions extends CommonOptions { - id: string; - } - - interface InfoOptions extends CommonOptions { - id: string; - } - - interface GetOptions extends InfoOptions {} - - interface CloneOptions extends CommonOptions { - id: string; - } - - interface ListOptions extends CommonOptions {} - } - - interface Acl { - consul: Consul; - - /** - * Creates a new token with policy - */ - create: { - (opts: Acl.CreateOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Acl.CreateOptions): Thenable; - }; - - /** - * Update the policy of a token - */ - update: { - (opts: Acl.UpdateOptions, callback: Callback): void; - (opts: Acl.UpdateOptions): Thenable; - } - - /** - * Destroys a given token - */ - destroy: { - (id: string, callback: Callback): void; - (opts: Acl.DestroyOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Acl.DestroyOptions): Thenable; - }; - - /** - * Queries the policy of a given token - */ - info: { - (id: string, callback: Callback): void; - (opts: Acl.InfoOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Acl.InfoOptions): Thenable; - }; - get: { - (id: string, callback: Callback): void; - (opts: Acl.GetOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Acl.GetOptions): Thenable; - }; - - /** - * Creates a new token by cloning an existing token - */ - clone: { - (id: string, callback: Callback): void; - (opts: Acl.CloneOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Acl.CloneOptions): Thenable; - }; - - /** - * Lists all the active tokens - */ - list: { - (opts: Acl.ListOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Acl.ListOptions): Thenable; - }; - } - - interface AclStatic { - new (consul: Consul): Acl; - } - - namespace Agent { - - namespace Check { - - interface ListOptions extends CommonOptions {} - - interface RegisterOptions extends CommonOptions { - name: string; - id?: string; - serviceid?: string; - http?: string; - script?: string; - interval?: string; - ttl?: string; - notes?: string; - status?: string; - } - - interface DeregisterOptions extends CommonOptions { - id: string; - } - - interface PassOptions extends CommonOptions { - id: string; - note?: string; - } - - interface WarnOptions extends CommonOptions { - id: string; - note?: string; - } - - interface FailOptions extends CommonOptions { - id: string; - note?: string; - } - } - - interface Check { - consul: Consul; - - /** - * Returns the checks the local agent is managing - */ - list: { - (opts: Check.ListOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Check.ListOptions): Thenable; - }; - - /** - * Registers a new local check - */ - register: { - (opts: Check.RegisterOptions, callback: Callback): void; - (opts: Check.RegisterOptions): Thenable; - }; - - /** - * Deregister a local check - */ - deregister: { - (id: string, callback: Callback): void; - (opts: Check.DeregisterOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Check.DeregisterOptions): Thenable; - }; - - /** - * Mark a local test as passing - */ - pass: { - (id: string, callback: Callback): void; - (opts: Check.PassOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Check.PassOptions): Thenable; - }; - - /** - * Mark a local test as warning - */ - warn: { - (id: string, callback: Callback): void; - (opts: Check.WarnOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Check.WarnOptions): Thenable; - }; - - /** - * Mark a local test as critical - */ - fail: { - (id: string, callback: Callback): void; - (opts: Check.FailOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Check.FailOptions): Thenable; - }; - } - - interface CheckStatic { - new (consul: Consul): Check; - } - - namespace Service { - - interface RegisterCheck { - http?: string; - script?: string; - interval?: string; - ttl?: string; - notes?: string; - status?: string; - } - - interface ListOptions extends CommonOptions {} - - interface RegisterOptions extends CommonOptions { - name: string; - id?: string; - tags?: string[]; - address?: string; - port?: number; - check?: RegisterCheck; - checks?: RegisterCheck[]; - } - - interface DeregisterOptions extends CommonOptions { - id: string; - } - - interface MaintenanceOptions extends CommonOptions { - id: string; - enable: boolean; - reason?: string; - } - } - - interface Service { - consul: Consul; - - /** - * Returns the services local agent is managing - */ - list: { - (opts: Service.ListOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Service.ListOptions): Thenable; - }; - - /** - * Registers a new local service - */ - register: { - (name: string, callback: Callback): void; - (opts: Service.RegisterOptions, callback: Callback): void; - (name: string): Thenable; - (opts: Service.RegisterOptions): Thenable; - }; - - /** - * Deregister a local service - */ - deregister: { - (id: string, callback: Callback): void; - (opts: Service.DeregisterOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Service.DeregisterOptions): Thenable; - }; - - /** - * Manages node maintenance mode - */ - maintenance: { - (opts: Service.MaintenanceOptions, callback: Callback): void; - (opts: Service.MaintenanceOptions): Thenable; - }; - } - - interface ServiceStatic { - new (consul: Consul): Service; - } - - interface ChecksOptions extends Check.ListOptions {} - - interface ServicesOptions extends Service.ListOptions {} - - interface MembersOptions extends CommonOptions { - wan?: boolean; - } - - interface SelfOptions extends CommonOptions {} - - interface MaintenanceOptions extends CommonOptions { - enable: boolean; - reason?: string; - } - - interface JoinOptions extends CommonOptions { - address: string; - wan?: boolean; - } - - interface ForceLeaveOptions extends CommonOptions { - node: string; - } - } - - interface Agent { - consul: Consul; - check: Agent.Check; - service: Agent.Service; - - /** - * Returns the checks the local agent is managing - */ - checks: { - (opts: Agent.ChecksOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Agent.ChecksOptions): Thenable; - }; - - /** - * Returns the services local agent is managing - */ - services: { - (opts: Agent.ServicesOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Agent.ServicesOptions): Thenable; - }; - - /** - * Returns the members as seen by the local consul agent - */ - members: { - (opts: Agent.MembersOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Agent.MembersOptions): Thenable; - }; - - /** - * Returns the local node configuration - */ - self: { - (opts: Agent.SelfOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Agent.SelfOptions): Thenable; - }; - - /** - * Manages node maintenance mode - */ - maintenance: { - (enable: boolean, callback: Callback): void; - (opts: Agent.MaintenanceOptions, callback: Callback): void; - (enable: boolean): Thenable; - (opts: Agent.MaintenanceOptions): Thenable; - }; - - /** - * Trigger local agent to join a node - */ - join: { - (address: string, callback: Callback): void; - (opts: Agent.JoinOptions, callback: Callback): void; - (address: string): Thenable; - (opts: Agent.JoinOptions): Thenable; - }; - - /** - * Force remove node - */ - forceLeave: { - (node: string, callback: Callback): void; - (opts: Agent.ForceLeaveOptions, callback: Callback): void; - (node: string): Thenable; - (opts: Agent.ForceLeaveOptions): Thenable; - }; - } - - interface AgentStatic { - new (consul: Consul): Agent; - - Check: Agent.CheckStatic; - Service: Agent.ServiceStatic; - } - - namespace Catalog { - - namespace Node { - - interface ListOptions extends CommonOptions { - dc?: string; - } - - interface ServicesOptions extends CommonOptions { - node: string; - } - } - - interface Node { - consul: Consul; - - /** - * Lists nodes in a given DC - */ - list: { - (dc: string, callback: Callback): void; - (opts: Node.ListOptions, callback: Callback): void; - (callback: Callback): void; - (dc?: string): Thenable; - (opts?: Node.ListOptions): Thenable; - }; - - /** - * Lists the services provided by a node - */ - services: { - (node: string, callback: Callback): void; - (opts: Node.ServicesOptions, callback: Callback): void; - (node: string): Thenable; - (opts: Node.ServicesOptions): Thenable; - }; - } - - interface NodeStatic { - new(consul: Consul): Node; - } - - namespace Service { - - interface ListOptions extends CommonOptions { - dc?: string; - } - - interface NodesOptions extends CommonOptions { - service: string; - dc?: string; - tag?: string; - } - } - - - - interface Service { - consul: Consul; - - /** - * Lists services in a given DC - */ - list: { - (dc: string, callback: Callback): void; - (opts: Service.ListOptions, callback: Callback): void; - (callback: Callback): void; - (dc?: string): Thenable; - (opts?: Service.ListOptions): Thenable; - }; - - /** - * Lists the nodes in a given service - */ - nodes: { - (service: string, callback: Callback): void; - (opts: Service.NodesOptions, callback: Callback): void; - (service: string): Thenable; - (opts: Service.NodesOptions): Thenable; - }; - } - - interface ServiceStatic { - new(consul: Consul): Service; - } - - interface DatacentersOptions extends CommonOptions {} - - interface NodesOptions extends Node.ListOptions {} - - interface ServicesOptions extends Service.ListOptions {} - } - - interface Catalog { - consul: Consul; - node: Catalog.Node; - service: Catalog.Service; - - /** - * Lists known datacenters - */ - datacenters: { - (opts: Catalog.DatacentersOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Catalog.DatacentersOptions): Thenable; - }; - - /** - * Lists nodes in a given DC - */ - nodes: { - (dc: string, callback: Callback): void; - (opts: Catalog.NodesOptions, callback: Callback): void; - (callback: Callback): void; - (dc?: string): Thenable; - (opts?: Catalog.NodesOptions): Thenable; - }; - - /** - * Lists services in a given DC - */ - services: { - (dc: string, callback: Callback): void; - (opts: Catalog.ServicesOptions, callback: Callback): void; - (callback: Callback): void; - (dc?: string): Thenable; - (opts?: Catalog.ServicesOptions): Thenable; - }; - } - - interface CatalogStatic { - new(consul: Consul): Catalog; - - Node: Catalog.NodeStatic; - Service: Catalog.ServiceStatic; - } - - namespace Event { - - interface FireOptions extends CommonOptions { - name: string; - payload: string|Buffer; - node?: string; - service?: string; - tag?: string; - } - - interface ListOptions extends CommonOptions { - name?: string; - } - } - - interface Event { - consul: Consul; - - /** - * Fires a new user event - */ - fire: { - (name: string, payload: string|Buffer, callback: Callback): void; - (name: string, callback: Callback): void; - (opts: Event.FireOptions, callback: Callback): void; - (name: string, payload: string|Buffer): Thenable; - (name: string): Thenable; - (opts: Event.FireOptions): Thenable; - }; - - /** - * Lists the most recent events an agent has seen - */ - list: { - (name: string, callback: Callback): void; - (opts: Event.ListOptions, callback: Callback): void; - (callback: Callback): void; - (name?: string): Thenable; - (opts?: Event.ListOptions): Thenable; - }; - } - - interface EventStatic { - new(consul: Consul): Event; - } - - namespace Health { - - interface NodeOptions extends CommonOptions { - node: string; - dc?: string; - } - - interface ChecksOptions extends CommonOptions { - service: string; - dc?: string; - } - - interface ServiceOptions extends CommonOptions { - service: string; - dc?: string; - tag?: string; - passing?: boolean; - } - - interface StateOptions extends CommonOptions { - state: string; - dc?: string; - } - } - - interface Health { - consul: Consul; - - /** - * Returns the health info of a node - */ - node: { - (node: string, callback: Callback): void; - (opts: Health.NodeOptions, callback: Callback): void; - (node: string): Thenable; - (opts: Health.NodeOptions): Thenable; - }; - - /** - * Returns the checks of a service - */ - checks: { - (service: string, callback: Callback): void; - (opts: Health.ChecksOptions, callback: Callback): void; - (service: string): Thenable; - (opts: Health.ChecksOptions): Thenable; - }; - - /** - * Returns the nodes and health info of a service - */ - service: { - (service: string, callback: Callback): void; - (opts: Health.ServiceOptions, callback: Callback): void; - (service: string): Thenable; - (opts: Health.ServiceOptions): Thenable; - }; - - /** - * Returns the checks in a given state - */ - state: { - (state: string, callback: Callback): void; - (opts: Health.StateOptions, callback: Callback): void; - (state: string): Thenable; - (opts: Health.StateOptions): Thenable; - }; - } - - interface HealthStatic { - new(consul: Consul): Health; - } - - namespace Kv { - - interface GetOptions extends CommonOptions { - key: string; - dc?: string; - recurse?: boolean; - index?: string; - wait?: string; - raw?: boolean; - buffer?: boolean; - } - - interface KeysOptions extends CommonOptions { - key: string; - dc?: string; - separator?: string; - } - - interface SetOptions extends CommonOptions { - key: string; - value: string|Buffer; - dc?: string; - flags?: number; - cas?: string; - acquire?: string; - release?: string; - } - - interface DelOptions extends CommonOptions { - key: string; - dc?: string; - recurse?: boolean; - cas?: string; - } - - interface DeleteOptions extends DelOptions {} - } - - interface Kv { - consul: Consul; - - /** - * Get - */ - get: { - (key: string, callback: Callback): void; - (opts: Kv.GetOptions, callback: Callback): void; - (key: string): Thenable; - (opts: Kv.GetOptions): Thenable; - }; - - /** - * Keys - */ - keys: { - (key: string, callback: Callback): void; - (opts: Kv.KeysOptions, callback: Callback): void; - (callback: Callback): void; - (key?: string): Thenable; - (opts?: Kv.KeysOptions): Thenable; - }; - - /** - * Set - */ - set: { - (key: string, value: string|Buffer, opts: Kv.SetOptions, callback: Callback): void; - (key: string, value: string|Buffer, callback: Callback): void; - (opts: Kv.SetOptions, callback: Callback): void; - (key: string, value: string|Buffer, opts: Kv.SetOptions): Thenable; - (key: string, value: string|Buffer): Thenable; - (opts: Kv.SetOptions): Thenable; - }; - - /** - * Delete - */ - del: { - (key: string, callback: Callback): void; - (opts: Kv.DelOptions, callback: Callback): void; - (key: string): Thenable; - (opts: Kv.DelOptions): Thenable; - }; - delete: { - (key: string, callback: Callback): void; - (opts: Kv.DeleteOptions, callback: Callback): void; - (key: string): Thenable; - (opts: Kv.DeleteOptions): Thenable; - }; - } - - interface KvStatic { - new(consul: Consul): Kv; - } - - namespace Lock { - - interface Options { - key: string; - session?: Object|string; - value?: string|Buffer; - lockwaittime?: string; - lockretrytime?: string; - } - } - - interface Lock extends NodeJS.EventEmitter { - consul: Consul; - - /** - * Acquire lock - */ - acquire(): void; - - /** - * Release lock - */ - release(): void; - } - - interface LockStatic { - new(consul: Consul, opts: Lock.Options): Lock; - } - - namespace Session { - - interface CreateOptions extends CommonOptions { - dc?: string; - lockdelay?: string; - name?: string; - node?: string; - checks?: string[]; - behavior?: string; - ttl?: string; - } - - interface DestroyOptions extends CommonOptions { - id: string; - dc?: string; - } - - interface InfoOptions extends CommonOptions { - id: string; - dc?: string; - } - - interface GetOptions extends InfoOptions {} - - interface NodeOptions extends CommonOptions { - node: string; - dc?: string; - } - - interface ListOptions extends CommonOptions { - dc?: string; - } - - interface RenewOptions extends CommonOptions { - id: string; - dc?: string; - } - } - - - interface Session { - consul: Consul; - - /** - * Creates a new session - */ - create: { - (opts: Session.CreateOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Session.CreateOptions): Thenable; - }; - - /** - * Destroys a given session - */ - destroy: { - (id: string, callback: Callback): void; - (opts: Session.DestroyOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Session.DestroyOptions): Thenable; - }; - - /** - * Queries a given session - */ - info: { - (id: string, callback: Callback): void; - (opts: Session.InfoOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Session.InfoOptions): Thenable; - }; - get: { - (id: string, callback: Callback): void; - (opts: Session.GetOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Session.GetOptions): Thenable; - }; - - /** - * Lists sessions belonging to a node - */ - node: { - (node: string, callback: Callback): void; - (opts: Session.NodeOptions, callback: Callback): void; - (node: string): Thenable; - (opts: Session.NodeOptions): Thenable; - }; - - /** - * Lists all the active sessions - */ - list: { - (opts: Session.ListOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Session.ListOptions): Thenable; - }; - - /** - * Renews a TTL-based session - */ - renew: { - (id: string, callback: Callback): void; - (opts: Session.RenewOptions, callback: Callback): void; - (id: string): Thenable; - (opts: Session.RenewOptions): Thenable; - }; - } - - interface SessionStatic { - new(consul: Consul): Session; - } - - namespace Status { - - interface LeaderOptions extends CommonOptions {} - - interface PeersOptions extends CommonOptions {} - } - - interface Status { - consul: Consul; - - /** - * Returns the current Raft leader. - */ - leader: { - (opts: Status.LeaderOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Status.LeaderOptions): Thenable; - }; - - /** - * Returns the current Raft peer set - */ - peers: { - (opts: Status.PeersOptions, callback: Callback): void; - (callback: Callback): void; - (opts?: Status.PeersOptions): Thenable; - }; - } - - interface StatusStatic { - new(consul: Consul): Status; - } - - namespace Watch { - - interface Options { - method: Function; - options?: CommonOptions; - } - } - - interface Watch extends NodeJS.EventEmitter { - consul: Consul; - - /** - * Is running - */ - isRunning(): boolean; - - /** - * Update time - */ - updateTime(): number; - - /** - * End watch - */ - end(): void; - } - - interface WatchStatic { - new(consul: Consul, opts: Watch.Options): Watch; - } - - interface ConsulOptions { - host?: string; - port?: string; - secure?: boolean; - ca?: string[]; - defaults?: CommonOptions; - promisify?: boolean|Function; - } - - interface Consul { - acl: Acl; - agent: Agent; - catalog: Catalog; - event: Event; - health: Health; - kv: Kv; - session: Session; - status: Status; - - /** - * Lock helper. - */ - lock(opts: Lock.Options): Lock; - - /** - * Watch helper. - */ - watch(opts: Watch.Options): Watch; - } - - interface ConsulStatic { - (opts?: ConsulOptions): Consul; - new (opts?: ConsulOptions): Consul; - - Acl: AclStatic; - Agent: AgentStatic; - Catalog: CatalogStatic; - Event: EventStatic; - Health: HealthStatic; - Kv: KvStatic; - Lock: LockStatic; - Session: SessionStatic; - Status: StatusStatic; - Watch: WatchStatic; - } - } - - let Consul: Consul.ConsulStatic; - - export = Consul; + + +import {IncomingMessage as HttpIncomingMessage} from "http"; + +declare namespace Consul { + + interface Thenable { + then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => void): Thenable; + catch(onRejected?: (error: any) => U | Thenable): Thenable; + } + + interface CommonOptions { + consistent?: boolean; + dc?: string; + stale?: boolean; + token?: string; + wait?: string; + wan?: boolean; + + ctx?: NodeJS.EventEmitter; + timeout?: number; + } + + interface Response extends HttpIncomingMessage { + body?: Object | string | Buffer; + } + + interface Callback { + (err?: Error, data?: TData, res?: Response): any; + } + + namespace Acl { + + interface CreateOptions extends CommonOptions { + name?: string; + type?: string; + rules?: string; + } + + interface UpdateOptions extends CommonOptions { + id: string; + name?: string; + type?: string; + rules?: string; + } + + interface DestroyOptions extends CommonOptions { + id: string; + } + + interface InfoOptions extends CommonOptions { + id: string; + } + + interface GetOptions extends InfoOptions { } + + interface CloneOptions extends CommonOptions { + id: string; + } + + interface ListOptions extends CommonOptions { } + } + + interface Acl { + consul: Consul; + + /** + * Creates a new token with policy + */ + create: { + (opts: Acl.CreateOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Acl.CreateOptions): Thenable; + }; + + /** + * Update the policy of a token + */ + update: { + (opts: Acl.UpdateOptions, callback: Callback): void; + (opts: Acl.UpdateOptions): Thenable; + } + + /** + * Destroys a given token + */ + destroy: { + (id: string, callback: Callback): void; + (opts: Acl.DestroyOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Acl.DestroyOptions): Thenable; + }; + + /** + * Queries the policy of a given token + */ + info: { + (id: string, callback: Callback): void; + (opts: Acl.InfoOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Acl.InfoOptions): Thenable; + }; + get: { + (id: string, callback: Callback): void; + (opts: Acl.GetOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Acl.GetOptions): Thenable; + }; + + /** + * Creates a new token by cloning an existing token + */ + clone: { + (id: string, callback: Callback): void; + (opts: Acl.CloneOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Acl.CloneOptions): Thenable; + }; + + /** + * Lists all the active tokens + */ + list: { + (opts: Acl.ListOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Acl.ListOptions): Thenable; + }; + } + + interface AclStatic { + new (consul: Consul): Acl; + } + + namespace Agent { + + namespace Check { + + interface ListOptions extends CommonOptions { } + + interface RegisterOptions extends CommonOptions { + name: string; + id?: string; + serviceid?: string; + http?: string; + script?: string; + interval?: string; + ttl?: string; + notes?: string; + status?: string; + } + + interface DeregisterOptions extends CommonOptions { + id: string; + } + + interface PassOptions extends CommonOptions { + id: string; + note?: string; + } + + interface WarnOptions extends CommonOptions { + id: string; + note?: string; + } + + interface FailOptions extends CommonOptions { + id: string; + note?: string; + } + } + + interface Check { + consul: Consul; + + /** + * Returns the checks the local agent is managing + */ + list: { + (opts: Check.ListOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Check.ListOptions): Thenable; + }; + + /** + * Registers a new local check + */ + register: { + (opts: Check.RegisterOptions, callback: Callback): void; + (opts: Check.RegisterOptions): Thenable; + }; + + /** + * Deregister a local check + */ + deregister: { + (id: string, callback: Callback): void; + (opts: Check.DeregisterOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Check.DeregisterOptions): Thenable; + }; + + /** + * Mark a local test as passing + */ + pass: { + (id: string, callback: Callback): void; + (opts: Check.PassOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Check.PassOptions): Thenable; + }; + + /** + * Mark a local test as warning + */ + warn: { + (id: string, callback: Callback): void; + (opts: Check.WarnOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Check.WarnOptions): Thenable; + }; + + /** + * Mark a local test as critical + */ + fail: { + (id: string, callback: Callback): void; + (opts: Check.FailOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Check.FailOptions): Thenable; + }; + } + + interface CheckStatic { + new (consul: Consul): Check; + } + + namespace Service { + + interface RegisterCheck { + http?: string; + script?: string; + interval?: string; + ttl?: string; + notes?: string; + status?: string; + } + + interface ListOptions extends CommonOptions { } + + interface RegisterOptions extends CommonOptions { + name: string; + id?: string; + tags?: string[]; + address?: string; + port?: number; + check?: RegisterCheck; + checks?: RegisterCheck[]; + } + + interface DeregisterOptions extends CommonOptions { + id: string; + } + + interface MaintenanceOptions extends CommonOptions { + id: string; + enable: boolean; + reason?: string; + } + } + + interface Service { + consul: Consul; + + /** + * Returns the services local agent is managing + */ + list: { + (opts: Service.ListOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Service.ListOptions): Thenable; + }; + + /** + * Registers a new local service + */ + register: { + (name: string, callback: Callback): void; + (opts: Service.RegisterOptions, callback: Callback): void; + (name: string): Thenable; + (opts: Service.RegisterOptions): Thenable; + }; + + /** + * Deregister a local service + */ + deregister: { + (id: string, callback: Callback): void; + (opts: Service.DeregisterOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Service.DeregisterOptions): Thenable; + }; + + /** + * Manages node maintenance mode + */ + maintenance: { + (opts: Service.MaintenanceOptions, callback: Callback): void; + (opts: Service.MaintenanceOptions): Thenable; + }; + } + + interface ServiceStatic { + new (consul: Consul): Service; + } + + interface ChecksOptions extends Check.ListOptions { } + + interface ServicesOptions extends Service.ListOptions { } + + interface MembersOptions extends CommonOptions { + wan?: boolean; + } + + interface SelfOptions extends CommonOptions { } + + interface MaintenanceOptions extends CommonOptions { + enable: boolean; + reason?: string; + } + + interface JoinOptions extends CommonOptions { + address: string; + wan?: boolean; + } + + interface ForceLeaveOptions extends CommonOptions { + node: string; + } + } + + interface Agent { + consul: Consul; + check: Agent.Check; + service: Agent.Service; + + /** + * Returns the checks the local agent is managing + */ + checks: { + (opts: Agent.ChecksOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Agent.ChecksOptions): Thenable; + }; + + /** + * Returns the services local agent is managing + */ + services: { + (opts: Agent.ServicesOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Agent.ServicesOptions): Thenable; + }; + + /** + * Returns the members as seen by the local consul agent + */ + members: { + (opts: Agent.MembersOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Agent.MembersOptions): Thenable; + }; + + /** + * Returns the local node configuration + */ + self: { + (opts: Agent.SelfOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Agent.SelfOptions): Thenable; + }; + + /** + * Manages node maintenance mode + */ + maintenance: { + (enable: boolean, callback: Callback): void; + (opts: Agent.MaintenanceOptions, callback: Callback): void; + (enable: boolean): Thenable; + (opts: Agent.MaintenanceOptions): Thenable; + }; + + /** + * Trigger local agent to join a node + */ + join: { + (address: string, callback: Callback): void; + (opts: Agent.JoinOptions, callback: Callback): void; + (address: string): Thenable; + (opts: Agent.JoinOptions): Thenable; + }; + + /** + * Force remove node + */ + forceLeave: { + (node: string, callback: Callback): void; + (opts: Agent.ForceLeaveOptions, callback: Callback): void; + (node: string): Thenable; + (opts: Agent.ForceLeaveOptions): Thenable; + }; + } + + interface AgentStatic { + new (consul: Consul): Agent; + + Check: Agent.CheckStatic; + Service: Agent.ServiceStatic; + } + + namespace Catalog { + + namespace Node { + + interface ListOptions extends CommonOptions { + dc?: string; + } + + interface ServicesOptions extends CommonOptions { + node: string; + } + } + + interface Node { + consul: Consul; + + /** + * Lists nodes in a given DC + */ + list: { + (dc: string, callback: Callback): void; + (opts: Node.ListOptions, callback: Callback): void; + (callback: Callback): void; + (dc?: string): Thenable; + (opts?: Node.ListOptions): Thenable; + }; + + /** + * Lists the services provided by a node + */ + services: { + (node: string, callback: Callback): void; + (opts: Node.ServicesOptions, callback: Callback): void; + (node: string): Thenable; + (opts: Node.ServicesOptions): Thenable; + }; + } + + interface NodeStatic { + new (consul: Consul): Node; + } + + namespace Service { + + interface ListOptions extends CommonOptions { + dc?: string; + } + + interface NodesOptions extends CommonOptions { + service: string; + dc?: string; + tag?: string; + } + } + + + + interface Service { + consul: Consul; + + /** + * Lists services in a given DC + */ + list: { + (dc: string, callback: Callback): void; + (opts: Service.ListOptions, callback: Callback): void; + (callback: Callback): void; + (dc?: string): Thenable; + (opts?: Service.ListOptions): Thenable; + }; + + /** + * Lists the nodes in a given service + */ + nodes: { + (service: string, callback: Callback): void; + (opts: Service.NodesOptions, callback: Callback): void; + (service: string): Thenable; + (opts: Service.NodesOptions): Thenable; + }; + } + + interface ServiceStatic { + new (consul: Consul): Service; + } + + interface DatacentersOptions extends CommonOptions { } + + interface NodesOptions extends Node.ListOptions { } + + interface ServicesOptions extends Service.ListOptions { } + } + + interface Catalog { + consul: Consul; + node: Catalog.Node; + service: Catalog.Service; + + /** + * Lists known datacenters + */ + datacenters: { + (opts: Catalog.DatacentersOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Catalog.DatacentersOptions): Thenable; + }; + + /** + * Lists nodes in a given DC + */ + nodes: { + (dc: string, callback: Callback): void; + (opts: Catalog.NodesOptions, callback: Callback): void; + (callback: Callback): void; + (dc?: string): Thenable; + (opts?: Catalog.NodesOptions): Thenable; + }; + + /** + * Lists services in a given DC + */ + services: { + (dc: string, callback: Callback): void; + (opts: Catalog.ServicesOptions, callback: Callback): void; + (callback: Callback): void; + (dc?: string): Thenable; + (opts?: Catalog.ServicesOptions): Thenable; + }; + } + + interface CatalogStatic { + new (consul: Consul): Catalog; + + Node: Catalog.NodeStatic; + Service: Catalog.ServiceStatic; + } + + namespace Event { + + interface FireOptions extends CommonOptions { + name: string; + payload: string | Buffer; + node?: string; + service?: string; + tag?: string; + } + + interface ListOptions extends CommonOptions { + name?: string; + } + } + + interface Event { + consul: Consul; + + /** + * Fires a new user event + */ + fire: { + (name: string, payload: string | Buffer, callback: Callback): void; + (name: string, callback: Callback): void; + (opts: Event.FireOptions, callback: Callback): void; + (name: string, payload: string | Buffer): Thenable; + (name: string): Thenable; + (opts: Event.FireOptions): Thenable; + }; + + /** + * Lists the most recent events an agent has seen + */ + list: { + (name: string, callback: Callback): void; + (opts: Event.ListOptions, callback: Callback): void; + (callback: Callback): void; + (name?: string): Thenable; + (opts?: Event.ListOptions): Thenable; + }; + } + + interface EventStatic { + new (consul: Consul): Event; + } + + namespace Health { + + interface NodeOptions extends CommonOptions { + node: string; + dc?: string; + } + + interface ChecksOptions extends CommonOptions { + service: string; + dc?: string; + } + + interface ServiceOptions extends CommonOptions { + service: string; + dc?: string; + tag?: string; + passing?: boolean; + } + + interface StateOptions extends CommonOptions { + state: string; + dc?: string; + } + } + + interface Health { + consul: Consul; + + /** + * Returns the health info of a node + */ + node: { + (node: string, callback: Callback): void; + (opts: Health.NodeOptions, callback: Callback): void; + (node: string): Thenable; + (opts: Health.NodeOptions): Thenable; + }; + + /** + * Returns the checks of a service + */ + checks: { + (service: string, callback: Callback): void; + (opts: Health.ChecksOptions, callback: Callback): void; + (service: string): Thenable; + (opts: Health.ChecksOptions): Thenable; + }; + + /** + * Returns the nodes and health info of a service + */ + service: { + (service: string, callback: Callback): void; + (opts: Health.ServiceOptions, callback: Callback): void; + (service: string): Thenable; + (opts: Health.ServiceOptions): Thenable; + }; + + /** + * Returns the checks in a given state + */ + state: { + (state: string, callback: Callback): void; + (opts: Health.StateOptions, callback: Callback): void; + (state: string): Thenable; + (opts: Health.StateOptions): Thenable; + }; + } + + interface HealthStatic { + new (consul: Consul): Health; + } + + namespace Kv { + + interface GetOptions extends CommonOptions { + key: string; + dc?: string; + recurse?: boolean; + index?: string; + wait?: string; + raw?: boolean; + buffer?: boolean; + } + + interface KeysOptions extends CommonOptions { + key: string; + dc?: string; + separator?: string; + } + + interface SetOptions extends CommonOptions { + key: string; + value: string | Buffer; + dc?: string; + flags?: number; + cas?: string; + acquire?: string; + release?: string; + } + + interface DelOptions extends CommonOptions { + key: string; + dc?: string; + recurse?: boolean; + cas?: string; + } + + interface DeleteOptions extends DelOptions { } + } + + interface Kv { + consul: Consul; + + /** + * Get + */ + get: { + (key: string, callback: Callback): void; + (opts: Kv.GetOptions, callback: Callback): void; + (key: string): Thenable; + (opts: Kv.GetOptions): Thenable; + }; + + /** + * Keys + */ + keys: { + (key: string, callback: Callback): void; + (opts: Kv.KeysOptions, callback: Callback): void; + (callback: Callback): void; + (key?: string): Thenable; + (opts?: Kv.KeysOptions): Thenable; + }; + + /** + * Set + */ + set: { + (key: string, value: string | Buffer, opts: Kv.SetOptions, callback: Callback): void; + (key: string, value: string | Buffer, callback: Callback): void; + (opts: Kv.SetOptions, callback: Callback): void; + (key: string, value: string | Buffer, opts: Kv.SetOptions): Thenable; + (key: string, value: string | Buffer): Thenable; + (opts: Kv.SetOptions): Thenable; + }; + + /** + * Delete + */ + del: { + (key: string, callback: Callback): void; + (opts: Kv.DelOptions, callback: Callback): void; + (key: string): Thenable; + (opts: Kv.DelOptions): Thenable; + }; + delete: { + (key: string, callback: Callback): void; + (opts: Kv.DeleteOptions, callback: Callback): void; + (key: string): Thenable; + (opts: Kv.DeleteOptions): Thenable; + }; + } + + interface KvStatic { + new (consul: Consul): Kv; + } + + namespace Lock { + + interface Options { + key: string; + session?: Object | string; + value?: string | Buffer; + lockwaittime?: string; + lockretrytime?: string; + } + } + + interface Lock extends NodeJS.EventEmitter { + consul: Consul; + + /** + * Acquire lock + */ + acquire(): void; + + /** + * Release lock + */ + release(): void; + } + + interface LockStatic { + new (consul: Consul, opts: Lock.Options): Lock; + } + + namespace Session { + + interface CreateOptions extends CommonOptions { + dc?: string; + lockdelay?: string; + name?: string; + node?: string; + checks?: string[]; + behavior?: string; + ttl?: string; + } + + interface DestroyOptions extends CommonOptions { + id: string; + dc?: string; + } + + interface InfoOptions extends CommonOptions { + id: string; + dc?: string; + } + + interface GetOptions extends InfoOptions { } + + interface NodeOptions extends CommonOptions { + node: string; + dc?: string; + } + + interface ListOptions extends CommonOptions { + dc?: string; + } + + interface RenewOptions extends CommonOptions { + id: string; + dc?: string; + } + } + + + interface Session { + consul: Consul; + + /** + * Creates a new session + */ + create: { + (opts: Session.CreateOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Session.CreateOptions): Thenable; + }; + + /** + * Destroys a given session + */ + destroy: { + (id: string, callback: Callback): void; + (opts: Session.DestroyOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Session.DestroyOptions): Thenable; + }; + + /** + * Queries a given session + */ + info: { + (id: string, callback: Callback): void; + (opts: Session.InfoOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Session.InfoOptions): Thenable; + }; + get: { + (id: string, callback: Callback): void; + (opts: Session.GetOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Session.GetOptions): Thenable; + }; + + /** + * Lists sessions belonging to a node + */ + node: { + (node: string, callback: Callback): void; + (opts: Session.NodeOptions, callback: Callback): void; + (node: string): Thenable; + (opts: Session.NodeOptions): Thenable; + }; + + /** + * Lists all the active sessions + */ + list: { + (opts: Session.ListOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Session.ListOptions): Thenable; + }; + + /** + * Renews a TTL-based session + */ + renew: { + (id: string, callback: Callback): void; + (opts: Session.RenewOptions, callback: Callback): void; + (id: string): Thenable; + (opts: Session.RenewOptions): Thenable; + }; + } + + interface SessionStatic { + new (consul: Consul): Session; + } + + namespace Status { + + interface LeaderOptions extends CommonOptions { } + + interface PeersOptions extends CommonOptions { } + } + + interface Status { + consul: Consul; + + /** + * Returns the current Raft leader. + */ + leader: { + (opts: Status.LeaderOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Status.LeaderOptions): Thenable; + }; + + /** + * Returns the current Raft peer set + */ + peers: { + (opts: Status.PeersOptions, callback: Callback): void; + (callback: Callback): void; + (opts?: Status.PeersOptions): Thenable; + }; + } + + interface StatusStatic { + new (consul: Consul): Status; + } + + namespace Watch { + + interface Options { + method: Function; + options?: CommonOptions; + } + } + + interface Watch extends NodeJS.EventEmitter { + consul: Consul; + + /** + * Is running + */ + isRunning(): boolean; + + /** + * Update time + */ + updateTime(): number; + + /** + * End watch + */ + end(): void; + } + + interface WatchStatic { + new (consul: Consul, opts: Watch.Options): Watch; + } + + interface ConsulOptions { + host?: string; + port?: string; + secure?: boolean; + ca?: string[]; + defaults?: CommonOptions; + promisify?: boolean | Function; + } + + interface Consul { + acl: Acl; + agent: Agent; + catalog: Catalog; + event: Event; + health: Health; + kv: Kv; + session: Session; + status: Status; + + /** + * Lock helper. + */ + lock(opts: Lock.Options): Lock; + + /** + * Watch helper. + */ + watch(opts: Watch.Options): Watch; + } + + interface ConsulStatic { + (opts?: ConsulOptions): Consul; + new (opts?: ConsulOptions): Consul; + + Acl: AclStatic; + Agent: AgentStatic; + Catalog: CatalogStatic; + Event: EventStatic; + Health: HealthStatic; + Kv: KvStatic; + Lock: LockStatic; + Session: SessionStatic; + Status: StatusStatic; + Watch: WatchStatic; + } } + +declare let Consul: Consul.ConsulStatic; + +export = Consul; diff --git a/contentful-resolve-response/contentful-resolve-response.d.ts b/contentful-resolve-response/contentful-resolve-response.d.ts index bd2daef9e6..ba04d42b5c 100644 --- a/contentful-resolve-response/contentful-resolve-response.d.ts +++ b/contentful-resolve-response/contentful-resolve-response.d.ts @@ -3,7 +3,6 @@ // Definitions by: Anton Karsten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'contentful-resolve-response' { - function resolveResponse(response: any): any; - export = resolveResponse; -} + +declare function resolveResponse(response: any): any; +export = resolveResponse; diff --git a/contextjs/contextjs.d.ts b/contextjs/contextjs.d.ts index 3ae8c54502..b36003e3dc 100644 --- a/contextjs/contextjs.d.ts +++ b/contextjs/contextjs.d.ts @@ -3,31 +3,30 @@ // Definitions by: Kern Handa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "contextjs" { - interface MenuObject { - action?: (e: Event) => void; - divider?: boolean; - header?: string; - href?: string; - subMenu?: MenuObject[]; - target?: string; - text?: string; - } - interface InitSettings { - above?: string | boolean; - compress?: boolean; - fadeSpeed?: number; - filter?: (e: Element) => void; - preventDoubleContext?: boolean; - } - - namespace context { - function init(settings?: InitSettings): void; - function destroy(selector: any): void; - function attach(selector: any, menuObjects: MenuObject[]): void; - function settings(settings: InitSettings): void; - } - - export = context; +interface MenuObject { + action?: (e: Event) => void; + divider?: boolean; + header?: string; + href?: string; + subMenu?: MenuObject[]; + target?: string; + text?: string; } + +interface InitSettings { + above?: string | boolean; + compress?: boolean; + fadeSpeed?: number; + filter?: (e: Element) => void; + preventDoubleContext?: boolean; +} + +declare namespace context { + function init(settings?: InitSettings): void; + function destroy(selector: any): void; + function attach(selector: any, menuObjects: MenuObject[]): void; + function settings(settings: InitSettings): void; +} + +export = context; diff --git a/convert-source-map/convert-source-map.d.ts b/convert-source-map/convert-source-map.d.ts index 76b31445fb..6ae6c712f4 100644 --- a/convert-source-map/convert-source-map.d.ts +++ b/convert-source-map/convert-source-map.d.ts @@ -3,25 +3,24 @@ // Definitions by: Andrew Gaspar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "convert-source-map" { - export interface SourceMapConverter { - toObject(): any; - toJSON(space?: any): string; - toBase64(): string; - toComment(): string; - addProperty(key: string, value: any): SourceMapConverter; - setProperty(key: string, value: any): SourceMapConverter; +export interface SourceMapConverter { + toObject(): any; + toJSON(space?: any): string; + toBase64(): string; + toComment(): string; - getProperty(key: string): any; - } + addProperty(key: string, value: any): SourceMapConverter; + setProperty(key: string, value: any): SourceMapConverter; - export function removeComments(src: string): string; - export var commentRegex: RegExp; - - export function fromObject(obj: any): SourceMapConverter; - export function fromJSON(json: string): SourceMapConverter; - export function fromBase64(base64: string): SourceMapConverter; - export function fromComment(comment: string): SourceMapConverter; - export function fromSource(source: string): SourceMapConverter; + getProperty(key: string): any; } + +declare export function removeComments(src: string): string; +declare export var commentRegex: RegExp; + +declare export function fromObject(obj: any): SourceMapConverter; +declare export function fromJSON(json: string): SourceMapConverter; +declare export function fromBase64(base64: string): SourceMapConverter; +declare export function fromComment(comment: string): SourceMapConverter; +declare export function fromSource(source: string): SourceMapConverter; diff --git a/convict/convict.d.ts b/convict/convict.d.ts index 05323de269..c99255828d 100644 --- a/convict/convict.d.ts +++ b/convict/convict.d.ts @@ -3,75 +3,73 @@ // Definitions by: Wim Looman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "convict" { - namespace convict { - interface Format { - name?: string; - validate?: (val: any) => void; - coerce?: (val: any) => any; - } +declare namespace convict { - interface Schema { - [name: string]: convict.Schema | { - default: any; - doc?: string; - /** - * From the implementation: - * - * format can be a: - * - predefine type, as seen below - * - an array of enumerated values, e.g. ["production", "development", "testing"] - * - built-in JavaScript type, i.e. Object, Array, String, Number, Boolean - * - or if omitted, the Object.prototype.toString.call of the default value - * - * The docs also state that any function that validates is ok too - */ - format?: string | Array | Function; - env?: string; - arg?: string; - }; - } - - interface Config { - get(name: string): any; - default(name: string): any; - has(name: string): boolean; - set(name: string, value: any): void; - load(conf: Object): void; - loadFile(file: string): void; - loadFile(files: string[]): void; - validate(): void; - /** - * Exports all the properties (that is the keys and their current values) as a {JSON} {Object} - * @returns {Object} A {JSON} compliant {Object} - */ - getProperties() : Object; - /** - * Exports the schema as a {JSON} {Object} - * @returns {Object} A {JSON} compliant {Object} - */ - getSchema() : Object; - - /** - * Exports all the properties (that is the keys and their current values) as a JSON string. - * @returns {String} a string representing this object - */ - toString() : string; - - /** - * Exports the schema as a JSON string. - * @returns {String} a string representing the schema of this {Config} - */ - getSchemaString() : string; - } + interface Format { + name?: string; + validate?: (val: any) => void; + coerce?: (val: any) => any; } - interface convict { - addFormat(format: convict.Format): void; - addFormats(formats: { [name: string]: convict.Format }): void; - (config: convict.Schema): convict.Config; + + interface Schema { + [name: string]: convict.Schema | { + default: any; + doc?: string; + /** + * From the implementation: + * + * format can be a: + * - predefine type, as seen below + * - an array of enumerated values, e.g. ["production", "development", "testing"] + * - built-in JavaScript type, i.e. Object, Array, String, Number, Boolean + * - or if omitted, the Object.prototype.toString.call of the default value + * + * The docs also state that any function that validates is ok too + */ + format?: string | Array | Function; + env?: string; + arg?: string; + }; + } + + interface Config { + get(name: string): any; + default(name: string): any; + has(name: string): boolean; + set(name: string, value: any): void; + load(conf: Object): void; + loadFile(file: string): void; + loadFile(files: string[]): void; + validate(): void; + /** + * Exports all the properties (that is the keys and their current values) as a {JSON} {Object} + * @returns {Object} A {JSON} compliant {Object} + */ + getProperties(): Object; + /** + * Exports the schema as a {JSON} {Object} + * @returns {Object} A {JSON} compliant {Object} + */ + getSchema(): Object; + + /** + * Exports all the properties (that is the keys and their current values) as a JSON string. + * @returns {String} a string representing this object + */ + toString(): string; + + /** + * Exports the schema as a JSON string. + * @returns {String} a string representing the schema of this {Config} + */ + getSchemaString(): string; } - var convict : convict; - export = convict; } - +interface convict { + addFormat(format: convict.Format): void; + addFormats(formats: { [name: string]: convict.Format }): void; + (config: convict.Schema): convict.Config; +} +declare var convict: convict; +export = convict; diff --git a/cookie-parser/cookie-parser.d.ts b/cookie-parser/cookie-parser.d.ts index b2ecb55613..2d5aad89db 100644 --- a/cookie-parser/cookie-parser.d.ts +++ b/cookie-parser/cookie-parser.d.ts @@ -5,9 +5,8 @@ /// -declare module "cookie-parser" { - import express = require('express'); - function e(secret?: string, options?: any): express.RequestHandler; - namespace e{} - export = e; -} \ No newline at end of file + +import express = require('express'); +declare function e(secret?: string, options?: any): express.RequestHandler; +declare namespace e { } +export = e; diff --git a/cookies/cookies.d.ts b/cookies/cookies.d.ts index 23621ee2ae..95b0541a53 100644 --- a/cookies/cookies.d.ts +++ b/cookies/cookies.d.ts @@ -5,96 +5,95 @@ /// -declare module "cookies" { - import * as http from "http" - namespace cookies { - interface ICookies { - /** - * This extracts the cookie with the given name from the - * Cookie header in the request. If such a cookie exists, - * its value is returned. Otherwise, nothing is returned. - */ - get(name: string): string; - /** - * This extracts the cookie with the given name from the - * Cookie header in the request. If such a cookie exists, - * its value is returned. Otherwise, nothing is returned. - */ - get(name: string, opts: IOptions): string; +import * as http from "http" - /** - * This sets the given cookie in the response and returns - * the current context to allow chaining.If the value is omitted, - * an outbound header with an expired date is used to delete the cookie. - */ - set(name: string, value: string): ICookies; - /** - * This sets the given cookie in the response and returns - * the current context to allow chaining.If the value is omitted, - * an outbound header with an expired date is used to delete the cookie. - */ - set(name: string, value: string, opts: IOptions): ICookies; - } +declare namespace cookies { + interface ICookies { + /** + * This extracts the cookie with the given name from the + * Cookie header in the request. If such a cookie exists, + * its value is returned. Otherwise, nothing is returned. + */ + get(name: string): string; + /** + * This extracts the cookie with the given name from the + * Cookie header in the request. If such a cookie exists, + * its value is returned. Otherwise, nothing is returned. + */ + get(name: string, opts: IOptions): string; - interface IOptions { - /** - * a number representing the milliseconds from Date.now() for expiry - */ - maxAge?: number; - /** - * a Date object indicating the cookie's expiration - * date (expires at the end of session by default). - */ - expires?: Date; - /** - * a string indicating the path of the cookie (/ by default). - */ - path?: string; - /** - * a string indicating the domain of the cookie (no default). - */ - domain?: string; - /** - * a boolean indicating whether the cookie is only to be sent - * over HTTPS (false by default for HTTP, true by default for HTTPS). - */ - secure?: boolean; - /** - * a boolean indicating whether the cookie is only to be sent - * over HTTPS (use this if you handle SSL not in your node process). - */ - secureProxy?: boolean; - /** - * a boolean indicating whether the cookie is only to be sent over HTTP(S), - * and not made available to client JavaScript (true by default). - */ - httpOnly?: boolean; - /** - * a boolean indicating whether the cookie is to be signed (false by default). - * If this is true, another cookie of the same name with the .sig suffix - * appended will also be sent, with a 27-byte url-safe base64 SHA1 value - * representing the hash of cookie-name=cookie-value against the first Keygrip key. - * This signature key is used to detect tampering the next time a cookie is received. - */ - signed?: boolean; - /** - * a boolean indicating whether to overwrite previously set - * cookies of the same name (false by default). If this is true, - * all cookies set during the same request with the same - * name (regardless of path or domain) are filtered out of - * the Set-Cookie header when setting this cookie. - */ - overwrite?: boolean; - } + /** + * This sets the given cookie in the response and returns + * the current context to allow chaining.If the value is omitted, + * an outbound header with an expired date is used to delete the cookie. + */ + set(name: string, value: string): ICookies; + /** + * This sets the given cookie in the response and returns + * the current context to allow chaining.If the value is omitted, + * an outbound header with an expired date is used to delete the cookie. + */ + set(name: string, value: string, opts: IOptions): ICookies; } - interface CookiesStatic { - new (request: http.IncomingMessage, response: http.ServerResponse): cookies.ICookies; - new (request: http.IncomingMessage, response: http.ServerResponse, keys?: Array): cookies.ICookies; + interface IOptions { + /** + * a number representing the milliseconds from Date.now() for expiry + */ + maxAge?: number; + /** + * a Date object indicating the cookie's expiration + * date (expires at the end of session by default). + */ + expires?: Date; + /** + * a string indicating the path of the cookie (/ by default). + */ + path?: string; + /** + * a string indicating the domain of the cookie (no default). + */ + domain?: string; + /** + * a boolean indicating whether the cookie is only to be sent + * over HTTPS (false by default for HTTP, true by default for HTTPS). + */ + secure?: boolean; + /** + * a boolean indicating whether the cookie is only to be sent + * over HTTPS (use this if you handle SSL not in your node process). + */ + secureProxy?: boolean; + /** + * a boolean indicating whether the cookie is only to be sent over HTTP(S), + * and not made available to client JavaScript (true by default). + */ + httpOnly?: boolean; + /** + * a boolean indicating whether the cookie is to be signed (false by default). + * If this is true, another cookie of the same name with the .sig suffix + * appended will also be sent, with a 27-byte url-safe base64 SHA1 value + * representing the hash of cookie-name=cookie-value against the first Keygrip key. + * This signature key is used to detect tampering the next time a cookie is received. + */ + signed?: boolean; + /** + * a boolean indicating whether to overwrite previously set + * cookies of the same name (false by default). If this is true, + * all cookies set during the same request with the same + * name (regardless of path or domain) are filtered out of + * the Set-Cookie header when setting this cookie. + */ + overwrite?: boolean; } - - const cookies: CookiesStatic; - - export = cookies } + +interface CookiesStatic { + new (request: http.IncomingMessage, response: http.ServerResponse): cookies.ICookies; + new (request: http.IncomingMessage, response: http.ServerResponse, keys?: Array): cookies.ICookies; +} + +declare const cookies: CookiesStatic; + +export = cookies diff --git a/copy-paste/copy-paste.d.ts b/copy-paste/copy-paste.d.ts index a8a844b5bf..00ec1aa127 100644 --- a/copy-paste/copy-paste.d.ts +++ b/copy-paste/copy-paste.d.ts @@ -3,44 +3,43 @@ // Definitions by: Tobias Kahlert // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'copy-paste' { - - export type CopyCallback = (err: Error) => void; - export type PasteCallback = (err: Error, content: string) => void; - - /** - * Asynchronously replaces the current contents of the clip board with text. - * - * @param {T} content Takes either a string, array, object, or readable stream. - * @return {T} Returns the same value passed in. - */ - export function copy(content: T): T; - - /** - * Asynchronously replaces the current contents of the clip board with text. - * - * @param {T} content Takes either a string, array, object, or readable stream. - * @param {CopyCallback} callback will fire when the copy operation is complete. - * @return {T} Returns the same value passed in. - */ - export function copy(content: T, callback: CopyCallback): T; - /** - * Synchronously returns the current contents of the system clip board. - * - * Note: The synchronous version of paste is not always availabled. - * An error message is shown if the synchronous version of paste is used on an unsupported platform. - * The asynchronous version of paste is always available. - * - * @return {string} Returns the current contents of the system clip board. - */ - export function paste(): string; - - /** - * Asynchronously returns the current contents of the system clip board. - * - * @param {PasteCallback} callback The contents of the system clip board are passed to the callback as the second parameter. - */ - export function paste(callback: PasteCallback): void; -} \ No newline at end of file +export type CopyCallback = (err: Error) => void; +export type PasteCallback = (err: Error, content: string) => void; + +/** + * Asynchronously replaces the current contents of the clip board with text. + * + * @param {T} content Takes either a string, array, object, or readable stream. + * @return {T} Returns the same value passed in. + */ +declare export function copy(content: T): T; + +/** + * Asynchronously replaces the current contents of the clip board with text. + * + * @param {T} content Takes either a string, array, object, or readable stream. + * @param {CopyCallback} callback will fire when the copy operation is complete. + * @return {T} Returns the same value passed in. + */ +declare export function copy(content: T, callback: CopyCallback): T; + + +/** + * Synchronously returns the current contents of the system clip board. + * + * Note: The synchronous version of paste is not always availabled. + * An error message is shown if the synchronous version of paste is used on an unsupported platform. + * The asynchronous version of paste is always available. + * + * @return {string} Returns the current contents of the system clip board. + */ +declare export function paste(): string; + +/** + * Asynchronously returns the current contents of the system clip board. + * + * @param {PasteCallback} callback The contents of the system clip board are passed to the callback as the second parameter. + */ +declare export function paste(callback: PasteCallback): void; diff --git a/core-decorators/core-decorators.d.ts b/core-decorators/core-decorators.d.ts index 30d3a6c170..18fcc95a27 100644 --- a/core-decorators/core-decorators.d.ts +++ b/core-decorators/core-decorators.d.ts @@ -3,134 +3,133 @@ // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "core-decorators" { - export interface ClassDecorator { - (target: TFunction): TFunction|void; - } - export interface ParameterDecorator { - (target: Object, propertyKey: string|symbol, parameterIndex: number): void; - } - - export interface PropertyDecorator { - (target: Object, propertyKey: string|symbol): void; - } - - export interface MethodDecorator { - (target: Object, propertyKey: string|symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor|void; - } - - export interface PropertyOrMethodDecorator extends MethodDecorator, PropertyDecorator { - (target: Object, propertyKey: string|symbol): void; - } - - export interface Deprecate extends MethodDecorator { - (message?: string, option?: DeprecateOption): MethodDecorator; - } - - export interface DeprecateOption { - url: string; - } - - export interface ThrottleOptions { - /** allows to trigger function on the leading. */ - leading?: boolean; - /** allows to trigger function on the trailing edge of the wait interval. */ - trailing?: boolean; - } - - export interface Console { - log(message?: any, ...optionalParams: any[]): void; - time(timerName?: string): void; - timeEnd(timerName?: string): void; - } - - /** - * Forces invocations of this function to always have this refer to the class instance, - * even if the function is passed around or would otherwise lose its this context. e.g. var fn = context.method; - */ - var autobind: Function; - /** - * Marks a property or method as not being writable. - */ - var readonly: PropertyOrMethodDecorator; - /** - * Checks that the marked method indeed overrides a function with the same signature somewhere on the prototype chain. - */ - var override: MethodDecorator; - /** - * Calls console.warn() with a deprecation message. Provide a custom message to override the default one. You can also provide an options hash with a url, for further reading. - */ - var deprecate: Deprecate; - /** - * Calls console.warn() with a deprecation message. Provide a custom message to override the default one. You can also provide an options hash with a url, for further reading. - */ - var deprecated: Deprecate; - /** - * Creates a new debounced function which will be invoked after wait milliseconds since the time it was invoked. Default timeout is 300 ms. - */ - var debounce: (wait: number) => MethodDecorator; - /** - * Creates a new throttled function which will be invoked in every wait milliseconds. Default timeout is 300 ms. - */ - var throttle: (wait: number, options?: ThrottleOptions) => MethodDecorator; - /** - * Suppresses any JavaScript console.warn() call while the decorated function is called. (i.e. on the stack) - */ - var suppressWarnings: MethodDecorator; - /** - * Marks a property or method as not being enumerable. - */ - var nonenumerable: PropertyOrMethodDecorator; - /** - * Marks a property or method as not being writable. - */ - var nonconfigurable: PropertyOrMethodDecorator; - /** - * Initial implementation included, likely slow. WIP. - */ - var memoize: MethodDecorator; - /** - * Immediately applies the provided function and arguments to the method, allowing you to wrap methods with arbitrary helpers like those provided by lodash. - * The first argument is the function to apply, all further arguments will be passed to that decorating function. - */ - var decorate: (func: Function, ...args: any[]) => MethodDecorator; - /** - * Prevents a property initializer from running until the decorated property is actually looked up. - * Useful to prevent excess allocations that might otherwise not be used, but be careful not to over-optimize things. - */ - var lazyInitialize: PropertyDecorator; - /** - * Mixes in all property descriptors from the provided Plain Old JavaScript Objects (aka POJOs) as arguments. - * Mixins are applied in the order they are passed, but do not override descriptors already on the class, including those inherited traditionally. - */ - var mixin: (...mixins: any[]) => ClassDecorator; - /** - * Mixes in all property descriptors from the provided Plain Old JavaScript Objects (aka POJOs) as arguments. - * Mixins are applied in the order they are passed, but do not override descriptors already on the class, including those inherited traditionally. - */ - var mixins: (...mixins: any[]) => ClassDecorator; - /** - * Uses console.time and console.timeEnd to provide function timings with a unique label whose default prefix is ClassName.method. Supply a first argument to override the prefix: - */ - var time: (label: string, console?: Console) => MethodDecorator; - - export { - autobind, - readonly, - override, - deprecate, - deprecated, - debounce, - throttle, - suppressWarnings, - nonenumerable, - nonconfigurable, - memoize, - decorate, - lazyInitialize, - mixin, - mixins, - time, - }; +export interface ClassDecorator { + (target: TFunction): TFunction | void; } + +export interface ParameterDecorator { + (target: Object, propertyKey: string | symbol, parameterIndex: number): void; +} + +export interface PropertyDecorator { + (target: Object, propertyKey: string | symbol): void; +} + +export interface MethodDecorator { + (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; +} + +export interface PropertyOrMethodDecorator extends MethodDecorator, PropertyDecorator { + (target: Object, propertyKey: string | symbol): void; +} + +export interface Deprecate extends MethodDecorator { + (message?: string, option?: DeprecateOption): MethodDecorator; +} + +export interface DeprecateOption { + url: string; +} + +export interface ThrottleOptions { + /** allows to trigger function on the leading. */ + leading?: boolean; + /** allows to trigger function on the trailing edge of the wait interval. */ + trailing?: boolean; +} + +export interface Console { + log(message?: any, ...optionalParams: any[]): void; + time(timerName?: string): void; + timeEnd(timerName?: string): void; +} + +/** + * Forces invocations of this function to always have this refer to the class instance, + * even if the function is passed around or would otherwise lose its this context. e.g. var fn = context.method; + */ +declare var autobind: Function; +/** + * Marks a property or method as not being writable. + */ +declare var readonly: PropertyOrMethodDecorator; +/** + * Checks that the marked method indeed overrides a function with the same signature somewhere on the prototype chain. + */ +declare var override: MethodDecorator; +/** + * Calls console.warn() with a deprecation message. Provide a custom message to override the default one. You can also provide an options hash with a url, for further reading. + */ +declare var deprecate: Deprecate; +/** + * Calls console.warn() with a deprecation message. Provide a custom message to override the default one. You can also provide an options hash with a url, for further reading. + */ +declare var deprecated: Deprecate; +/** + * Creates a new debounced function which will be invoked after wait milliseconds since the time it was invoked. Default timeout is 300 ms. + */ +declare var debounce: (wait: number) => MethodDecorator; +/** + * Creates a new throttled function which will be invoked in every wait milliseconds. Default timeout is 300 ms. + */ +declare var throttle: (wait: number, options?: ThrottleOptions) => MethodDecorator; +/** + * Suppresses any JavaScript console.warn() call while the decorated function is called. (i.e. on the stack) + */ +declare var suppressWarnings: MethodDecorator; +/** + * Marks a property or method as not being enumerable. + */ +declare var nonenumerable: PropertyOrMethodDecorator; +/** + * Marks a property or method as not being writable. + */ +declare var nonconfigurable: PropertyOrMethodDecorator; +/** + * Initial implementation included, likely slow. WIP. + */ +declare var memoize: MethodDecorator; +/** + * Immediately applies the provided function and arguments to the method, allowing you to wrap methods with arbitrary helpers like those provided by lodash. + * The first argument is the function to apply, all further arguments will be passed to that decorating function. + */ +declare var decorate: (func: Function, ...args: any[]) => MethodDecorator; +/** + * Prevents a property initializer from running until the decorated property is actually looked up. + * Useful to prevent excess allocations that might otherwise not be used, but be careful not to over-optimize things. + */ +declare var lazyInitialize: PropertyDecorator; +/** + * Mixes in all property descriptors from the provided Plain Old JavaScript Objects (aka POJOs) as arguments. + * Mixins are applied in the order they are passed, but do not override descriptors already on the class, including those inherited traditionally. + */ +declare var mixin: (...mixins: any[]) => ClassDecorator; +/** + * Mixes in all property descriptors from the provided Plain Old JavaScript Objects (aka POJOs) as arguments. + * Mixins are applied in the order they are passed, but do not override descriptors already on the class, including those inherited traditionally. + */ +declare var mixins: (...mixins: any[]) => ClassDecorator; +/** + * Uses console.time and console.timeEnd to provide function timings with a unique label whose default prefix is ClassName.method. Supply a first argument to override the prefix: + */ +declare var time: (label: string, console?: Console) => MethodDecorator; + +export { +autobind, +readonly, +override, +deprecate, +deprecated, +debounce, +throttle, +suppressWarnings, +nonenumerable, +nonconfigurable, +memoize, +decorate, +lazyInitialize, +mixin, +mixins, +time, +}; diff --git a/cors/cors.d.ts b/cors/cors.d.ts index eaf917fb1f..ddc601624c 100644 --- a/cors/cors.d.ts +++ b/cors/cors.d.ts @@ -5,20 +5,19 @@ /// -declare module "cors" { - import express = require('express'); - namespace e { - interface CorsOptions { - origin?: any; - methods?: any; - allowedHeaders?: any; - exposedHeaders?: any; - credentials?: boolean; - maxAge?: number; - } +import express = require('express'); + +declare namespace e { + interface CorsOptions { + origin?: any; + methods?: any; + allowedHeaders?: any; + exposedHeaders?: any; + credentials?: boolean; + maxAge?: number; } - - function e(options?: e.CorsOptions): express.RequestHandler; - export = e; } + +declare function e(options?: e.CorsOptions): express.RequestHandler; +export = e; diff --git a/couchbase/couchbase.d.ts b/couchbase/couchbase.d.ts index 351c9a806d..36dca55bea 100644 --- a/couchbase/couchbase.d.ts +++ b/couchbase/couchbase.d.ts @@ -6,1124 +6,1123 @@ /// -declare module 'couchbase' { - import events = require('events'); + +import events = require('events'); + +/** + * Enumeration of all error codes. See libcouchbase documentation for more details on what these errors represent. + */ +declare enum errors { + /** Operation was successful. **/ + success, + + /** Authentication should continue. **/ + authContinue, + + /** Error authenticating. **/ + authError, + + /** The passed incr/decr delta was invalid. **/ + deltaBadVal, + + /** Object is too large to be stored on the cluster. **/ + objectTooBig, + + /** Operation was successful. **/ + serverBusy, + + /** Server is too busy to handle your request right now. **/ + cLibInternal, + + /** An invalid arguement was passed. **/ + cLinInvalidArgument, + + /** The server is out of memory. **/ + cLibOutOfMemory, + + /** An invalid range was specified. **/ + invalidRange, + + /** An unknown error occured within libcouchbase. **/ + cLibGenericError, + + /** A temporary error occured. Try again. **/ + temporaryError, + + /** The key already exists on the server. **/ + keyAlreadyExists, + + /** The key does not exist on the server. **/ + keyNotFound, + + /** Failed to open library. **/ + failedToOpenLibrary, + + /** Failed to find expected symbol in library. **/ + failedToFindSymbol, + + /** A network error occured. **/ + networkError, + + /** Operations were performed on the incorrect server. **/ + wrongServer, + + /** Operations were performed on the incorrect server. **/ + notMyVBucket, + + /** The document was not stored. **/ + notSorted, + + /** An unsupported operation was sent to the server. **/ + notSupported, + + /** An unknown command was sent to the server. **/ + unknownCommand, + + /** An unknown host was specified. **/ + unknownHost, + + /** A protocol error occured. **/ + protocolError, + + /** The operation timed out. **/ + timedOut, + + /** Error connecting to the server. **/ + connectError, + + /** The bucket you request was not found. **/ + bukcketNotFound, + + /** libcouchbase is out of memory. **/ + clientOutOfMemory, + + /** A temporary error occured in libcouchbase. Try again. **/ + clientTemporaryError, + + /** A bad handle was passed. **/ + badHandle, + + /** A server bug caused the operation to fail. **/ + serverBug, + + /** The host format specified is invalid. **/ + invalidHostFormat, + + /** Not enough nodes to meet the operations durability requirements. **/ + notEnoughNodes, + + /** Duplicate items. **/ + duplicateItems, + + /** Key mapping failed and could not match a server. **/ + noMatchingServerForKey, + + /** A bad environment variable was specified. **/ + badEnvironmentVariable, + + /** Couchnode is out of memory. **/ + outOfMemory, + + /** Invalid arguements were passed. **/ + invalidArguments, + + /** An error occured while trying to schedule the operation. **/ + schedulingError, + + /** Not all operations completed successfully. **/ + checkResults, + + /** A generic error occured in Couchnode. **/ + genericError, + + /** The specified durability requirements could not be satisfied. **/ + durabilityFailed, + + /** An error occured during a RESTful operation. **/ + restError +} + +/** + * Represents a singular cluster containing your buckets. + */ +declare class Cluster { + /** + * Create a new instance of the Cluster class. + * @param cnstr The connection string for your cluster. + * @param options The options object. + */ + constructor(cnstr?: string, options?: ClusterConstructorOptions); /** - * Enumeration of all error codes. See libcouchbase documentation for more details on what these errors represent. + * Creates a manager allowing the management of a Couchbase cluster. */ - enum errors { - /** Operation was successful. **/ - success, + manager(): ClusterManager; - /** Authentication should continue. **/ - authContinue, + /** + * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. + * @param name The name of the bucket to open. + */ + openBucket(name?: string): Bucket; - /** Error authenticating. **/ - authError, - /** The passed incr/decr delta was invalid. **/ - deltaBadVal, + /** + * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. + * @param name The name of the bucket to open. + * @param password Password for the bucket. + */ + openBucket(name?: string, password?: string): Bucket; - /** Object is too large to be stored on the cluster. **/ - objectTooBig, + /** + * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. + * @param name The name of the bucket to open. + * @param callback Callback to invoke on connection success or failure. + */ + openBucket(name?: string, callback?: Function): Bucket; - /** Operation was successful. **/ - serverBusy, + /** + * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. + * @param name The name of the bucket to open. + * @param password Password for the bucket. + * @param callback Callback to invoke on connection success or failure. + */ + openBucket(name?: string, password?: string, callback?: Function): Bucket; +} - /** Server is too busy to handle your request right now. **/ - cLibInternal, +interface ClusterConstructorOptions { + /** + * The path to the certificate to use for SSL connections + */ + certpath: string; +} - /** An invalid arguement was passed. **/ - cLinInvalidArgument, +interface CreateBucketOptions { + /** + * The bucket name + */ + name?: string; + authType?: string, + bucketType?: string; + ramQuotaMB?: number; + replicaNumber?: number; +} - /** The server is out of memory. **/ - cLibOutOfMemory, +/** + * Class for performing management operations against a cluster. + */ +interface ClusterManager { + /** + * + * @param name + * @param callback + */ + createBucket(name: string, callback: Function): void; - /** An invalid range was specified. **/ - invalidRange, + /** + * + * @param name + * @param opts + * @param callback + */ + createBucket(name: string, opts: any, callback: Function): void; - /** An unknown error occured within libcouchbase. **/ - cLibGenericError, + /** + * + * @param callback + */ + listBuckets(callback: Function): void; - /** A temporary error occured. Try again. **/ - temporaryError, + /** + * + * @param name + * @param callback + */ + removeBucket(name: string, callback: Function): void; +} - /** The key already exists on the server. **/ - keyAlreadyExists, +/** + * The virtual class thrown for all Couchnode errors. + */ +interface CouchbaseError extends Error { + /** + * The error code for this error. + */ + code: errors; +} - /** The key does not exist on the server. **/ - keyNotFound, +interface AppendOptions { + /** + * The CAS value to check. If the item on the server contains a different CAS value, the operation will fail. Note that if this option is undefined, no comparison will be performed. + */ + cas?: Bucket.CAS; - /** Failed to open library. **/ - failedToOpenLibrary, + /** + * Ensures this operation is persisted to this many nodes. + */ + persist_to?: number; - /** Failed to find expected symbol in library. **/ - failedToFindSymbol, + /** + * Ensures this operation is replicated to this many nodes. + */ + replicate_to?: number; +} - /** A network error occured. **/ - networkError, +interface PrependOptions extends AppendOptions { } - /** Operations were performed on the incorrect server. **/ - wrongServer, +interface RemoveOptions extends AppendOptions { } - /** Operations were performed on the incorrect server. **/ - notMyVBucket, +interface ReplaceOptions extends AppendOptions { + /** + * Set the initial expiration time for the document. A value of 0 represents never expiring. + */ + expiry?: number; +} - /** The document was not stored. **/ - notSorted, +interface UpsertOptions extends ReplaceOptions { } - /** An unsupported operation was sent to the server. **/ - notSupported, +interface TouchOptions { + /** + * Ensures this operation is persisted to this many nodes. + */ + persist_to?: number; - /** An unknown command was sent to the server. **/ - unknownCommand, + /** + * Ensures this operation is replicated to this many nodes. + */ + replicate_to?: number; +} - /** An unknown host was specified. **/ - unknownHost, +interface CounterOptions { + /** + * Sets the initial value for the document if it does not exist. Specifying a value of undefined will cause the operation to fail if the document does not exist, otherwise this value must be equal to or greater than 0. + */ + initial?: number; - /** A protocol error occured. **/ - protocolError, + /** + * Set the initial expiration time for the document. A value of 0 represents never expiring. + */ + expiry?: number; - /** The operation timed out. **/ - timedOut, + /** + * Ensures this operation is persisted to this many nodes + */ + persist_to?: number; - /** Error connecting to the server. **/ - connectError, + /** + * Ensures this operation is replicated to this many nodes + */ + replicate_to?: number; +} - /** The bucket you request was not found. **/ - bukcketNotFound, +interface GetAndLockOptions { + lockTime?: number; +} - /** libcouchbase is out of memory. **/ - clientOutOfMemory, +interface GetReplicaOptions { - /** A temporary error occured in libcouchbase. Try again. **/ - clientTemporaryError, + /** + * The index for which replica you wish to retrieve this value from, or if undefined, use the value from the first server that replies. + */ + index?: number; +} - /** A bad handle was passed. **/ - badHandle, +interface InsertOptions { - /** A server bug caused the operation to fail. **/ - serverBug, + /** + * Set the initial expiration time for the document. A value of 0 represents never expiring. + */ + expiry?: number; - /** The host format specified is invalid. **/ - invalidHostFormat, + /** + * Ensures this operation is persisted to this many nodes. + */ + persist_to?: number; - /** Not enough nodes to meet the operations durability requirements. **/ - notEnoughNodes, + /** + * Ensures this operation is replicated to this many nodes. + */ + replicate_to?: number; +} - /** Duplicate items. **/ - duplicateItems, +/** + * A class for performing management operations against a bucket. This class should not be instantiated directly, but instead through the use of the Bucket#manager method instead. + */ +interface BucketManager { - /** Key mapping failed and could not match a server. **/ - noMatchingServerForKey, + /** + * Flushes the cluster, deleting all data stored within this bucket. Note that this method requires the Flush permission to be enabled on the bucket from the management console before it will work. + * @param callback The callback function. + */ + flush(callback: Function): void; - /** A bad environment variable was specified. **/ - badEnvironmentVariable, + /** + * Retrieves a specific design document from this bucket. + * @param name + * @param callback The callback function. + */ + getDesignDocument(name: string, callback: Function): void; - /** Couchnode is out of memory. **/ - outOfMemory, + /** + * Retrieves a list of all design documents registered to a bucket. + * @param callback The callback function. + */ + getDesignDocuments(callback: Function): void; - /** Invalid arguements were passed. **/ - invalidArguments, + /** + * Registers a design document to this bucket, failing if it already exists. + * @param name + * @param data + * @param callback The callback function. + * @returns {} + */ + insertDesignDocument(name: string, data: any, callback: Function): void; - /** An error occured while trying to schedule the operation. **/ - schedulingError, + /** + * Unregisters a design document from this bucket. + * @param name + * @param callback The callback function. + * @returns {} + */ + removeDesignDocument(name: string, callback: Function): void; - /** Not all operations completed successfully. **/ - checkResults, + /** + * Registers a design document to this bucket, overwriting any existing design document that was previously registered. + * @param name + * @param data + * @param callback The callback function. + * @returns {} + */ + upsertDesignDocument(name: string, data: any, callback: Function): void; +} - /** A generic error occured in Couchnode. **/ - genericError, +/** + * Class for dynamically construction of view queries. This class should never be constructed directly, instead you should use ViewQuery.from to construct this object. + */ +declare class ViewQuery { + /** + * Instantiates a ViewQuery object for the specified design document and view name. + * @param ddoc The design document to use. + * @param name The view to use. + */ + static from(ddoc: string, name: string): ViewQuery; - /** The specified durability requirements could not be satisfied. **/ - durabilityFailed, + /** + * Specifies the design document and view name to use for this query. + * @param ddoc The design document to use. + * @param name The view to use. + */ + from(ddoc: string, name: string): ViewQuery; - /** An error occured during a RESTful operation. **/ - restError + /** + * Allows you to specify custom view options that may not be available though the fluent interface defined by this class. + * @param opts + */ + custom(opts: any): ViewQuery; + + /** + * Flag to request a view request accross all nodes in the case of a development view. + * @param full_set + */ + full_set(full_set: boolean): ViewQuery; + + /** + * Specifies whether to preform grouping during view execution. + * @param group + */ + group(group: boolean): ViewQuery; + + /** + * Specifies the level at which to perform view grouping. + * @param group_level + */ + group_level(group_level: number): ViewQuery; + + /** + * Specifies a range of document id's to retrieve from the index. + * @param start + * @param end + */ + id_range(start: any, end: any): ViewQuery; + + /** + * Flag to request a view request include the full document value. + * @param include_docs + */ + include_docs(include_docs: boolean): ViewQuery; + + /** + * Specifies a specified key to retrieve from the index. + * @param key + */ + key(key: any): ViewQuery; + + /** + * Specifies a list of keys you wish to retrieve from the index. + * @param keys + */ + keys(key: any[]): ViewQuery; + + /** + * Specifies the maximum number of results to return. + * @param limit + */ + limit(limit: number): ViewQuery; + + /** + * Sets the error handling mode for this query. + * @param mode + */ + on_error(mode: ViewQuery.ErrorMode): ViewQuery; + + /** + * Specifies the desired ordering for the results. + * @param order + */ + order(order: ViewQuery.Order): ViewQuery; + + /** + * Specifies a range of keys to retrieve from the index. You may specify both a start and an end point and additionally specify whether or not the end value is inclusive or exclusive. + * @param start + * @param end + * @param inclusive_end + */ + range(start: any | any[], end: any | any[], inclusive_end?: boolean): ViewQuery; + + /** + * Specifies whether to execute the map-reduce reduce step. + * @param reduce + */ + reduce(reduce: boolean): ViewQuery; + + /** + * Specifies how many results to skip from the beginning of the result set. + * @param skip + */ + skip(skip: number): ViewQuery; + + /** + * Specifies how this query will affect view indexing, both before and after the query is executed. + * @param stale + */ + stale(stale: ViewQuery.Update): ViewQuery; +} + +declare namespace ViewQuery { + /** + * Enumeration for specifying on_error behaviour. + */ + enum ErrorMode { + /** + * Continues querying when an error occurs. + */ + CONTINUE, + + /** + * Stops and errors query when an error occurs. + */ + STOP } /** - * Represents a singular cluster containing your buckets. + * Enumeration for specifying view result ordering. */ - class Cluster { + enum Order { /** - * Create a new instance of the Cluster class. - * @param cnstr The connection string for your cluster. - * @param options The options object. + * Orders with lower values first and higher values last. */ - constructor(cnstr?: string, options?: ClusterConstructorOptions); + ASCENDING, /** - * Creates a manager allowing the management of a Couchbase cluster. + * Orders with higher values first and lower values last. */ - manager(): ClusterManager; - - /** - * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. - * @param name The name of the bucket to open. - */ - openBucket(name?: string): Bucket; - - - /** - * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. - * @param name The name of the bucket to open. - * @param password Password for the bucket. - */ - openBucket(name?: string, password?: string): Bucket; - - /** - * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. - * @param name The name of the bucket to open. - * @param callback Callback to invoke on connection success or failure. - */ - openBucket(name?: string, callback?: Function): Bucket; - - /** - * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. - * @param name The name of the bucket to open. - * @param password Password for the bucket. - * @param callback Callback to invoke on connection success or failure. - */ - openBucket(name?: string, password?: string, callback?: Function): Bucket; - } - - interface ClusterConstructorOptions { - /** - * The path to the certificate to use for SSL connections - */ - certpath: string; - } - - interface CreateBucketOptions { - /** - * The bucket name - */ - name?: string; - authType?: string, - bucketType?: string; - ramQuotaMB?: number; - replicaNumber?: number; + DESCENDING } /** - * Class for performing management operations against a cluster. + * Enumeration for specifying view update semantics. */ - interface ClusterManager { + enum Update { /** - * - * @param name - * @param callback + * Causes the view to be fully indexed before results are retrieved. */ - createBucket(name: string, callback: Function): void; + BEFORE, /** - * - * @param name - * @param opts - * @param callback + * Allows the index to stay in whatever state it is already in prior retrieval of the query results. */ - createBucket(name: string, opts: any, callback: Function): void; + NONE, /** - * - * @param callback + * Forces the view to be indexed after the results of this query has been fetched. */ - listBuckets(callback: Function): void; + AFTER + } +} + +/** + * Class for dynamically construction of N1QL queries. This class should never be constructed directly, instead you should use the N1qlQuery.fromString static method to instantiate a N1qlStringQuery. + */ +declare class N1qlQuery { + /** + * Creates a query object directly from the passed query string. + * @param str + */ + static fromString(str: string): N1qlStringQuery; + + /** + * Returns the fully prepared string representation of this query. + */ + toString(): string; +} + +declare namespace N1qlQuery { + /** + * Enumeration for specifying N1QL consistency semantics. + */ + enum Consistency { + /** + * This is the default (for single-statement requests). + */ + NOT_BOUND, /** - * - * @param name - * @param callback + * This implements strong consistency per request. */ - removeBucket(name: string, callback: Function): void; + REQUEST_PLUS, + + /** + * This implements strong consistency per statement. + */ + STATEMENT_PLUS + } +} + +/** + * Class for holding a explicitly defined N1QL query string. + */ +declare class N1qlStringQuery extends N1qlQuery { + /** + * Specifies whether this query is adhoc or should be prepared. + * @param adhoc + */ + adhoc(adhoc: boolean): N1qlStringQuery; + + /** + * Specify the consistency level for this query. + * @param val + */ + consistency(val: N1qlQuery.Consistency): N1qlStringQuery; + + /** + * Returns the fully prepared object representation of this query. + */ + toObject(): any; + + /** + * Returns the fully prepared string representation of this query. + */ + toString(): string; +} + +/** + * Class for dynamically construction of spatial queries. This class should never be constructed directly, instead you should use SpatialQuery.from to construct this object. + */ +declare class SpatialQuery { + /** + * Instantiates a SpatialQuery object for the specified design document and view name. + * @param ddoc The design document to use. + * @param name The view to use. + */ + static from(ddoc: string, name: string): SpatialQuery; + + /** + * Specifies the design document and view name to use for this query. + * @param ddoc + * @param name + */ + from(ddoc: string, name: string): SpatialQuery; + + /** + * Specifies a bounding box to query the index for. This value must be an array of exactly 4 numbers which represents the left, top, right and bottom edges of the bounding box (in that order). + * @param bbox + */ + bbox(bbox: number[]): SpatialQuery; + + /** + * Allows you to specify custom view options that may not be available though the fluent interface defined by this class. + * @param opts + */ + custom(opts: any): SpatialQuery; + + /** + * Specifies the maximum number of results to return. + * @param limit + */ + limit(limit: number): SpatialQuery; + + /** + * Specifies how many results to skip from the beginning of the result set. + * @param skip + */ + skip(skip: number): SpatialQuery; + + /** + * Specifies how this query will affect view indexing, both before and after the query is executed. + * @param stale + */ + stale(stale: SpatialQuery.Update): SpatialQuery; +} + +declare namespace SpatialQuery { + /** + * Enumeration for specifying view update semantics. + */ + enum Update { + /** + * Causes the view to be fully indexed before results are retrieved. + */ + BEFORE, + + /** + * Allows the index to stay in whatever state it is already in prior retrieval of the query results. + */ + NONE, + + /** + * Forces the view to be indexed after the results of this query has been fetched. + */ + AFTER + } +} + +/** + * The Bucket class represents a connection to a Couchbase bucket. Never instantiate this class directly. Instead use the Cluster#openBucket method instead. + */ +interface Bucket { + /** + * Returns the version of the Node.js library as a string. + */ + clientVersion: string; + + /** + * Gets or sets the config throttling in milliseconds. The config throttling is the time that Bucket will wait before forcing a configuration refresh. If no refresh occurs before this period while a configuration is marked invalid, an update will be triggered. + */ + configThrottle: number; + + /** + * Sets or gets the connection timeout in milliseconds. This is the timeout value used when connecting to the configuration port during the initial connection (in this case, use this as a key in the 'options' parameter in the constructor) and/or when Bucket attempts to reconnect in-situ (if the current connection has failed). + */ + connectionTimeout: number; + + /** + * Gets or sets the durability interval in milliseconds. The durability interval is the time that Bucket will wait between requesting new durability information during a durability poll. + */ + durabilityInterval: number; + + /** + * Gets or sets the durability timeout in milliseconds. The durability timeout is the time that Bucket will wait for a response from the server in regards to a durability request. If there are no responses received within this time frame, the request fails with an error. + */ + durabilityTimeout: number; + + /** + * Returns the libcouchbase version as a string. This information will usually be in the format of 2.4.0-fffffff representing the major, minor, patch and git-commit that the built libcouchbase is based upon. + */ + lcbVersion: string; + + /** + * Gets or sets the management timeout in milliseconds. The management timeout is the time that Bucket will wait for a response from the server for a management request. If the response is not received within this time frame, the request is failed out with an error. + */ + managementTimeout: number; + + /** + * Sets or gets the node connection timeout in msecs. This value is similar to Bucket#connectionTimeout, but defines the time to wait for a particular node to respond before trying the next one. + */ + nodeConnectionTimeout: number; + + /** + * Gets or sets the operation timeout in milliseconds. The operation timeout is the time that Bucket will wait for a response from the server for a CRUD operation. If the response is not received within this time frame, the operation is failed with an error. + */ + operationTimeout: number; + + /** + * Gets or sets the view timeout in milliseconds. The view timeout is the time that Bucket will wait for a response from the server for a view request. If the response is not received within this time frame, the request fails with an error. + */ + viewTimeout: number; + + /** + * Similar to Bucket#upsert, but instead of setting a new key, it appends data to the existing key. Note that this function only makes sense when the stored data is a string; 'appending' to a JSON document may result in parse errors when the document is later retrieved. + * @param key The target document key. + * @param fragment The document's contents to append. + * @param callback The callback function. + */ + append(key: any | Buffer, fragment: any, callback: Bucket.OpCallback): void; + + /** + * + * @param key The target document key. + * @param fragment The document's contents to append. + * @param options The options object. + * @param callback The callback function. + */ + append(key: any | Buffer, fragment: any, options: AppendOptions, callback: Bucket.OpCallback): void; + + /** + * Increments or decrements a key's numeric value. + * Note that JavaScript does not support 64-bit integers (while libcouchbase and the server do). You might receive an inaccurate value if the number is greater than 53-bits (JavaScript's maximum integer precision). + * @param key The target document key. + * @param delta The amount to add or subtract from the counter value. This value may be any non-zero integer. + * @param callback The callback function. + */ + counter(key: any | Buffer, delta: number, callback: Bucket.OpCallback): void; + + /** + * + * @param key The target document key. + * @param delta The amount to add or subtract from the counter value. This value may be any non-zero integer. + * @param options The options object. + * @param callback The callback function. + */ + counter(key: any | Buffer, delta: number, options: CounterOptions, callback: Bucket.OpCallback): void; + + /** + * Shuts down this connection. + */ + disconnect(): void; + + /** + * Enables N1QL support on the client. A cbq-server URI must be passed. This method will be deprecated in the future in favor of automatic configuration through the connected cluster. + * @param hosts An array of host/port combinations which are N1QL servers attached to this cluster. + */ + enableN1ql(hosts: string | string[]): void; + + /** + * Retrieves a document. + * @param key The target document key. + * @param callback The callback function. + */ + get(key: any | Buffer, callback: Bucket.OpCallback): void; + + /** + * @param key The target document key. + * @param options The options object. + * @param callback The callback function. + */ + get(key: any | Buffer, options: any, callback: Bucket.OpCallback): void; + + /** + * Lock the document on the server and retrieve it. When an document is locked, its CAS changes and subsequent operations on the document (without providing the current CAS) will fail until the lock is no longer held. + * This function behaves identically to Bucket#get in that it will return the value. It differs in that the document is also locked. This ensures that attempts by other client instances to access this document while the lock is held will fail. + * Once locked, a document can be unlocked either by explicitly calling Bucket#unlock or by performing a storage operation (e.g. Bucket#upsert, Bucket#replace, Bucket::append) with the current CAS value. Note that any other lock operations on this key will fail while a document is locked. + * @param key The target document key. + * @param callback The callback function. + */ + getAndLock(key: any, callback: Bucket.OpCallback): void; + + /** + * Lock the document on the server and retrieve it. When an document is locked, its CAS changes and subsequent operations on the document (without providing the current CAS) will fail until the lock is no longer held. + * This function behaves identically to Bucket#get in that it will return the value. It differs in that the document is also locked. This ensures that attempts by other client instances to access this document while the lock is held will fail. + * Once locked, a document can be unlocked either by explicitly calling Bucket#unlock or by performing a storage operation (e.g. Bucket#upsert, Bucket#replace, Bucket::append) with the current CAS value. Note that any other lock operations on this key will fail while a document is locked. + * @param key The target document key. + * @param options The options object. + * @param callback The callback function. + * @returns {} + */ + getAndLock(key: any, options: GetAndLockOptions, callback: Bucket.OpCallback): void; + + /** + * Retrieves a document and updates the expiry of the item at the same time. + * @param key The target document key. + * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds). + * @param options The options object. + * @param callback The callback function. + */ + getAndTouch(key: any | Buffer, expiry: number, options: any, callback: Bucket.OpCallback): void; + + /** + * Retrieves a document and updates the expiry of the item at the same time. + * @param key The target document key. + * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds). + * @param callback The callback function. + */ + getAndTouch(key: any | Buffer, expiry: number, callback: Bucket.OpCallback): void; + + /** + * Retrieves a list of keys + * @param keys The target document keys. + * @param callback The callback function. + */ + getMulti(key: any[] | Buffer[], callback: Bucket.MultiGetCallback): void; + + /** + * Get a document from a replica server in your cluster. + * @param key The target document key. + * @param callback The callback function. + */ + getReplica(key: any | Buffer, callback: Bucket.OpCallback): void; + + /** + * Get a document from a replica server in your cluster. + * @param key The target document key. + * @param options The options object. + * @param callback The callback function. + */ + getReplica(key: any | Buffer, options: GetReplicaOptions, callback: Bucket.OpCallback): void; + + /** + * Identical to Bucket#upsert but will fail if the document already exists. + * @param key The target document key. + * @param value The document's contents. + * @param callback The callback function. + */ + insert(key: any | Buffer, value: any, callback: Bucket.OpCallback): void; + + /** + * Identical to Bucket#upsert but will fail if the document already exists. + * @param key The target document key. + * @param value The document's contents. + * @param options The options object. + * @param callback The callback function. + */ + insert(key: any | Buffer, value: any, options: InsertOptions, callback: Bucket.OpCallback): void; + + /** + * Returns an instance of a BuckerManager for performing management operations against a bucket. + */ + manager(): BucketManager; + + /** + * Like Bucket#append, but prepends data to the existing value. + * @param key The target document key. + * @param fragment The document's contents to prepend. + * @param callback The callback function. + */ + prepend(key: any, fragment: any, callback: Bucket.OpCallback): void; + + /** + * Like Bucket#append, but prepends data to the existing value. + * @param key The target document key. + * @param fragment The document's contents to prepend. + * @param options The options object. + * @param callback The callback function. + */ + prepend(key: any, fragment: any, options: PrependOptions, callback: Bucket.OpCallback): void; + + /** + * Executes a previously prepared query object. This could be a ViewQuery or a N1qlQuery. + * Note: N1qlQuery queries are currently an uncommitted interface and may be subject to change in 2.0.0's final release. + * @param query The query to execute. + * @param callback The callback function. + */ + query(query: ViewQuery | N1qlQuery, callback: Bucket.QueryCallback): Bucket.ViewQueryResponse | Bucket.N1qlQueryResponse; + + /** + * Executes a previously prepared query object. This could be a ViewQuery or a N1qlQuery. + * Note: N1qlQuery queries are currently an uncommitted interface and may be subject to change in 2.0.0's final release. + * @param query The query to execute. + * @param params A list or map to do replacements on a N1QL query. + * @param callback The callback function. + */ + query(query: ViewQuery | N1qlQuery, params: Object | Array, callback: Bucket.QueryCallback): Bucket.ViewQueryResponse | Bucket.N1qlQueryResponse; + + /** + * Deletes a document on the server. + * @param key The target document key. + * @param callback The callback function. + */ + remove(key: any | Buffer, callback: Bucket.OpCallback): void; + + /** + * Deletes a document on the server. + * @param key The target document key. + * @param options The options object. + * @param callback The callback function. + */ + remove(key: any | Buffer, options: RemoveOptions, callback: Bucket.OpCallback): void; + + /** + * Identical to Bucket#upsert, but will only succeed if the document exists already (i.e. the inverse of Bucket#insert). + * @param key The target document key. + * @param value The document's contents. + * @param callback The callback function. + */ + replace(key: any | Buffer, value: any, callback: Bucket.OpCallback): void; + + /** + * Identical to Bucket#upsert, but will only succeed if the document exists already (i.e. the inverse of Bucket#insert). + * @param key The target document key. + * @param value The document's contents. + * @param options The options object. + * @param callback The callback function. + */ + replace(key: any | Buffer, value: any, options: ReplaceOptions, callback: Bucket.OpCallback): void; + + /** + * Configures a custom set of transcoder functions for encoding and decoding values that are being stored or retreived from the server. + * @param encoder The function for encoding. + * @param decoder The function for decoding. + */ + setTranscoder(encoder: Bucket.EncoderFunction, decoder: Bucket.DecoderFunction): void; + + /** + * Update the document expiration time. + * @param key The target document key. + * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds). Values larger than 302460*60 seconds (30 days) are interpreted as absolute times (from the epoch). + * @param options The options object. + * @param callback The callback function. + */ + touch(key: any | Buffer, expiry: number, options: TouchOptions, callback: Bucket.OpCallback): void; + + /** + * Unlock a previously locked document on the server. See the Bucket#lock method for more details on locking. + * @param key The target document key. + * @param cas The CAS value returned when the key was locked. This operation will fail if the CAS value provided does not match that which was the result of the original lock operation. + * @param callback The callback function. + */ + unlock(key: any | Buffer, cas: Bucket.CAS, callback: Bucket.OpCallback): void; + + /** + * Unlock a previously locked document on the server. See the Bucket#lock method for more details on locking. + * @param key The target document key. + * @param cas The CAS value returned when the key was locked. This operation will fail if the CAS value provided does not match that which was the result of the original lock operation. + * @param options The options object. + * @param callback The callback function. + */ + unlock(key: any | Buffer, cas: Bucket.CAS, options: any, callback: Bucket.OpCallback): void; + + /** + * Stores a document to the bucket. + * @param key The target document key. + * @param value The document's contents. + * @param callback The callback function. + */ + upsert(key: any | Buffer, value: any, callback: Bucket.OpCallback): void; + + /** + * Stores a document to the bucket. + * @param key The target document key. + * @param value The document's contents. + * @param options The options object. + * @param callback The callback function. + */ + upsert(key: any | Buffer, value: any, options: UpsertOptions, callback: Bucket.OpCallback): void; +} + +declare namespace Bucket { + + /** + * his is used as a callback from executed queries. It is a shortcut method that automatically subscribes to the rows and error events of the Bucket.ViewQueryResponse. + */ + interface QueryCallback { + /** + * @param error The error for the operation. This can either be an Error object or a falsy value. + * @param rows The rows returned from the query. + * @param meta The metadata returned by the query. + */ + (error: CouchbaseError, rows: any[], meta: Bucket.ViewQueryResponse.Meta): void; } /** - * The virtual class thrown for all Couchnode errors. + * Single-Key callbacks. + * This callback is passed to all of the single key functions. + * It returns a result objcet containing a combination of a CAS and a value, depending on which operation was invoked. */ - interface CouchbaseError extends Error { + interface OpCallback { /** - * The error code for this error. + * @param error The error for the operation. This can either be an Error object or a value which evaluates to false (null, undefined, 0 or false). + * @param result The result of the operation that was executed. This usually contains at least a cas property, and on some operations will contain a value property as well. */ - code: errors; - } - - interface AppendOptions { - /** - * The CAS value to check. If the item on the server contains a different CAS value, the operation will fail. Note that if this option is undefined, no comparison will be performed. - */ - cas?: Bucket.CAS; - - /** - * Ensures this operation is persisted to this many nodes. - */ - persist_to?: number; - - /** - * Ensures this operation is replicated to this many nodes. - */ - replicate_to?: number; - } - - interface PrependOptions extends AppendOptions { } - - interface RemoveOptions extends AppendOptions { } - - interface ReplaceOptions extends AppendOptions { - /** - * Set the initial expiration time for the document. A value of 0 represents never expiring. - */ - expiry?: number; - } - - interface UpsertOptions extends ReplaceOptions { } - - interface TouchOptions { - /** - * Ensures this operation is persisted to this many nodes. - */ - persist_to?: number; - - /** - * Ensures this operation is replicated to this many nodes. - */ - replicate_to?: number; - } - - interface CounterOptions { - /** - * Sets the initial value for the document if it does not exist. Specifying a value of undefined will cause the operation to fail if the document does not exist, otherwise this value must be equal to or greater than 0. - */ - initial?: number; - - /** - * Set the initial expiration time for the document. A value of 0 represents never expiring. - */ - expiry?: number; - - /** - * Ensures this operation is persisted to this many nodes - */ - persist_to?: number; - - /** - * Ensures this operation is replicated to this many nodes - */ - replicate_to?: number; - } - - interface GetAndLockOptions { - lockTime?: number; - } - - interface GetReplicaOptions { - - /** - * The index for which replica you wish to retrieve this value from, or if undefined, use the value from the first server that replies. - */ - index?: number; - } - - interface InsertOptions { - - /** - * Set the initial expiration time for the document. A value of 0 represents never expiring. - */ - expiry?: number; - - /** - * Ensures this operation is persisted to this many nodes. - */ - persist_to?: number; - - /** - * Ensures this operation is replicated to this many nodes. - */ - replicate_to?: number; + (error: CouchbaseError | number, result: any): void; } /** - * A class for performing management operations against a bucket. This class should not be instantiated directly, but instead through the use of the Bucket#manager method instead. + * Multi-Get Callback. + * This callback is used to return results from a getMulti operation. */ - interface BucketManager { - + interface MultiGetCallback { /** - * Flushes the cluster, deleting all data stored within this bucket. Note that this method requires the Flush permission to be enabled on the bucket from the management console before it will work. - * @param callback The callback function. + * @param error The number of keys that failed to be retrieved. The precise errors are available by checking the error property of the individual documents. + * @param results This is a map of keys to results. The result for each key will optionally contain an error if one occured, or if no error occured will contain the CAS and value of the document. */ - flush(callback: Function): void; - - /** - * Retrieves a specific design document from this bucket. - * @param name - * @param callback The callback function. - */ - getDesignDocument(name: string, callback: Function): void; - - /** - * Retrieves a list of all design documents registered to a bucket. - * @param callback The callback function. - */ - getDesignDocuments(callback: Function): void; - - /** - * Registers a design document to this bucket, failing if it already exists. - * @param name - * @param data - * @param callback The callback function. - * @returns {} - */ - insertDesignDocument(name: string, data: any, callback: Function): void; - - /** - * Unregisters a design document from this bucket. - * @param name - * @param callback The callback function. - * @returns {} - */ - removeDesignDocument(name: string, callback: Function): void; - - /** - * Registers a design document to this bucket, overwriting any existing design document that was previously registered. - * @param name - * @param data - * @param callback The callback function. - * @returns {} - */ - upsertDesignDocument(name: string, data: any, callback: Function): void; + (error: number, results: any[]): void; } /** - * Class for dynamically construction of view queries. This class should never be constructed directly, instead you should use ViewQuery.from to construct this object. + * Transcoder Encoding Function. + * This function will receive a value when a storage operation is invoked that needs to encode user-provided data for storage into Couchbase. It expects to be returned a Buffer object to store along with an integer representing any flag metadata relating to how to decode the key later using the matching DecoderFunction. */ - class ViewQuery { - /** - * Instantiates a ViewQuery object for the specified design document and view name. - * @param ddoc The design document to use. - * @param name The view to use. - */ - static from(ddoc: string, name: string): ViewQuery; - - /** - * Specifies the design document and view name to use for this query. - * @param ddoc The design document to use. - * @param name The view to use. - */ - from(ddoc: string, name: string): ViewQuery; - - /** - * Allows you to specify custom view options that may not be available though the fluent interface defined by this class. - * @param opts - */ - custom(opts: any): ViewQuery; - - /** - * Flag to request a view request accross all nodes in the case of a development view. - * @param full_set - */ - full_set(full_set: boolean): ViewQuery; - - /** - * Specifies whether to preform grouping during view execution. - * @param group - */ - group(group: boolean): ViewQuery; - - /** - * Specifies the level at which to perform view grouping. - * @param group_level - */ - group_level(group_level: number): ViewQuery; - - /** - * Specifies a range of document id's to retrieve from the index. - * @param start - * @param end - */ - id_range(start: any, end: any): ViewQuery; - - /** - * Flag to request a view request include the full document value. - * @param include_docs - */ - include_docs(include_docs: boolean): ViewQuery; - - /** - * Specifies a specified key to retrieve from the index. - * @param key - */ - key(key: any): ViewQuery; - - /** - * Specifies a list of keys you wish to retrieve from the index. - * @param keys - */ - keys(key: any[]): ViewQuery; - - /** - * Specifies the maximum number of results to return. - * @param limit - */ - limit(limit: number): ViewQuery; - - /** - * Sets the error handling mode for this query. - * @param mode - */ - on_error(mode: ViewQuery.ErrorMode): ViewQuery; - - /** - * Specifies the desired ordering for the results. - * @param order - */ - order(order: ViewQuery.Order): ViewQuery; - - /** - * Specifies a range of keys to retrieve from the index. You may specify both a start and an end point and additionally specify whether or not the end value is inclusive or exclusive. - * @param start - * @param end - * @param inclusive_end - */ - range(start: any | any[], end: any | any[], inclusive_end?: boolean): ViewQuery; - - /** - * Specifies whether to execute the map-reduce reduce step. - * @param reduce - */ - reduce(reduce: boolean): ViewQuery; - - /** - * Specifies how many results to skip from the beginning of the result set. - * @param skip - */ - skip(skip: number): ViewQuery; - - /** - * Specifies how this query will affect view indexing, both before and after the query is executed. - * @param stale - */ - stale(stale: ViewQuery.Update): ViewQuery; - } - - namespace ViewQuery { - /** - * Enumeration for specifying on_error behaviour. - */ - enum ErrorMode { - /** - * Continues querying when an error occurs. - */ - CONTINUE, - - /** - * Stops and errors query when an error occurs. - */ - STOP - } - - /** - * Enumeration for specifying view result ordering. - */ - enum Order { - /** - * Orders with lower values first and higher values last. - */ - ASCENDING, - - /** - * Orders with higher values first and lower values last. - */ - DESCENDING - } - - /** - * Enumeration for specifying view update semantics. - */ - enum Update { - /** - * Causes the view to be fully indexed before results are retrieved. - */ - BEFORE, - - /** - * Allows the index to stay in whatever state it is already in prior retrieval of the query results. - */ - NONE, - - /** - * Forces the view to be indexed after the results of this query has been fetched. - */ - AFTER - } - } - - /** - * Class for dynamically construction of N1QL queries. This class should never be constructed directly, instead you should use the N1qlQuery.fromString static method to instantiate a N1qlStringQuery. - */ - class N1qlQuery { - /** - * Creates a query object directly from the passed query string. - * @param str - */ - static fromString(str: string): N1qlStringQuery; - - /** - * Returns the fully prepared string representation of this query. - */ - toString(): string; - } - - namespace N1qlQuery { - /** - * Enumeration for specifying N1QL consistency semantics. - */ - enum Consistency { - /** - * This is the default (for single-statement requests). - */ - NOT_BOUND, - - /** - * This implements strong consistency per request. - */ - REQUEST_PLUS, - - /** - * This implements strong consistency per statement. - */ - STATEMENT_PLUS - } - } - - /** - * Class for holding a explicitly defined N1QL query string. - */ - class N1qlStringQuery extends N1qlQuery { - /** - * Specifies whether this query is adhoc or should be prepared. - * @param adhoc - */ - adhoc(adhoc: boolean): N1qlStringQuery; - - /** - * Specify the consistency level for this query. - * @param val - */ - consistency(val: N1qlQuery.Consistency): N1qlStringQuery; - - /** - * Returns the fully prepared object representation of this query. - */ - toObject(): any; - - /** - * Returns the fully prepared string representation of this query. - */ - toString(): string; - } - - /** - * Class for dynamically construction of spatial queries. This class should never be constructed directly, instead you should use SpatialQuery.from to construct this object. - */ - class SpatialQuery { - /** - * Instantiates a SpatialQuery object for the specified design document and view name. - * @param ddoc The design document to use. - * @param name The view to use. - */ - static from(ddoc: string, name: string): SpatialQuery; - - /** - * Specifies the design document and view name to use for this query. - * @param ddoc - * @param name - */ - from(ddoc: string, name: string): SpatialQuery; - - /** - * Specifies a bounding box to query the index for. This value must be an array of exactly 4 numbers which represents the left, top, right and bottom edges of the bounding box (in that order). - * @param bbox - */ - bbox(bbox: number[]): SpatialQuery; - - /** - * Allows you to specify custom view options that may not be available though the fluent interface defined by this class. - * @param opts - */ - custom(opts: any): SpatialQuery; - - /** - * Specifies the maximum number of results to return. - * @param limit - */ - limit(limit: number): SpatialQuery; - - /** - * Specifies how many results to skip from the beginning of the result set. - * @param skip - */ - skip(skip: number): SpatialQuery; - - /** - * Specifies how this query will affect view indexing, both before and after the query is executed. - * @param stale - */ - stale(stale: SpatialQuery.Update): SpatialQuery; - } - - namespace SpatialQuery { - /** - * Enumeration for specifying view update semantics. - */ - enum Update { - /** - * Causes the view to be fully indexed before results are retrieved. - */ - BEFORE, - - /** - * Allows the index to stay in whatever state it is already in prior retrieval of the query results. - */ - NONE, - - /** - * Forces the view to be indexed after the results of this query has been fetched. - */ - AFTER - } - } - - /** - * The Bucket class represents a connection to a Couchbase bucket. Never instantiate this class directly. Instead use the Cluster#openBucket method instead. - */ - interface Bucket { - /** - * Returns the version of the Node.js library as a string. - */ - clientVersion: string; - - /** - * Gets or sets the config throttling in milliseconds. The config throttling is the time that Bucket will wait before forcing a configuration refresh. If no refresh occurs before this period while a configuration is marked invalid, an update will be triggered. - */ - configThrottle: number; - - /** - * Sets or gets the connection timeout in milliseconds. This is the timeout value used when connecting to the configuration port during the initial connection (in this case, use this as a key in the 'options' parameter in the constructor) and/or when Bucket attempts to reconnect in-situ (if the current connection has failed). - */ - connectionTimeout: number; - - /** - * Gets or sets the durability interval in milliseconds. The durability interval is the time that Bucket will wait between requesting new durability information during a durability poll. - */ - durabilityInterval: number; - - /** - * Gets or sets the durability timeout in milliseconds. The durability timeout is the time that Bucket will wait for a response from the server in regards to a durability request. If there are no responses received within this time frame, the request fails with an error. - */ - durabilityTimeout: number; - - /** - * Returns the libcouchbase version as a string. This information will usually be in the format of 2.4.0-fffffff representing the major, minor, patch and git-commit that the built libcouchbase is based upon. - */ - lcbVersion: string; - - /** - * Gets or sets the management timeout in milliseconds. The management timeout is the time that Bucket will wait for a response from the server for a management request. If the response is not received within this time frame, the request is failed out with an error. - */ - managementTimeout: number; - - /** - * Sets or gets the node connection timeout in msecs. This value is similar to Bucket#connectionTimeout, but defines the time to wait for a particular node to respond before trying the next one. - */ - nodeConnectionTimeout: number; - - /** - * Gets or sets the operation timeout in milliseconds. The operation timeout is the time that Bucket will wait for a response from the server for a CRUD operation. If the response is not received within this time frame, the operation is failed with an error. - */ - operationTimeout: number; - - /** - * Gets or sets the view timeout in milliseconds. The view timeout is the time that Bucket will wait for a response from the server for a view request. If the response is not received within this time frame, the request fails with an error. - */ - viewTimeout: number; - - /** - * Similar to Bucket#upsert, but instead of setting a new key, it appends data to the existing key. Note that this function only makes sense when the stored data is a string; 'appending' to a JSON document may result in parse errors when the document is later retrieved. - * @param key The target document key. - * @param fragment The document's contents to append. - * @param callback The callback function. - */ - append(key: any | Buffer, fragment: any, callback: Bucket.OpCallback): void; - - /** - * - * @param key The target document key. - * @param fragment The document's contents to append. - * @param options The options object. - * @param callback The callback function. - */ - append(key: any | Buffer, fragment: any, options: AppendOptions, callback: Bucket.OpCallback): void; - - /** - * Increments or decrements a key's numeric value. - * Note that JavaScript does not support 64-bit integers (while libcouchbase and the server do). You might receive an inaccurate value if the number is greater than 53-bits (JavaScript's maximum integer precision). - * @param key The target document key. - * @param delta The amount to add or subtract from the counter value. This value may be any non-zero integer. - * @param callback The callback function. - */ - counter(key: any | Buffer, delta: number, callback: Bucket.OpCallback): void; - - /** - * - * @param key The target document key. - * @param delta The amount to add or subtract from the counter value. This value may be any non-zero integer. - * @param options The options object. - * @param callback The callback function. - */ - counter(key: any | Buffer, delta: number, options: CounterOptions, callback: Bucket.OpCallback): void; - - /** - * Shuts down this connection. - */ - disconnect(): void; - - /** - * Enables N1QL support on the client. A cbq-server URI must be passed. This method will be deprecated in the future in favor of automatic configuration through the connected cluster. - * @param hosts An array of host/port combinations which are N1QL servers attached to this cluster. - */ - enableN1ql(hosts: string | string[]): void; - - /** - * Retrieves a document. - * @param key The target document key. - * @param callback The callback function. - */ - get(key: any | Buffer, callback: Bucket.OpCallback): void; - - /** - * @param key The target document key. - * @param options The options object. - * @param callback The callback function. - */ - get(key: any | Buffer, options: any, callback: Bucket.OpCallback): void; - - /** - * Lock the document on the server and retrieve it. When an document is locked, its CAS changes and subsequent operations on the document (without providing the current CAS) will fail until the lock is no longer held. - * This function behaves identically to Bucket#get in that it will return the value. It differs in that the document is also locked. This ensures that attempts by other client instances to access this document while the lock is held will fail. - * Once locked, a document can be unlocked either by explicitly calling Bucket#unlock or by performing a storage operation (e.g. Bucket#upsert, Bucket#replace, Bucket::append) with the current CAS value. Note that any other lock operations on this key will fail while a document is locked. - * @param key The target document key. - * @param callback The callback function. - */ - getAndLock(key: any, callback: Bucket.OpCallback): void; - - /** - * Lock the document on the server and retrieve it. When an document is locked, its CAS changes and subsequent operations on the document (without providing the current CAS) will fail until the lock is no longer held. - * This function behaves identically to Bucket#get in that it will return the value. It differs in that the document is also locked. This ensures that attempts by other client instances to access this document while the lock is held will fail. - * Once locked, a document can be unlocked either by explicitly calling Bucket#unlock or by performing a storage operation (e.g. Bucket#upsert, Bucket#replace, Bucket::append) with the current CAS value. Note that any other lock operations on this key will fail while a document is locked. - * @param key The target document key. - * @param options The options object. - * @param callback The callback function. - * @returns {} - */ - getAndLock(key: any, options: GetAndLockOptions, callback: Bucket.OpCallback): void; - - /** - * Retrieves a document and updates the expiry of the item at the same time. - * @param key The target document key. - * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds). - * @param options The options object. - * @param callback The callback function. - */ - getAndTouch(key: any | Buffer, expiry: number, options: any, callback: Bucket.OpCallback): void; - - /** - * Retrieves a document and updates the expiry of the item at the same time. - * @param key The target document key. - * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds). - * @param callback The callback function. - */ - getAndTouch(key: any | Buffer, expiry: number, callback: Bucket.OpCallback): void; - - /** - * Retrieves a list of keys - * @param keys The target document keys. - * @param callback The callback function. - */ - getMulti(key: any[] | Buffer[], callback: Bucket.MultiGetCallback): void; - - /** - * Get a document from a replica server in your cluster. - * @param key The target document key. - * @param callback The callback function. - */ - getReplica(key: any | Buffer, callback: Bucket.OpCallback): void; - - /** - * Get a document from a replica server in your cluster. - * @param key The target document key. - * @param options The options object. - * @param callback The callback function. - */ - getReplica(key: any | Buffer, options: GetReplicaOptions, callback: Bucket.OpCallback): void; - - /** - * Identical to Bucket#upsert but will fail if the document already exists. - * @param key The target document key. - * @param value The document's contents. - * @param callback The callback function. - */ - insert(key: any | Buffer, value: any, callback: Bucket.OpCallback): void; - - /** - * Identical to Bucket#upsert but will fail if the document already exists. - * @param key The target document key. - * @param value The document's contents. - * @param options The options object. - * @param callback The callback function. - */ - insert(key: any | Buffer, value: any, options: InsertOptions, callback: Bucket.OpCallback): void; - - /** - * Returns an instance of a BuckerManager for performing management operations against a bucket. - */ - manager(): BucketManager; - - /** - * Like Bucket#append, but prepends data to the existing value. - * @param key The target document key. - * @param fragment The document's contents to prepend. - * @param callback The callback function. - */ - prepend(key: any, fragment: any, callback: Bucket.OpCallback): void; - - /** - * Like Bucket#append, but prepends data to the existing value. - * @param key The target document key. - * @param fragment The document's contents to prepend. - * @param options The options object. - * @param callback The callback function. - */ - prepend(key: any, fragment: any, options: PrependOptions, callback: Bucket.OpCallback): void; - - /** - * Executes a previously prepared query object. This could be a ViewQuery or a N1qlQuery. - * Note: N1qlQuery queries are currently an uncommitted interface and may be subject to change in 2.0.0's final release. - * @param query The query to execute. - * @param callback The callback function. - */ - query(query: ViewQuery | N1qlQuery, callback: Bucket.QueryCallback): Bucket.ViewQueryResponse | Bucket.N1qlQueryResponse; - - /** - * Executes a previously prepared query object. This could be a ViewQuery or a N1qlQuery. - * Note: N1qlQuery queries are currently an uncommitted interface and may be subject to change in 2.0.0's final release. - * @param query The query to execute. - * @param params A list or map to do replacements on a N1QL query. - * @param callback The callback function. - */ - query(query: ViewQuery | N1qlQuery, params: Object | Array, callback: Bucket.QueryCallback): Bucket.ViewQueryResponse | Bucket.N1qlQueryResponse; - - /** - * Deletes a document on the server. - * @param key The target document key. - * @param callback The callback function. - */ - remove(key: any | Buffer, callback: Bucket.OpCallback): void; - - /** - * Deletes a document on the server. - * @param key The target document key. - * @param options The options object. - * @param callback The callback function. - */ - remove(key: any | Buffer, options: RemoveOptions, callback: Bucket.OpCallback): void; - - /** - * Identical to Bucket#upsert, but will only succeed if the document exists already (i.e. the inverse of Bucket#insert). - * @param key The target document key. - * @param value The document's contents. - * @param callback The callback function. - */ - replace(key: any | Buffer, value: any, callback: Bucket.OpCallback): void; - - /** - * Identical to Bucket#upsert, but will only succeed if the document exists already (i.e. the inverse of Bucket#insert). - * @param key The target document key. - * @param value The document's contents. - * @param options The options object. - * @param callback The callback function. - */ - replace(key: any | Buffer, value: any, options: ReplaceOptions, callback: Bucket.OpCallback): void; - - /** - * Configures a custom set of transcoder functions for encoding and decoding values that are being stored or retreived from the server. - * @param encoder The function for encoding. - * @param decoder The function for decoding. - */ - setTranscoder(encoder: Bucket.EncoderFunction, decoder: Bucket.DecoderFunction): void; - - /** - * Update the document expiration time. - * @param key The target document key. - * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds). Values larger than 302460*60 seconds (30 days) are interpreted as absolute times (from the epoch). - * @param options The options object. - * @param callback The callback function. - */ - touch(key: any | Buffer, expiry: number, options: TouchOptions, callback: Bucket.OpCallback): void; - - /** - * Unlock a previously locked document on the server. See the Bucket#lock method for more details on locking. - * @param key The target document key. - * @param cas The CAS value returned when the key was locked. This operation will fail if the CAS value provided does not match that which was the result of the original lock operation. - * @param callback The callback function. - */ - unlock(key: any | Buffer, cas: Bucket.CAS, callback: Bucket.OpCallback): void; - - /** - * Unlock a previously locked document on the server. See the Bucket#lock method for more details on locking. - * @param key The target document key. - * @param cas The CAS value returned when the key was locked. This operation will fail if the CAS value provided does not match that which was the result of the original lock operation. - * @param options The options object. - * @param callback The callback function. - */ - unlock(key: any | Buffer, cas: Bucket.CAS, options: any, callback: Bucket.OpCallback): void; - - /** - * Stores a document to the bucket. - * @param key The target document key. - * @param value The document's contents. - * @param callback The callback function. - */ - upsert(key: any | Buffer, value: any, callback: Bucket.OpCallback): void; - - /** - * Stores a document to the bucket. - * @param key The target document key. - * @param value The document's contents. - * @param options The options object. - * @param callback The callback function. - */ - upsert(key: any | Buffer, value: any, options: UpsertOptions, callback: Bucket.OpCallback): void; - } - - namespace Bucket { - - /** - * his is used as a callback from executed queries. It is a shortcut method that automatically subscribes to the rows and error events of the Bucket.ViewQueryResponse. - */ - interface QueryCallback { - /** - * @param error The error for the operation. This can either be an Error object or a falsy value. - * @param rows The rows returned from the query. - * @param meta The metadata returned by the query. - */ - (error: CouchbaseError, rows: any[], meta: Bucket.ViewQueryResponse.Meta): void; - } - - /** - * Single-Key callbacks. - * This callback is passed to all of the single key functions. - * It returns a result objcet containing a combination of a CAS and a value, depending on which operation was invoked. - */ - interface OpCallback { - /** - * @param error The error for the operation. This can either be an Error object or a value which evaluates to false (null, undefined, 0 or false). - * @param result The result of the operation that was executed. This usually contains at least a cas property, and on some operations will contain a value property as well. - */ - (error: CouchbaseError | number, result: any): void; - } - - /** - * Multi-Get Callback. - * This callback is used to return results from a getMulti operation. - */ - interface MultiGetCallback { - /** - * @param error The number of keys that failed to be retrieved. The precise errors are available by checking the error property of the individual documents. - * @param results This is a map of keys to results. The result for each key will optionally contain an error if one occured, or if no error occured will contain the CAS and value of the document. - */ - (error: number, results: any[]): void; - } - + interface EncoderFunction { /** * Transcoder Encoding Function. * This function will receive a value when a storage operation is invoked that needs to encode user-provided data for storage into Couchbase. It expects to be returned a Buffer object to store along with an integer representing any flag metadata relating to how to decode the key later using the matching DecoderFunction. + * @param value The value needing encoding. */ - interface EncoderFunction { + (value: any): Bucket.TranscoderDoc; + } + + /** + * Transcoder Decoding Function. + * This function will receive an object containing a Buffer value and an integer value representing any flags metadata whenever a retrieval operation is executed. It is expected that this function will return a value representing the original value stored and encoded with its matching EncoderFunction. + */ + interface DecoderFunction { + /** + * + * @param doc The data from Couchbase to decode. + */ + (doc: Bucket.TranscoderDoc): any + } + + /** + * The CAS value is a special object that indicates the current state of the item on the server. Each time an object is mutated on the server, the value is changed. CAS objects can be used in conjunction with mutation operations to ensure that the value on the server matches the local value retrieved by the client. This is useful when doing document updates on the server as you can ensure no changes were applied by other clients while you were in the process of mutating the document locally. + * In the Node.js SDK, the CAS is represented as an opaque value. As such,y ou cannot generate CAS objects, but should rather use the values returned from a Bucket.OpCallback. + */ + interface CAS { + + } + + /** + * An event emitter allowing you to bind to various query result set events. + */ + interface N1qlQueryResponse extends events.EventEmitter { + + } + + namespace N1qlQueryResponse { + /** + * The meta-information available from a view query response. + */ + interface Meta { /** - * Transcoder Encoding Function. - * This function will receive a value when a storage operation is invoked that needs to encode user-provided data for storage into Couchbase. It expects to be returned a Buffer object to store along with an integer representing any flag metadata relating to how to decode the key later using the matching DecoderFunction. - * @param value The value needing encoding. + * The identifier for this query request. */ - (value: any): Bucket.TranscoderDoc; + requestID: number; } + } + /** + * A class used in relation to transcoders. + */ + class TranscoderDoc { + value: Buffer; + flags: number; + } + + /** + * An event emitter allowing you to bind to various query result set events. + */ + interface ViewQueryResponse extends events.EventEmitter { + + } + + namespace ViewQueryResponse { /** - * Transcoder Decoding Function. - * This function will receive an object containing a Buffer value and an integer value representing any flags metadata whenever a retrieval operation is executed. It is expected that this function will return a value representing the original value stored and encoded with its matching EncoderFunction. + * The meta-information available from a view query response. */ - interface DecoderFunction { + interface Meta { /** - * - * @param doc The data from Couchbase to decode. + * The total number of rows available in the index of the view that was queried. */ - (doc: Bucket.TranscoderDoc): any - } - - /** - * The CAS value is a special object that indicates the current state of the item on the server. Each time an object is mutated on the server, the value is changed. CAS objects can be used in conjunction with mutation operations to ensure that the value on the server matches the local value retrieved by the client. This is useful when doing document updates on the server as you can ensure no changes were applied by other clients while you were in the process of mutating the document locally. - * In the Node.js SDK, the CAS is represented as an opaque value. As such,y ou cannot generate CAS objects, but should rather use the values returned from a Bucket.OpCallback. - */ - interface CAS { - - } - - /** - * An event emitter allowing you to bind to various query result set events. - */ - interface N1qlQueryResponse extends events.EventEmitter { - - } - - namespace N1qlQueryResponse { - /** - * The meta-information available from a view query response. - */ - interface Meta { - /** - * The identifier for this query request. - */ - requestID: number; - } - } - - /** - * A class used in relation to transcoders. - */ - class TranscoderDoc { - value: Buffer; - flags: number; - } - - /** - * An event emitter allowing you to bind to various query result set events. - */ - interface ViewQueryResponse extends events.EventEmitter { - - } - - namespace ViewQueryResponse { - /** - * The meta-information available from a view query response. - */ - interface Meta { - /** - * The total number of rows available in the index of the view that was queried. - */ - total_rows: number; - } + total_rows: number; } } } diff --git a/cradle/cradle.d.ts b/cradle/cradle.d.ts index 22a2fcf58e..9812979921 100644 --- a/cradle/cradle.d.ts +++ b/cradle/cradle.d.ts @@ -3,120 +3,119 @@ // Definitions by: Panu Horsmalahti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "cradle" { - interface Options { - host?: string; - hostname?: string; - cache?: boolean; - raw?: boolean; - forceSave?: boolean; - auth?: string | { - username: string; - password: string; - } - ca?: string; - secure?: boolean; - retries?: number; - retryTimeout?: number; - maxSockets?: number; - } - interface Callback { - (error: any, response: any): void; +interface Options { + host?: string; + hostname?: string; + cache?: boolean; + raw?: boolean; + forceSave?: boolean; + auth?: string | { + username: string; + password: string; } - - interface ErrorCallback { - (error: any): void; - } - - export class Connection { - constructor(uri?: string, port?: number, options?: Options); - database(name: string): Database; - databases(Callback: Callback): void; - config(callback: Callback): void; - info(callback: Callback): void; - stats(callback: Callback): void; - activeTasks(callback: Callback): void; - uuids(callback: Callback): void; - uuids(count: number, callback: Callback): void; - replicate(options: { - source: string | { - url: string; - }; - target: string | { - url: string; - }; - cancel?: boolean; - continuous?: boolean; - create_target?: boolean; - doc_ids?: string[]; - filter?: string; - proxy?: string; - query_params?: any; - }, callback: Callback): void; - } - - export interface ChangesOptions { - since: number; - } - - export class Database { - name: string; - get(id: string, callback: (error: any, document: any) => void): void; - get(id: string, callback: (error: any, document: T) => void): void; - get(id: string, rev: string, callback: (error: any, document: any) => void): void; - get(id: string, rev: string, callback: (error: any, document: T) => void): void; - get(ids: string[], callback: Callback): void; - save(document: any, callback: Callback): void; - save(id: string, document: any, callback: Callback): void; - save(id: string, revision: string, document: any, - callback: Callback): void; - save(document: T, callback: Callback): void; - save(id: string, document: T, callback: Callback): void; - save(id: string, revision: string, document: T, - callback: Callback): void; - save(documents: any[], callback: Callback): void; - merge(id: string, document: any, callback: Callback): void; - merge(id: string, document: T, callback: Callback): void; - remove(id: string, revision: string, callback: Callback): void; - update(name: string, id: string, queryObject: any, documentBody: any, - callback: Callback): void; - view(name: string, callback: Callback): void; - view(name: string, options: { - group?: boolean; - reduce?: boolean; - key?: string; - startkey?: any; - endkey?: any; - include_docs?: boolean; - limit?: number; - descending?: boolean; - }, callback: Callback): void; - temporaryView(view: any, callback: Callback): void; - create(callback: ErrorCallback): void; - exists(callback: (error: any, exists: boolean) => void): void; - destroy(callback: ErrorCallback): void; - changes(options: ChangesOptions): any; - changes(callback: (error: any, list: any[]) => void): void; - changes(options: ChangesOptions, callback: (error: any, - list: any[]) => void): void; - saveAttachment(idAndRevData: { - id: string; - rev: string; - }, attachmentData: any, callback: Callback): void; - getAttachment(id: string, attachmentName: string, - callback: Callback): void; - removeAttachment(id: string, attachmentName: string, - callback: Callback): void; - info(callback: Callback): void; - all(callback: Callback): void; - all(options: any, callback: Callback): void; - compact(callback: Callback): void; - compact(design: string, callback: Callback): void; - viewCleanup(callback: Callback): void; - replicate(target: string, callback: Callback): void; - replicate(target: string, options: any, callback: Callback): void; - } - - export function setup(options: Options): void; + ca?: string; + secure?: boolean; + retries?: number; + retryTimeout?: number; + maxSockets?: number; } + +interface Callback { + (error: any, response: any): void; +} + +interface ErrorCallback { + (error: any): void; +} + +declare export class Connection { + constructor(uri?: string, port?: number, options?: Options); + database(name: string): Database; + databases(Callback: Callback): void; + config(callback: Callback): void; + info(callback: Callback): void; + stats(callback: Callback): void; + activeTasks(callback: Callback): void; + uuids(callback: Callback): void; + uuids(count: number, callback: Callback): void; + replicate(options: { + source: string | { + url: string; + }; + target: string | { + url: string; + }; + cancel?: boolean; + continuous?: boolean; + create_target?: boolean; + doc_ids?: string[]; + filter?: string; + proxy?: string; + query_params?: any; + }, callback: Callback): void; +} + +export interface ChangesOptions { + since: number; +} + +declare export class Database { + name: string; + get(id: string, callback: (error: any, document: any) => void): void; + get(id: string, callback: (error: any, document: T) => void): void; + get(id: string, rev: string, callback: (error: any, document: any) => void): void; + get(id: string, rev: string, callback: (error: any, document: T) => void): void; + get(ids: string[], callback: Callback): void; + save(document: any, callback: Callback): void; + save(id: string, document: any, callback: Callback): void; + save(id: string, revision: string, document: any, + callback: Callback): void; + save(document: T, callback: Callback): void; + save(id: string, document: T, callback: Callback): void; + save(id: string, revision: string, document: T, + callback: Callback): void; + save(documents: any[], callback: Callback): void; + merge(id: string, document: any, callback: Callback): void; + merge(id: string, document: T, callback: Callback): void; + remove(id: string, revision: string, callback: Callback): void; + update(name: string, id: string, queryObject: any, documentBody: any, + callback: Callback): void; + view(name: string, callback: Callback): void; + view(name: string, options: { + group?: boolean; + reduce?: boolean; + key?: string; + startkey?: any; + endkey?: any; + include_docs?: boolean; + limit?: number; + descending?: boolean; + }, callback: Callback): void; + temporaryView(view: any, callback: Callback): void; + create(callback: ErrorCallback): void; + exists(callback: (error: any, exists: boolean) => void): void; + destroy(callback: ErrorCallback): void; + changes(options: ChangesOptions): any; + changes(callback: (error: any, list: any[]) => void): void; + changes(options: ChangesOptions, callback: (error: any, + list: any[]) => void): void; + saveAttachment(idAndRevData: { + id: string; + rev: string; + }, attachmentData: any, callback: Callback): void; + getAttachment(id: string, attachmentName: string, + callback: Callback): void; + removeAttachment(id: string, attachmentName: string, + callback: Callback): void; + info(callback: Callback): void; + all(callback: Callback): void; + all(options: any, callback: Callback): void; + compact(callback: Callback): void; + compact(design: string, callback: Callback): void; + viewCleanup(callback: Callback): void; + replicate(target: string, callback: Callback): void; + replicate(target: string, options: any, callback: Callback): void; +} + +declare export function setup(options: Options): void; diff --git a/create-error/create-error.d.ts b/create-error/create-error.d.ts index a92048ee1d..95d1fd4e7b 100644 --- a/create-error/create-error.d.ts +++ b/create-error/create-error.d.ts @@ -3,19 +3,18 @@ // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'create-error' { - // FIXME See Global type references https://github.com/Microsoft/TypeScript/issues/983 - type Err = Error; - namespace createError { +// FIXME See Global type references https://github.com/Microsoft/TypeScript/issues/983 +type Err = Error; + +declare namespace createError { interface Error extends Err { - new (message?: string, obj?: any): T; + new (message?: string, obj?: any): T; } - } - - function createError(): createError.Error; - function createError>(name: string, properties?: any): T; - function createError>(Target: createError.Error, name?: string, properties?: any): T; - - export = createError; } + +declare function createError(): createError.Error; +declare function createError>(name: string, properties?: any): T; +declare function createError>(Target: createError.Error, name?: string, properties?: any): T; + +export = createError; diff --git a/credential/credential.d.ts b/credential/credential.d.ts index 2934a090d4..4027305a01 100644 --- a/credential/credential.d.ts +++ b/credential/credential.d.ts @@ -3,16 +3,14 @@ // Definitions by: Phú // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'credential' { - type HashCallback = (err: Error, hash: string) => void; - type VerifyCallback = (err: Error, isValid: boolean) => void; - namespace credential { - function hash(password: string, callback: HashCallback): void; - function verify(hash: string, password: string, callback: VerifyCallback): void; - } - - export = credential; +type HashCallback = (err: Error, hash: string) => void; +type VerifyCallback = (err: Error, isValid: boolean) => void; +declare namespace credential { + function hash(password: string, callback: HashCallback): void; + function verify(hash: string, password: string, callback: VerifyCallback): void; } + +export = credential; diff --git a/cron/cron.d.ts b/cron/cron.d.ts index 2eb532cf56..491b790d2e 100644 --- a/cron/cron.d.ts +++ b/cron/cron.d.ts @@ -3,25 +3,22 @@ // Definitions by: Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "cron" { - interface CronJobStatic { - new(cronTime: string|Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any): CronJob; - new(options: { - cronTime: string|Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any + +interface CronJobStatic { + new (cronTime: string | Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any): CronJob; + new (options: { + cronTime: string | Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any }): CronJob; - } - interface CronJob { +} +interface CronJob { start(): void; stop(): void; - } - export var CronJob: CronJobStatic; - - interface CronTimeStatic { - new(time: string|Date): CronTime; - } - interface CronTime {} - export var CronTime: CronTimeStatic; - } +declare export var CronJob: CronJobStatic; +interface CronTimeStatic { + new (time: string | Date): CronTime; +} +interface CronTime { } +declare export var CronTime: CronTimeStatic; diff --git a/cross-storage/cross-storage.d.ts b/cross-storage/cross-storage.d.ts index 05e1b0ac1f..f8e620ba29 100644 --- a/cross-storage/cross-storage.d.ts +++ b/cross-storage/cross-storage.d.ts @@ -3,21 +3,21 @@ // Definitions by: Daniel Chao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "cross-storage" { - interface CrossStorageClientOptions { + +interface CrossStorageClientOptions { timeout?: number; promise?: any; frameId?: string; - } +} - type CrossStorageMethod = "get" | "set" | "del" | "getKeys" | "clear"; +type CrossStorageMethod = "get" | "set" | "del" | "getKeys" | "clear"; - interface SubDomain { +interface SubDomain { origin: RegExp; allow: CrossStorageMethod[]; - } +} - export class CrossStorageClient { +declare export class CrossStorageClient { /** * Constructs a new cross storage client given the url to a hub. By default, an iframe is created @@ -27,33 +27,33 @@ declare module "cross-storage" { * install its listeners. If the promise key is supplied the constructor for a Promise, that Promise * library will be used instead of the default window.Promise. */ - constructor (hubUrl: string, opts: CrossStorageClientOptions) + constructor(hubUrl: string, opts: CrossStorageClientOptions) /** * Returns a promise that is fulfilled when a connection has been established with the cross storage * hub. Its use is required to avoid sending any requests prior to initialization being complete. */ - onConnect (): Promise; + onConnect(): Promise; /** * Sets a key to the specified value, optionally accepting a ttl to passively expire the key after a * number of milliseconds. Returns a promise that is fulfilled on success, or rejected if any errors * setting the key occurred, or the request timed out. */ - set (key: string, value: any, ttl?: number): Promise; + set(key: string, value: any, ttl?: number): Promise; /** * Accepts one or more keys for which to retrieve their values. Returns a promise that is settled on * hub response or timeout. On success, it is fulfilled with the value of the key if only passed a * single argument. Otherwise it's resolved with an array of values. On failure, it is rejected with * the corresponding error message. */ - get (key: string): Promise; - get (...keys: string[]): Promise; + get(key: string): Promise; + get(...keys: string[]): Promise; /** * Accepts one or more keys for deletion. Returns a promise that is settled on hub response or timeout. */ - del (...keys: string[]): Promise; + del(...keys: string[]): Promise; /** * Returns a promise that, when resolved, passes an array of keys currently in storage. @@ -70,9 +70,9 @@ declare module "cross-storage" { * being invoked. */ close(): void; - } +} - export class CrossStorageHub { +declare export class CrossStorageHub { /** * Accepts an array of objects with two keys: origin and allow. The value of origin is expected to be * a RegExp, and allow, an array of strings. The cross storage hub is then initialized to accept requests @@ -80,7 +80,5 @@ declare module "cross-storage" { * include any of: get, set, del, getKeys and clear. A 'ready' message is sent to the parent window once * complete. */ - static init (subdomains: SubDomain[]): void; - } - + static init(subdomains: SubDomain[]): void; } diff --git a/cson/cson.d.ts b/cson/cson.d.ts index 0150273c0c..e87aaff320 100644 --- a/cson/cson.d.ts +++ b/cson/cson.d.ts @@ -3,30 +3,29 @@ // Definitions by: Sam Saint-Pettersen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "cson" { - // Create Strings - export function stringify(data: Object, opts?: Object, indent?: any): string; - export function createCSONString(data: Object, opts?: Object, next?: any): string; - export function createJSONString(data: Object, opts?: Object, next?: any): string; - export function createString(data: Object, opts?: Object, next?: any): string; - // Parse Strings - export function parse(data: string, opts?: Object, next?: any): Object; - export function parseCSONString(data: string, opts?: Object, next?: any): Object; - export function parseJSONString(data: string, opts?: Object, next?: any): Object; - export function parseCSString(data: string, opts?: Object, next?: any): Object; - export function parseJSString(data: string, opts?: Object, next?: any): Object; - export function parseString(data: string, opts?: Object, next?:any): Object; +// Create Strings +declare export function stringify(data: Object, opts?: Object, indent?: any): string; +declare export function createCSONString(data: Object, opts?: Object, next?: any): string; +declare export function createJSONString(data: Object, opts?: Object, next?: any): string; +declare export function createString(data: Object, opts?: Object, next?: any): string; - // Parse Files - export function load(filePath: string, opts?: Object, next?: any): Object; - export function parseCSONFile(filePath: string, opts?: Object, next?: any): Object; - export function parseJSONFile(filePath: string, opts?: Object, next?: any): Object; - export function parseCSFile(filePath: string, opts?: Object, next?: any): Object; - export function parseJSFile(filePath: string, opts?: Object, next?: any): Object; +// Parse Strings +declare export function parse(data: string, opts?: Object, next?: any): Object; +declare export function parseCSONString(data: string, opts?: Object, next?: any): Object; +declare export function parseJSONString(data: string, opts?: Object, next?: any): Object; +declare export function parseCSString(data: string, opts?: Object, next?: any): Object; +declare export function parseJSString(data: string, opts?: Object, next?: any): Object; +declare export function parseString(data: string, opts?: Object, next?: any): Object; - // Require Files - export function requireCSFile(filePath: string, opts?: Object, next?: any): Object; - export function requireJSFile(filePath: string, opts?: Object, next?: any): Object; - export function requireFile(filePath: string, opts?: Object, next?: any): Object; -} +// Parse Files +declare export function load(filePath: string, opts?: Object, next?: any): Object; +declare export function parseCSONFile(filePath: string, opts?: Object, next?: any): Object; +declare export function parseJSONFile(filePath: string, opts?: Object, next?: any): Object; +declare export function parseCSFile(filePath: string, opts?: Object, next?: any): Object; +declare export function parseJSFile(filePath: string, opts?: Object, next?: any): Object; + +// Require Files +declare export function requireCSFile(filePath: string, opts?: Object, next?: any): Object; +declare export function requireJSFile(filePath: string, opts?: Object, next?: any): Object; +declare export function requireFile(filePath: string, opts?: Object, next?: any): Object; diff --git a/css/css.d.ts b/css/css.d.ts index acea1acf0e..2dabf77799 100644 --- a/css/css.d.ts +++ b/css/css.d.ts @@ -6,253 +6,251 @@ /** * CSS parser / stringifier for Node.js */ -declare module "css" { - /** - * css.parse options - */ - interface ParserOptions { - /** Silently fail on parse errors */ - silent?: boolean; - /** The path to the file containing css. Makes errors and source maps more helpful, by letting them know where code comes from. */ - source?: string; - } - /** - * css.stringify options - */ - interface StringifyOptions { - /** The string used to indent the output. Defaults to two spaces. */ - indent?: string; - /** Omit comments and extraneous whitespace. */ - compress?: boolean; - /** Return a sourcemap along with the CSS output. - * Using the source option of css.parse is strongly recommended - * when creating a source map. Specify sourcemap: 'generator' - * to return the SourceMapGenerator object instead of serializing the source map. - */ - sourcemap?: string; - /** (enabled by default, specify false to disable) - * Reads any source maps referenced by the input files - * when generating the output source map. When enabled, - * file system access may be required for reading the referenced source maps. - */ - inputSourcemaps?: boolean; - } +/** + * css.parse options + */ +interface ParserOptions { + /** Silently fail on parse errors */ + silent?: boolean; + /** The path to the file containing css. Makes errors and source maps more helpful, by letting them know where code comes from. */ + source?: string; +} - /** - * Error thrown during parsing. - */ - interface ParserError { - /** The full error message with the source position. */ - message?: string; - /** The error message without position. */ - reason?: string; - /** The value of options.source if passed to css.parse. Otherwise undefined. */ - filename?: string; - line?: number; - column?: number; - /** The portion of code that couldn't be parsed. */ - source?: string; - } +/** + * css.stringify options + */ +interface StringifyOptions { + /** The string used to indent the output. Defaults to two spaces. */ + indent?: string; + /** Omit comments and extraneous whitespace. */ + compress?: boolean; + /** Return a sourcemap along with the CSS output. + * Using the source option of css.parse is strongly recommended + * when creating a source map. Specify sourcemap: 'generator' + * to return the SourceMapGenerator object instead of serializing the source map. + */ + sourcemap?: string; + /** (enabled by default, specify false to disable) + * Reads any source maps referenced by the input files + * when generating the output source map. When enabled, + * file system access may be required for reading the referenced source maps. + */ + inputSourcemaps?: boolean; +} - // --------------------------------------------------------------------------------- - // AST Tree - // --------------------------------------------------------------------------------- +/** + * Error thrown during parsing. + */ +interface ParserError { + /** The full error message with the source position. */ + message?: string; + /** The error message without position. */ + reason?: string; + /** The value of options.source if passed to css.parse. Otherwise undefined. */ + filename?: string; + line?: number; + column?: number; + /** The portion of code that couldn't be parsed. */ + source?: string; +} - /** - * Information about a position in the code. - * The line and column numbers are 1-based: The first line is 1 and the first column of a line is 1 (not 0). - */ - interface Position { - line?: number; - column?: number; - } +// --------------------------------------------------------------------------------- +// AST Tree +// --------------------------------------------------------------------------------- - /** - * Base AST Tree Node. - */ - interface Node { - /** The possible values are the ones listed in the Types section on https://github.com/reworkcss/css page. */ - type?: string; - /** A reference to the parent node, or null if the node has no parent. */ - parent?: Node; - /** Information about the position in the source string that corresponds to the node. */ - position?: { - start?: Position; - end?: Position; - /** The value of options.source if passed to css.parse. Otherwise undefined. */ - source?: string; - /** The full source string passed to css.parse. */ - content?: string; - }; - } +/** + * Information about a position in the code. + * The line and column numbers are 1-based: The first line is 1 and the first column of a line is 1 (not 0). + */ +interface Position { + line?: number; + column?: number; +} - interface Rule extends Node { - /** The list of selectors of the rule, split on commas. Each selector is trimmed from whitespace and comments. */ - selectors?: Array; - /** Array of nodes with the types declaration and comment. */ - declarations?: Array; - } +/** + * Base AST Tree Node. + */ +interface Node { + /** The possible values are the ones listed in the Types section on https://github.com/reworkcss/css page. */ + type?: string; + /** A reference to the parent node, or null if the node has no parent. */ + parent?: Node; + /** Information about the position in the source string that corresponds to the node. */ + position?: { + start?: Position; + end?: Position; + /** The value of options.source if passed to css.parse. Otherwise undefined. */ + source?: string; + /** The full source string passed to css.parse. */ + content?: string; + }; +} - interface Declaration extends Node { - /** The property name, trimmed from whitespace and comments. May not be empty. */ - property?: string; - /** The value of the property, trimmed from whitespace and comments. Empty values are allowed. */ - value?: string; - } +interface Rule extends Node { + /** The list of selectors of the rule, split on commas. Each selector is trimmed from whitespace and comments. */ + selectors?: Array; + /** Array of nodes with the types declaration and comment. */ + declarations?: Array; +} - /** - * A rule-level or declaration-level comment. Comments inside selectors, properties and values etc. are lost. - */ - interface Comment extends Node { - comment?: string; - } +interface Declaration extends Node { + /** The property name, trimmed from whitespace and comments. May not be empty. */ + property?: string; + /** The value of the property, trimmed from whitespace and comments. Empty values are allowed. */ + value?: string; +} - /** - * The @charset at-rule. - */ - interface Charset { - /** The part following @charset. */ - charset?: string; - } +/** + * A rule-level or declaration-level comment. Comments inside selectors, properties and values etc. are lost. + */ +interface Comment extends Node { + comment?: string; +} - /** - * The @custom-media at-rule - */ - interface CustomMedia { - /** The ---prefixed name. */ - name?: string; - /** The part following the name. */ - media?: string; - } +/** + * The @charset at-rule. + */ +interface Charset { + /** The part following @charset. */ + charset?: string; +} - /** - * The @document at-rule. - */ - interface Document { - /** The part following @document. */ - document?: string; - /** The vendor prefix in @document, or undefined if there is none. */ - vendor?: string; - /** Array of nodes with the types rule, comment and any of the at-rule types. */ - rules?: Array; - } +/** + * The @custom-media at-rule + */ +interface CustomMedia { + /** The ---prefixed name. */ + name?: string; + /** The part following the name. */ + media?: string; +} - /** - * The @font-face at-rule. - */ - interface FontFace { - /** Array of nodes with the types declaration and comment. */ - declarations?: Array; - } +/** + * The @document at-rule. + */ +interface Document { + /** The part following @document. */ + document?: string; + /** The vendor prefix in @document, or undefined if there is none. */ + vendor?: string; + /** Array of nodes with the types rule, comment and any of the at-rule types. */ + rules?: Array; +} - /** - * The @host at-rule. - */ - interface Host { - /** Array of nodes with the types rule, comment and any of the at-rule types. */ - rules?: Array; - } +/** + * The @font-face at-rule. + */ +interface FontFace { + /** Array of nodes with the types declaration and comment. */ + declarations?: Array; +} - /** - * The @import at-rule. - */ - interface Import { - /** The part following @import. */ - import?: string; - } +/** + * The @host at-rule. + */ +interface Host { + /** Array of nodes with the types rule, comment and any of the at-rule types. */ + rules?: Array; +} - /** - * The @keyframes at-rule. - */ - interface KeyFrames { - /** The name of the keyframes rule. */ - name?: string; - /** The vendor prefix in @keyframes, or undefined if there is none. */ - vendor?: string; - /** Array of nodes with the types keyframe and comment. */ - keyframes?: Array; - } +/** + * The @import at-rule. + */ +interface Import { + /** The part following @import. */ + import?: string; +} - interface KeyFrame { - /** The list of "selectors" of the keyframe rule, split on commas. Each “selector†is trimmed from whitespace. */ - values?: Array; - /** Array of nodes with the types declaration and comment. */ - declarations?: Array; - } +/** + * The @keyframes at-rule. + */ +interface KeyFrames { + /** The name of the keyframes rule. */ + name?: string; + /** The vendor prefix in @keyframes, or undefined if there is none. */ + vendor?: string; + /** Array of nodes with the types keyframe and comment. */ + keyframes?: Array; +} - /** - * The @media at-rule. - */ - interface Media { - /** The part following @media. */ - media?: string; - /** Array of nodes with the types rule, comment and any of the at-rule types. */ - rules?: Array; - } +interface KeyFrame { + /** The list of "selectors" of the keyframe rule, split on commas. Each “selector†is trimmed from whitespace. */ + values?: Array; + /** Array of nodes with the types declaration and comment. */ + declarations?: Array; +} - /** - * The @namespace at-rule. - */ - interface Namespace { - /** The part following @namespace. */ - namespace?: string; - } +/** + * The @media at-rule. + */ +interface Media { + /** The part following @media. */ + media?: string; + /** Array of nodes with the types rule, comment and any of the at-rule types. */ + rules?: Array; +} - /** - * The @page at-rule. - */ - interface Page { - /** The list of selectors of the rule, split on commas. Each selector is trimmed from whitespace and comments. */ - selectors?: Array; - /** Array of nodes with the types declaration and comment. */ - declarations?: Array; - } +/** + * The @namespace at-rule. + */ +interface Namespace { + /** The part following @namespace. */ + namespace?: string; +} - /** - * The @supports at-rule. - */ - interface Supports { - /** The part following @supports. */ - supports?: string; - /** Array of nodes with the types rule, comment and any of the at-rule types. */ - rules?: Array; - } +/** + * The @page at-rule. + */ +interface Page { + /** The list of selectors of the rule, split on commas. Each selector is trimmed from whitespace and comments. */ + selectors?: Array; + /** Array of nodes with the types declaration and comment. */ + declarations?: Array; +} - /** All at-rules. */ - type AtRule = Charset|CustomMedia|Document|FontFace|Host|Import|KeyFrames|Media|Namespace|Page|Supports; +/** + * The @supports at-rule. + */ +interface Supports { + /** The part following @supports. */ + supports?: string; + /** Array of nodes with the types rule, comment and any of the at-rule types. */ + rules?: Array; +} - /** - * The root node returned by css.parse. - */ - interface Stylesheet extends Node { - stylesheet?: { - /** Array of nodes with the types rule, comment and any of the at-rule types. */ - rules?: Array; - /** Array of Errors. Errors collected during parsing when option silent is true. */ - parsingErrors?: Array - }; - } +/** All at-rules. */ +type AtRule = Charset | CustomMedia | Document | FontFace | Host | Import | KeyFrames | Media | Namespace | Page | Supports; - // --------------------------------------------------------------------------------- +/** + * The root node returned by css.parse. + */ +interface Stylesheet extends Node { + stylesheet?: { + /** Array of nodes with the types rule, comment and any of the at-rule types. */ + rules?: Array; + /** Array of Errors. Errors collected during parsing when option silent is true. */ + parsingErrors?: Array + }; +} - /** - * Accepts a CSS string and returns an AST object. - * - * @param {string} code - CSS code. - * @param {ParserOptions} options - CSS parser options. - * @return {Stylesheet} AST object built using provides CSS code. - */ - function parse(code: string, options?: ParserOptions): Stylesheet; +// --------------------------------------------------------------------------------- - /** - * Accepts an AST object (as css.parse produces) and returns a CSS string. - * - * @param {Stylesheet} stylesheet - AST tree. - * @param {StringifyOptions} options - AST tree to string serializaiton options. - * @return {string} CSS code. - */ - function stringify(stylesheet: Stylesheet, options?: StringifyOptions): string; +/** + * Accepts a CSS string and returns an AST object. + * + * @param {string} code - CSS code. + * @param {ParserOptions} options - CSS parser options. + * @return {Stylesheet} AST object built using provides CSS code. + */ +declare function parse(code: string, options?: ParserOptions): Stylesheet; -} \ No newline at end of file +/** + * Accepts an AST object (as css.parse produces) and returns a CSS string. + * + * @param {Stylesheet} stylesheet - AST tree. + * @param {StringifyOptions} options - AST tree to string serializaiton options. + * @return {string} CSS code. + */ +declare function stringify(stylesheet: Stylesheet, options?: StringifyOptions): string; diff --git a/csv-stringify/csv-stringify.d.ts b/csv-stringify/csv-stringify.d.ts index a1cc16a15b..a097cb4a26 100644 --- a/csv-stringify/csv-stringify.d.ts +++ b/csv-stringify/csv-stringify.d.ts @@ -5,79 +5,78 @@ /// -declare module "csv-stringify" { - namespace stringify { - interface StringifyOpts { - /** - * List of fields, applied when transform returns an object, order matters, read the transformer documentation for additionnal information, columns are auto discovered when the user write object, see the "header" option on how to print columns names on the first line. - */ - columns?: string[]; - /** - * Set the field delimiter, one character only, defaults to a comma. - */ - delimiter?: string; - /** - * Add the value of "options.rowDelimiter" on the last line, default to true. - */ - eof?: boolean; - /** - * Defaults to the escape read option. - */ - escape?: boolean; - /** - * Display the column names on the first line if the columns option is provided or discovered. - */ - header?: boolean; - /** - * String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). - */ - lineBreaks?: string; - /** - * Defaults to the quote read option. - */ - quote?: string; - /** - * Boolean, default to false, quote all the non-empty fields even if not required. - */ - quoted?: boolean; - /** - * Boolean, no default, quote empty fields? If specified, overrides quotedString for empty strings. - */ - quotedEmpty?: boolean; - /** - * Boolean, default to false, quote all fields of type string even if not required. - */ - quotedString?: boolean; - /** - * String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). - */ - rowDelimiter?: string; - } +declare namespace stringify { + interface StringifyOpts { + /** + * List of fields, applied when transform returns an object, order matters, read the transformer documentation for additionnal information, columns are auto discovered when the user write object, see the "header" option on how to print columns names on the first line. + */ + columns?: string[]; + /** + * Set the field delimiter, one character only, defaults to a comma. + */ + delimiter?: string; + /** + * Add the value of "options.rowDelimiter" on the last line, default to true. + */ + eof?: boolean; + /** + * Defaults to the escape read option. + */ + escape?: boolean; + /** + * Display the column names on the first line if the columns option is provided or discovered. + */ + header?: boolean; + /** + * String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). + */ + lineBreaks?: string; + /** + * Defaults to the quote read option. + */ + quote?: string; + /** + * Boolean, default to false, quote all the non-empty fields even if not required. + */ + quoted?: boolean; + /** + * Boolean, no default, quote empty fields? If specified, overrides quotedString for empty strings. + */ + quotedEmpty?: boolean; + /** + * Boolean, default to false, quote all fields of type string even if not required. + */ + quotedString?: boolean; + /** + * String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). + */ + rowDelimiter?: string; - interface Stringifier extends NodeJS.ReadWriteStream { + } - // Stringifier stream takes array of strings - write(line: string[]): boolean; + interface Stringifier extends NodeJS.ReadWriteStream { - // repeat declarations from NodeJS.WritableStream to avoid compile error - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - } - } + // Stringifier stream takes array of strings + write(line: string[]): boolean; - /** - * Callback version: string in --> callback with string out - */ - function stringify(input: any[][], opts: stringify.StringifyOpts, callback: (error: Error, output: string) => void): void; - function stringify(input: any[][], callback: (error: Error, output: string) => void): void; - - /** - * Streaming stringifier - */ - function stringify(opts: stringify.StringifyOpts): stringify.Stringifier; - - export = stringify; + // repeat declarations from NodeJS.WritableStream to avoid compile error + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + } } + +/** + * Callback version: string in --> callback with string out + */ +declare function stringify(input: any[][], opts: stringify.StringifyOpts, callback: (error: Error, output: string) => void): void; +declare function stringify(input: any[][], callback: (error: Error, output: string) => void): void; + +/** + * Streaming stringifier + */ +declare function stringify(opts: stringify.StringifyOpts): stringify.Stringifier; + +export = stringify; diff --git a/cuid/cuid.d.ts b/cuid/cuid.d.ts index a5b9429800..d7979eefcd 100644 --- a/cuid/cuid.d.ts +++ b/cuid/cuid.d.ts @@ -3,8 +3,7 @@ // Definitions by: Dave Keen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'cuid' { - function cuid(): string; - - export = cuid -} + +declare function cuid(): string; + +export = cuid diff --git a/custom-error-generator/custom-error-generator.d.ts b/custom-error-generator/custom-error-generator.d.ts index b6c3872bda..50c3e14338 100644 --- a/custom-error-generator/custom-error-generator.d.ts +++ b/custom-error-generator/custom-error-generator.d.ts @@ -3,9 +3,8 @@ // Definitions by: Thierry Miceli // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "custom-error-generator" { - function createError(name: string, parameters?: Object, Constructor?: any): any; - namespace createError { - } - export = createError; + +declare function createError(name: string, parameters?: Object, Constructor?: any): any; +declare namespace createError { } +export = createError; diff --git a/data-driven/data-driven.d.ts b/data-driven/data-driven.d.ts index 82c307daa8..fc21425b54 100644 --- a/data-driven/data-driven.d.ts +++ b/data-driven/data-driven.d.ts @@ -3,7 +3,6 @@ // Definitions by: Adam Babcock // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "data-driven" { - function data_driven(data:T[], callback:()=>any):any; - export = data_driven -} + +declare function data_driven(data: T[], callback: () => any): any; +export = data_driven diff --git a/debounce/debounce.d.ts b/debounce/debounce.d.ts index 7aa24601a7..43b1630689 100644 --- a/debounce/debounce.d.ts +++ b/debounce/debounce.d.ts @@ -3,9 +3,8 @@ // Definitions by: Denis Sokolov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "debounce" { - // Overload on boolean constants would allow us to narrow further, - // but it is not implemented for TypeScript yet - function f(f: A, interval?: number, immediate?: boolean): A - export default f; -} + +// Overload on boolean constants would allow us to narrow further, +// but it is not implemented for TypeScript yet +declare function f(f: A, interval?: number, immediate?: boolean): A +export default f; diff --git a/decamelize/decamelize.d.ts b/decamelize/decamelize.d.ts index 2209d1e856..5ee1f76f35 100644 --- a/decamelize/decamelize.d.ts +++ b/decamelize/decamelize.d.ts @@ -3,8 +3,7 @@ // Definitions by: Sam Verschueren // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "decamelize" { - function decamelize(input: string, separator?: string): string; - namespace decamelize {} - export = decamelize; -} \ No newline at end of file + +declare function decamelize(input: string, separator?: string): string; +declare namespace decamelize { } +export = decamelize; diff --git a/deep-equal/deep-equal.d.ts b/deep-equal/deep-equal.d.ts index 0afb0f402b..eef762a4ea 100644 --- a/deep-equal/deep-equal.d.ts +++ b/deep-equal/deep-equal.d.ts @@ -3,16 +3,15 @@ // Definitions by: remojansen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "deep-equal" { - interface DeepEqualOptions { - strict: boolean; - } - let deepEqual: ( - actual: Object, - expected: Object, - opts?: DeepEqualOptions) => boolean; +interface DeepEqualOptions { + strict: boolean; +} - export = deepEqual; -} \ No newline at end of file +declare let deepEqual: ( + actual: Object, + expected: Object, + opts?: DeepEqualOptions) => boolean; + +export = deepEqual; diff --git a/deep-extend/deep-extend.d.ts b/deep-extend/deep-extend.d.ts index 164e337a95..a23daa519b 100644 --- a/deep-extend/deep-extend.d.ts +++ b/deep-extend/deep-extend.d.ts @@ -3,13 +3,12 @@ // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'deep-extend' { - /* - * Recursive object extending. - */ - function deepExtend(target: T, source: U): T & U; - function deepExtend(target: T, source1: U, source2: V): T & U & V; - function deepExtend(target: T, source1: U, source2: V, source3: W): T & U & V & W; - function deepExtend(target: any, ...sources: any[]): any; - export = deepExtend; -} + +/* + * Recursive object extending. + */ +declare function deepExtend(target: T, source: U): T & U; +declare function deepExtend(target: T, source1: U, source2: V): T & U & V; +declare function deepExtend(target: T, source1: U, source2: V, source3: W): T & U & V & W; +declare function deepExtend(target: any, ...sources: any[]): any; +export = deepExtend; diff --git a/del/del.d.ts b/del/del.d.ts index 6ed59efa39..714dc2f936 100644 --- a/del/del.d.ts +++ b/del/del.d.ts @@ -5,24 +5,23 @@ /// -declare module "del" { - import glob = require("glob"); - function Del(pattern: string): Promise; - function Del(pattern: string, options: Del.Options): Promise; +import glob = require("glob"); - function Del(patterns: string[]): Promise; - function Del(patterns: string[], options: Del.Options): Promise; +declare function Del(pattern: string): Promise; +declare function Del(pattern: string, options: Del.Options): Promise; - namespace Del { - function sync(pattern: string, options?: Options): string[]; - function sync(patterns: string[], options?: Options): string[]; +declare function Del(patterns: string[]): Promise; +declare function Del(patterns: string[], options: Del.Options): Promise; - interface Options extends glob.IOptions { - force?: boolean; - dryRun?: boolean; - } +declare namespace Del { + function sync(pattern: string, options?: Options): string[]; + function sync(patterns: string[], options?: Options): string[]; + + interface Options extends glob.IOptions { + force?: boolean; + dryRun?: boolean; } - - export = Del; } + +export = Del; diff --git a/denodeify/denodeify.d.ts b/denodeify/denodeify.d.ts index f2e27f4bd5..d5283bf777 100644 --- a/denodeify/denodeify.d.ts +++ b/denodeify/denodeify.d.ts @@ -3,32 +3,31 @@ // Definitions by: joaomoreno // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "denodeify" { - function _(fn: _.F0, transformer?: _.M): () => Promise; - function _(fn: _.F1, transformer?: _.M): (a:A) => Promise; - function _(fn: _.F2, transformer?: _.M): (a:A, b:B) => Promise; - function _(fn: _.F3, transformer?: _.M): (a:A, b:B, c:C) => Promise; - function _(fn: _.F4, transformer?: _.M): (a:A, b:B, c:C, d:D) => Promise; - function _(fn: _.F5, transformer?: _.M): (a:A, b:B, c:C, d:D, e:E) => Promise; - function _(fn: _.F6, transformer?: _.M): (a:A, b:B, c:C, d:D, e:E, f:F) => Promise; - function _(fn: _.F7, transformer?: _.M): (a:A, b:B, c:C, d:D, e:E, f:F, g:G) => Promise; - function _(fn: _.F8, transformer?: _.M): (a:A, b:B, c:C, d:D, e:E, f:F, g:G, h:H) => Promise; - function _(fn: _.F, transformer?: _.M): (...args: any[]) => Promise; - module _ { - type Callback = (err: Error, result: R) => any; - type F0 = (cb: Callback) => any; - type F1 = (a:A, cb: Callback) => any; - type F2 = (a:A, b:B, cb: Callback) => any; - type F3 = (a:A, b:B, c:C, cb: Callback) => any; - type F4 = (a:A, b:B, c:C, d:D, cb: Callback) => any; - type F5 = (a:A, b:B, c:C, d:D, e:E, cb: Callback) => any; - type F6 = (a:A, b:B, c:C, d:D, e:E, f:F, cb: Callback) => any; - type F7 = (a:A, b:B, c:C, d:D, e:E, f:F, g:G, cb: Callback) => any; - type F8 = (a:A, b:B, c:C, d:D, e:E, f:F, g:G, h:H, cb: Callback) => any; - type F = (...args: any[]) => any; - type M = (err: Error, ...args: any[]) => any[]; - } +declare function _(fn: _.F0, transformer?: _.M): () => Promise; +declare function _(fn: _.F1, transformer?: _.M): (a: A) => Promise; +declare function _(fn: _.F2, transformer?: _.M): (a: A, b: B) => Promise; +declare function _(fn: _.F3, transformer?: _.M): (a: A, b: B, c: C) => Promise; +declare function _(fn: _.F4, transformer?: _.M): (a: A, b: B, c: C, d: D) => Promise; +declare function _(fn: _.F5, transformer?: _.M): (a: A, b: B, c: C, d: D, e: E) => Promise; +declare function _(fn: _.F6, transformer?: _.M): (a: A, b: B, c: C, d: D, e: E, f: F) => Promise; +declare function _(fn: _.F7, transformer?: _.M): (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => Promise; +declare function _(fn: _.F8, transformer?: _.M): (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H) => Promise; +declare function _(fn: _.F, transformer?: _.M): (...args: any[]) => Promise; - export = _; +declare module _ { + type Callback = (err: Error, result: R) => any; + type F0 = (cb: Callback) => any; + type F1 = (a: A, cb: Callback) => any; + type F2 = (a: A, b: B, cb: Callback) => any; + type F3 = (a: A, b: B, c: C, cb: Callback) => any; + type F4 = (a: A, b: B, c: C, d: D, cb: Callback) => any; + type F5 = (a: A, b: B, c: C, d: D, e: E, cb: Callback) => any; + type F6 = (a: A, b: B, c: C, d: D, e: E, f: F, cb: Callback) => any; + type F7 = (a: A, b: B, c: C, d: D, e: E, f: F, g: G, cb: Callback) => any; + type F8 = (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, cb: Callback) => any; + type F = (...args: any[]) => any; + type M = (err: Error, ...args: any[]) => any[]; } + +export = _; diff --git a/depd/depd.d.ts b/depd/depd.d.ts index 674bb21f32..499cd99b88 100644 --- a/depd/depd.d.ts +++ b/depd/depd.d.ts @@ -4,14 +4,13 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'depd' { - function depd(namespace: string): Deprecate; - interface Deprecate { - (message: string): void; - function(fn: Function, message?: string): Function; - property(obj: Object, prop: string, message: string): void; - } +declare function depd(namespace: string): Deprecate; - export = depd; -} \ No newline at end of file +interface Deprecate { + (message: string): void; + function(fn: Function, message?: string): Function; + property(obj: Object, prop: string, message: string): void; +} + +export = depd; diff --git a/detect-indent/detect-indent.d.ts b/detect-indent/detect-indent.d.ts index eb666199c6..15e82d0015 100644 --- a/detect-indent/detect-indent.d.ts +++ b/detect-indent/detect-indent.d.ts @@ -3,11 +3,9 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'detect-indent' { - interface DetectIndent { - (dir: string, alt?: string): string; - } - var _: DetectIndent; - export = _; -} +interface DetectIndent { + (dir: string, alt?: string): string; +} +declare var _: DetectIndent; +export = _; diff --git a/diff-match-patch/diff-match-patch.d.ts b/diff-match-patch/diff-match-patch.d.ts index 028fe9d65c..a57d4b2edf 100644 --- a/diff-match-patch/diff-match-patch.d.ts +++ b/diff-match-patch/diff-match-patch.d.ts @@ -3,37 +3,36 @@ // Definitions by: Asana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "diff-match-patch" { - type Diff = [number, string]; - export class diff_match_patch { - static new (): diff_match_patch; +type Diff = [number, string]; - Diff_Timeout: number; - Diff_EditCost: number; - Match_Threshold: number; - Match_Distance: number; - Patch_DeleteThreshold: number; - Patch_Margin: number; - Match_MaxBits: number; +declare export class diff_match_patch { + static new(): diff_match_patch; - diff_main(text1: string, text2: string, opt_checklines?: boolean, opt_deadline?: number): Diff[]; - diff_commonPrefix(text1: string, text2: string): number; - diff_commonSuffix(text1: string, text2: string): number; - diff_cleanupSemantic(diffs: Diff[]): void; - diff_cleanupSemanticLossless(diffs: Diff[]): void; - diff_cleanupEfficiency(diffs: Diff[]): void; - diff_cleanupMerge(diffs: Diff[]): void; - diff_xIndex(diffs: Diff[], loc: number): number; - diff_prettyHtml(diffs: Diff[]): string; - diff_text1(diffs: Diff[]): string; - diff_text2(diffs: Diff[]): string; - diff_levenshtein(diffs: Diff[]): number; - diff_toDelta(diffs: Diff[]): string; - diff_fromDelta(text1: string, delta: string): Diff[]; - } + Diff_Timeout: number; + Diff_EditCost: number; + Match_Threshold: number; + Match_Distance: number; + Patch_DeleteThreshold: number; + Patch_Margin: number; + Match_MaxBits: number; - export var DIFF_DELETE: number; - export var DIFF_INSERT: number; - export var DIFF_EQUAL: number; + diff_main(text1: string, text2: string, opt_checklines?: boolean, opt_deadline?: number): Diff[]; + diff_commonPrefix(text1: string, text2: string): number; + diff_commonSuffix(text1: string, text2: string): number; + diff_cleanupSemantic(diffs: Diff[]): void; + diff_cleanupSemanticLossless(diffs: Diff[]): void; + diff_cleanupEfficiency(diffs: Diff[]): void; + diff_cleanupMerge(diffs: Diff[]): void; + diff_xIndex(diffs: Diff[], loc: number): number; + diff_prettyHtml(diffs: Diff[]): string; + diff_text1(diffs: Diff[]): string; + diff_text2(diffs: Diff[]): string; + diff_levenshtein(diffs: Diff[]): number; + diff_toDelta(diffs: Diff[]): string; + diff_fromDelta(text1: string, delta: string): Diff[]; } + +declare export var DIFF_DELETE: number; +declare export var DIFF_INSERT: number; +declare export var DIFF_EQUAL: number; diff --git a/documentdb/documentdb.d.ts b/documentdb/documentdb.d.ts index 1d901179a6..053fe988bd 100644 --- a/documentdb/documentdb.d.ts +++ b/documentdb/documentdb.d.ts @@ -3,413 +3,412 @@ // Definitions by: Noel Abrahams , Brett Gutstein // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/documentdb -declare module 'documentdb' { - /** The feed options and query methods.*/ - interface FeedOptions { - /** Max number of items to be returned in the enumeration operation. */ - maxItemCount?: number; +/** The feed options and query methods.*/ +interface FeedOptions { - /** Opaque token for continuing the enumeration. */ - continuation?: string; + /** Max number of items to be returned in the enumeration operation. */ + maxItemCount?: number; - /** Token for use with Session consistency. */ - sessionToken?: string; - } + /** Opaque token for continuing the enumeration. */ + continuation?: string; - /** Options that can be specified for a request issued to the DocumentDB servers. */ - interface RequestOptions { + /** Token for use with Session consistency. */ + sessionToken?: string; +} - /** Indicates what is the pre trigger to be invoked before the operation. */ - preTriggerInclude?: string; +/** Options that can be specified for a request issued to the DocumentDB servers. */ +interface RequestOptions { - /** Indicates what is the post trigger to be invoked after the operation. */ - postTriggerInclude?: string; + /** Indicates what is the pre trigger to be invoked before the operation. */ + preTriggerInclude?: string; - /** Conditions Associated with the request. */ - accessCondition?: { + /** Indicates what is the post trigger to be invoked after the operation. */ + postTriggerInclude?: string; - /** Conditional HTTP method header type.*/ - type: string; + /** Conditions Associated with the request. */ + accessCondition?: { - /** Conditional HTTP method header value.*/ - condition: string - }; + /** Conditional HTTP method header type.*/ + type: string; - /** Specifies indexing directives (index, do not index ..etc).*/ - indexingDirective?: string; + /** Conditional HTTP method header value.*/ + condition: string + }; - /** Consistency level required by the client. */ - consistencyLevel?: string; + /** Specifies indexing directives (index, do not index ..etc).*/ + indexingDirective?: string; - /** Token for use with Session consistency.*/ - sessionToken?: string; + /** Consistency level required by the client. */ + consistencyLevel?: string; - /** Expiry time (in seconds) for resource token associated with permission (applicable only for requests on permissions).*/ - resourceTokenExpirySeconds?: number; + /** Token for use with Session consistency.*/ + sessionToken?: string; - /** Disables the automatic id generation. If id is missing in the body and this option is true, an error will be returned. */ - disableAutomaticIdGeneration?: boolean; - } - - /** The Sql query parameter. */ - interface SqlParameter { - /** The name of the parameter. */ - name: string; - - /** The value of the parameter. */ - value: any; - } - - /** The Sql query specification. */ - interface SqlQuerySpec { - /** The body of the query. */ - query: string; - - /** The array of SqlParameters. */ - parameters: SqlParameter[]; - } - - /** Represents the error object returned from a failed query. */ - interface QueryError { + /** Expiry time (in seconds) for resource token associated with permission (applicable only for requests on permissions).*/ + resourceTokenExpirySeconds?: number; - /** The response code corresponding to the error. */ - code: number; + /** Disables the automatic id generation. If id is missing in the body and this option is true, an error will be returned. */ + disableAutomaticIdGeneration?: boolean; +} - /** A string representing the error information. */ - body: string; //{ code: string; message: string; }; - } +/** The Sql query parameter. */ +interface SqlParameter { + /** The name of the parameter. */ + name: string; + + /** The value of the parameter. */ + value: any; +} + +/** The Sql query specification. */ +interface SqlQuerySpec { + /** The body of the query. */ + query: string; + + /** The array of SqlParameters. */ + parameters: SqlParameter[]; +} + +/** Represents the error object returned from a failed query. */ +interface QueryError { + + /** The response code corresponding to the error. */ + code: number; + + /** A string representing the error information. */ + body: string; //{ code: string; message: string; }; +} + +/** +* The callback to execute after the request execution. +* @param error - Will contain error information if an error occurs, undefined otherwise. +* @param resource - An object that represents the requested resource (Db, collection, document ... etc) if no error happens. +* @param responseHeaders - An object that contain the response headers. +*/ +interface RequestCallback { + (error: QueryError, resource: TResult, responseHeaders: any): void; +} + +/** Represents the result returned from a query. */ +interface QueryIterator { + + toArray(callback: (error: QueryError, result: TResultRow[]) => void): void; +} + +/** Reprents an object with a unique identifier. */ +interface UniqueId { + + /** The user-defined unique identifier for a document or other DocumentDB object (database, collection, procedure...) */ + id: string; +} + +/** Represents the common meta data for all DocumentDB objects. */ +interface AbstractMeta extends UniqueId { + + /** The self link.*/ + _self: string; + + /** The time the object was created.*/ + _ts: string; + + _rid?: string; + _etag?: string; + + _attachments?: string; +} + +/** Represents a custom document for storing in DocumentDB */ +interface NewDocument extends UniqueId { + + /** A custom property for containing the actual JSON object representing the document. + * Define a custom property in order to disambiguate the JSON document from the metadata added by Azure. + * This property is optional and the name is application-specific. + */ + //doc: TContent; +} + +/** Represents a document retrieved from storage. + * This differs from a new document by the properties in AbstractMeta, which are added by the system. + */ +interface RetrievedDocument extends NewDocument, AbstractMeta { + +} + +/** Represents the meta data for a database. */ +interface DatabaseMeta extends AbstractMeta { +} + +/** Represents the meta data for a collection. */ +interface CollectionMeta extends AbstractMeta { +} + +/** Represents the meta data for a stored procedure. */ +interface ProcedureMeta extends AbstractMeta { + body: string; +} + +/** Represents the meta data for a trigger. */ +interface TriggerMeta extends AbstractMeta { + body: string; + triggerType: string; + triggerOperation: string; +} + +/** An object that is used for authenticating requests and must contains one of the options. */ +export interface AuthOptions { + + /** The authorization master key to use to create the client. */ + masterKey?: string; + + /** An object that contains resources tokens. Keys for the object are resource Ids and values are the resource tokens.*/ + resourceTokens?: any; + + /** An array of {@link Permission} objects. */ + permissionFeed?: any[]; +} + +/** Represents a DocumentDB stored procecedure. */ +export interface Procedure extends UniqueId { + + /** The function representing the stored procedure. */ + body(...params: any[]): void; +} + +/** Represents a DocumentDB trigger. */ +export interface Trigger extends UniqueId { + /** The type of the trigger. Should be either 'pre' or 'post'. */ + triggerType: string; + + /** The trigger operation. Should be one of 'all', 'create', 'update', 'delete', or 'replace'. */ + triggerOperation: string; + + /** The function representing the trigger. */ + body(...params: any[]): void; +} + +/** Represents DocumentDB collection. */ +export interface Collection extends UniqueId { + + indexingPolicy?: IndexingPolicy; +} + +/** The Indexing Path +*

Indexing paths hints to optimize indexing.
+* Indexing paths allow tradeoff between indexing storage and query performance +*

+*/ +interface IndexingPath { + + /** The indexing type(range or hash) {@link IndexType}.*/ + IndexType: string; + + /** Path to be indexed.*/ + Path: string; + + /** Precision for this particular Index type for numeric data. */ + NumericPrecision: number; + + /** Precision for this particular Index type for string data. */ + StringPrecision: number; +} + +/** The Indexing Policy represents the indexing policy configuration for a collection. */ +interface IndexingPolicy { + + /** Specifies whether automatic indexing is enabled for a collection. +

In automatic indexing, documents can be explicitly excluded from indexing using {@link RequestOptions}. + In manual indexing, documents can be explicitly included.

*/ + automatic: boolean; + + /** The indexing mode (consistent or lazy) {@link IndexingMode}. */ + indexingMode: string; + + /** An array of {@link IndexingPath} represents The paths to be incuded for indexing. */ + IncludedPath: IndexingPath[]; + + /** An array of strings representing the paths to be excluded from indexing. */ + ExcludedPaths: string[]; +} + +/** Provides a client-side logical representation of the Azure DocumentDB database account. This client is used to configure and execute requests against the service. + */ +declare export class DocumentClient { + /** + * Constructs a DocumentClient. + * @param urlConnection - The service endpoint to use to create the client. + * @param auth - An object that is used for authenticating requests and must contains one of the options. + * @param [connectionPolicy] - An instance of {@link ConnectionPolicy} class. This parameter is optional and the default connectionPolicy will be used if omitted. + * @param [consistencyLevel] - An optional parameter that represents the consistency level. It can take any value from {@link ConsistencyLevel}. + */ + constructor(urlConnection: string, auth: AuthOptions, connectionPolicy?: any, consistencyLevel?: string); + + /** Send a request for creating a database. + *

+ * A database manages users, permissions and a set of collections.
+ * Each Azure DocumentDB Database Account is able to support multiple independent named databases, with the database being the logical container for data.
+ * Each Database consists of one or more collections, each of which in turn contain one or more documents. Since databases are an an administrative resource, the Service Master Key will be required in order to access and successfully complete any action using the User APIs.
+ *

+ * @param body - A json object that represents The database to be created. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public createDatabase(body: UniqueId, options: RequestOptions, callback: RequestCallback): void; /** - * The callback to execute after the request execution. - * @param error - Will contain error information if an error occurs, undefined otherwise. - * @param resource - An object that represents the requested resource (Db, collection, document ... etc) if no error happens. - * @param responseHeaders - An object that contain the response headers. + * Creates a collection. + *

+ * A collection is a named logical container for documents.
+ * A database may contain zero or more named collections and each collection consists of zero or more JSON documents.
+ * Being schema-free, the documents in a collection do not need to share the same structure or fields.
+ * Since collections are application resources, they can be authorized using either the master key or resource keys.
+ *

+ * @param databaseLink - The self-link of the database. + * @param body - Represents the body of the collection. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public createCollection(databaseLink: string, body: Collection, options: RequestOptions, callback: RequestCallback): void; + + /** + * Create a StoredProcedure. + *

+ * DocumentDB allows stored procedures to be executed in the storage tier, directly against a document collection. The script
+ * gets executed under ACID transactions on the primary storage partition of the specified collection. For additional details,
+ * refer to the server-side JavaScript API documentation. + *

+ * @param collectionLink - The self-link of the collection. + * @param procedure - Represents the body of the stored procedure. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public createStoredProcedure(collectionLink: string, procedure: Procedure, options: RequestOptions, callback: RequestCallback): void; + + /** + * Create a trigger. + *

+ * DocumentDB supports pre and post triggers defined in JavaScript to be executed on creates, updates and deletes.
+ * For additional details, refer to the server-side JavaScript API documentation. + *

+ * @param collectionLink - The self-link of the collection. + * @param trigger - Represents the body of the trigger. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public createTrigger(collectionLink: string, trigger: Trigger, options: RequestOptions, callback: RequestCallback): void; + + /** + * Create a document. + *

+ * There is no set schema for JSON documents. They may contain any number of custom properties as well as an optional list of attachments.
+ * A Document is an application resource and can be authorized using the master key or resource keys + *

+ * @param collectionLink - The self-link of the collection. + * @param document - Represents the body of the document. Can contain any number of user defined properties. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public createDocument(collectionSelfLink: string, document: NewDocument, options: RequestOptions, callback: RequestCallback>): void; + + /** + * Execute the StoredProcedure represented by the object. + * @param procedureLink - The self-link of the stored procedure. + * @param [params] - Represents the parameters of the stored procedure. + * @param callback - The callback for the request. + */ + public executeStoredProcedure(procedureLink: string, params: any[], callback: RequestCallback): void; + + /** Lists all databases that satisfy a query. + * @param query - A SQL query string. + * @param [options] - The feed options. + * @returns - An instance of QueryIterator to handle reading feed. + */ + public queryDatabases(query: string | SqlQuerySpec): QueryIterator; + + /** + * Query the collections for the database. + * @param databaseLink - The self-link of the database. + * @param query - A SQL query string. + * @param [options] - Represents the feed options. + * @returns - An instance of queryIterator to handle reading feed. + */ + public queryCollections(databaseLink: string, query: string | SqlQuerySpec): QueryIterator; + + /** + * Query the storedProcedures for the collection. + * @param collectionLink - The self-link of the collection. + * @param query - A SQL query string. + * @param [options] - Represents the feed options. + * @returns - An instance of queryIterator to handle reading feed. + */ + public queryStoredProcedures(collectionLink: string, query: string | SqlQuerySpec): QueryIterator; + + /** + * Query the documents for the collection. + * @param collectionLink - The self-link of the collection. + * @param query - A SQL query string. + * @param [options] - Represents the feed options. + * @returns - An instance of queryIterator to handle reading feed. */ - interface RequestCallback { - (error: QueryError, resource: TResult, responseHeaders: any): void; - } + public queryDocuments(collectionLink: string, query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator>; - /** Represents the result returned from a query. */ - interface QueryIterator { + /** + * Query the triggers for the collection. + * @param {string} collectionLink - The self-link of the collection. + * @param {SqlQuerySpec | string} query - A SQL query. + * @param {FeedOptions} [options] - Represents the feed options. + * @returns {QueryIterator} - An instance of queryIterator to handle reading feed. + */ + public queryTriggers(collectionLink: string, query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator; - toArray(callback: (error: QueryError, result: TResultRow[]) => void): void; - } - - /** Reprents an object with a unique identifier. */ - interface UniqueId { - - /** The user-defined unique identifier for a document or other DocumentDB object (database, collection, procedure...) */ - id: string; - } - - /** Represents the common meta data for all DocumentDB objects. */ - interface AbstractMeta extends UniqueId { - - /** The self link.*/ - _self: string; - - /** The time the object was created.*/ - _ts: string; - - _rid?: string; - _etag?: string; - - _attachments?: string; - } - - /** Represents a custom document for storing in DocumentDB */ - interface NewDocument extends UniqueId { - - /** A custom property for containing the actual JSON object representing the document. - * Define a custom property in order to disambiguate the JSON document from the metadata added by Azure. - * This property is optional and the name is application-specific. - */ - //doc: TContent; - } - - /** Represents a document retrieved from storage. - * This differs from a new document by the properties in AbstractMeta, which are added by the system. - */ - interface RetrievedDocument extends NewDocument, AbstractMeta { - - } - - /** Represents the meta data for a database. */ - interface DatabaseMeta extends AbstractMeta { - } - - /** Represents the meta data for a collection. */ - interface CollectionMeta extends AbstractMeta { - } - - /** Represents the meta data for a stored procedure. */ - interface ProcedureMeta extends AbstractMeta { - body: string; - } - - /** Represents the meta data for a trigger. */ - interface TriggerMeta extends AbstractMeta { - body: string; - triggerType: string; - triggerOperation: string; - } - - /** An object that is used for authenticating requests and must contains one of the options. */ - export interface AuthOptions { - - /** The authorization master key to use to create the client. */ - masterKey?: string; - - /** An object that contains resources tokens. Keys for the object are resource Ids and values are the resource tokens.*/ - resourceTokens?: any; - - /** An array of {@link Permission} objects. */ - permissionFeed?: any[]; - } - - /** Represents a DocumentDB stored procecedure. */ - export interface Procedure extends UniqueId { - - /** The function representing the stored procedure. */ - body(...params: any[]): void; - } - - /** Represents a DocumentDB trigger. */ - export interface Trigger extends UniqueId { - /** The type of the trigger. Should be either 'pre' or 'post'. */ - triggerType: string; - - /** The trigger operation. Should be one of 'all', 'create', 'update', 'delete', or 'replace'. */ - triggerOperation: string; - - /** The function representing the trigger. */ - body(...params: any[]): void; - } - - /** Represents DocumentDB collection. */ - export interface Collection extends UniqueId { - - indexingPolicy?: IndexingPolicy; - } - - /** The Indexing Path - *

Indexing paths hints to optimize indexing.
- * Indexing paths allow tradeoff between indexing storage and query performance - *

+ /** + * Delete the document object. + * @param documentLink - The self-link of the document. + * @param [options] - The request options. + * @param callback - The callback for the request. */ - interface IndexingPath { + public deleteDocument(documentLink: string, options: RequestOptions, callback: RequestCallback): void; - /** The indexing type(range or hash) {@link IndexType}.*/ - IndexType: string; + /** + * Delete the database object. + * @param databaseLink - The self-link of the database. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public deleteDatabase(databaseLink: string, options: RequestOptions, callback: RequestCallback): void; - /** Path to be indexed.*/ - Path: string; + /** + * Delete the collection object. + * @param collectionLink - The self-link of the collection. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public deleteCollection(collectionLink: string, options: RequestOptions, callback: RequestCallback): void; - /** Precision for this particular Index type for numeric data. */ - NumericPrecision: number; + /** + * Delete the StoredProcedure object. + * @param procedureLink - The self-link of the stored procedure. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public deleteStoredProcedure(procedureLink: string, options: RequestOptions, callback: RequestCallback): void; - /** Precision for this particular Index type for string data. */ - StringPrecision: number; - } + /** + * Replace the document object. + * @param {string} documentLink - The self-link of the document. + * @param {object} document - Represent the new document body. + * @param {RequestOptions} [options] - The request options. + * @param {RequestCallback} callback - The callback for the request. + */ + public replaceDocument(documentLink: string, document: NewDocument, options: RequestOptions, callback: RequestCallback>): void; - /** The Indexing Policy represents the indexing policy configuration for a collection. */ - interface IndexingPolicy { - - /** Specifies whether automatic indexing is enabled for a collection. -

In automatic indexing, documents can be explicitly excluded from indexing using {@link RequestOptions}. - In manual indexing, documents can be explicitly included.

*/ - automatic: boolean; - - /** The indexing mode (consistent or lazy) {@link IndexingMode}. */ - indexingMode: string; - - /** An array of {@link IndexingPath} represents The paths to be incuded for indexing. */ - IncludedPath: IndexingPath[]; - - /** An array of strings representing the paths to be excluded from indexing. */ - ExcludedPaths: string[]; - } - - /** Provides a client-side logical representation of the Azure DocumentDB database account. This client is used to configure and execute requests against the service. - */ - export class DocumentClient { - /** - * Constructs a DocumentClient. - * @param urlConnection - The service endpoint to use to create the client. - * @param auth - An object that is used for authenticating requests and must contains one of the options. - * @param [connectionPolicy] - An instance of {@link ConnectionPolicy} class. This parameter is optional and the default connectionPolicy will be used if omitted. - * @param [consistencyLevel] - An optional parameter that represents the consistency level. It can take any value from {@link ConsistencyLevel}. - */ - constructor(urlConnection: string, auth: AuthOptions, connectionPolicy?: any, consistencyLevel?: string); - - /** Send a request for creating a database. - *

- * A database manages users, permissions and a set of collections.
- * Each Azure DocumentDB Database Account is able to support multiple independent named databases, with the database being the logical container for data.
- * Each Database consists of one or more collections, each of which in turn contain one or more documents. Since databases are an an administrative resource, the Service Master Key will be required in order to access and successfully complete any action using the User APIs.
- *

- * @param body - A json object that represents The database to be created. - * @param [options] - The request options. - * @param callback - The callback for the request. - */ - public createDatabase(body: UniqueId, options: RequestOptions, callback: RequestCallback): void; - - /** - * Creates a collection. - *

- * A collection is a named logical container for documents.
- * A database may contain zero or more named collections and each collection consists of zero or more JSON documents.
- * Being schema-free, the documents in a collection do not need to share the same structure or fields.
- * Since collections are application resources, they can be authorized using either the master key or resource keys.
- *

- * @param databaseLink - The self-link of the database. - * @param body - Represents the body of the collection. - * @param [options] - The request options. - * @param callback - The callback for the request. - */ - public createCollection(databaseLink: string, body: Collection, options: RequestOptions, callback: RequestCallback): void; - - /** - * Create a StoredProcedure. - *

- * DocumentDB allows stored procedures to be executed in the storage tier, directly against a document collection. The script
- * gets executed under ACID transactions on the primary storage partition of the specified collection. For additional details,
- * refer to the server-side JavaScript API documentation. - *

- * @param collectionLink - The self-link of the collection. - * @param procedure - Represents the body of the stored procedure. - * @param [options] - The request options. - * @param callback - The callback for the request. - */ - public createStoredProcedure(collectionLink: string, procedure: Procedure, options: RequestOptions, callback: RequestCallback): void; - - /** - * Create a trigger. - *

- * DocumentDB supports pre and post triggers defined in JavaScript to be executed on creates, updates and deletes.
- * For additional details, refer to the server-side JavaScript API documentation. - *

- * @param collectionLink - The self-link of the collection. - * @param trigger - Represents the body of the trigger. - * @param [options] - The request options. - * @param callback - The callback for the request. - */ - public createTrigger(collectionLink: string, trigger: Trigger, options: RequestOptions, callback: RequestCallback): void; - - /** - * Create a document. - *

- * There is no set schema for JSON documents. They may contain any number of custom properties as well as an optional list of attachments.
- * A Document is an application resource and can be authorized using the master key or resource keys - *

- * @param collectionLink - The self-link of the collection. - * @param document - Represents the body of the document. Can contain any number of user defined properties. - * @param [options] - The request options. - * @param callback - The callback for the request. - */ - public createDocument(collectionSelfLink: string, document: NewDocument, options: RequestOptions, callback: RequestCallback>): void; - - /** - * Execute the StoredProcedure represented by the object. - * @param procedureLink - The self-link of the stored procedure. - * @param [params] - Represents the parameters of the stored procedure. - * @param callback - The callback for the request. - */ - public executeStoredProcedure(procedureLink: string, params: any[], callback: RequestCallback): void; - - /** Lists all databases that satisfy a query. - * @param query - A SQL query string. - * @param [options] - The feed options. - * @returns - An instance of QueryIterator to handle reading feed. - */ - public queryDatabases(query: string | SqlQuerySpec): QueryIterator; - - /** - * Query the collections for the database. - * @param databaseLink - The self-link of the database. - * @param query - A SQL query string. - * @param [options] - Represents the feed options. - * @returns - An instance of queryIterator to handle reading feed. - */ - public queryCollections(databaseLink: string, query: string | SqlQuerySpec): QueryIterator; - - /** - * Query the storedProcedures for the collection. - * @param collectionLink - The self-link of the collection. - * @param query - A SQL query string. - * @param [options] - Represents the feed options. - * @returns - An instance of queryIterator to handle reading feed. - */ - public queryStoredProcedures(collectionLink: string, query: string | SqlQuerySpec): QueryIterator; - - /** - * Query the documents for the collection. - * @param collectionLink - The self-link of the collection. - * @param query - A SQL query string. - * @param [options] - Represents the feed options. - * @returns - An instance of queryIterator to handle reading feed. - */ - public queryDocuments(collectionLink: string, query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator>; - - /** - * Query the triggers for the collection. - * @param {string} collectionLink - The self-link of the collection. - * @param {SqlQuerySpec | string} query - A SQL query. - * @param {FeedOptions} [options] - Represents the feed options. - * @returns {QueryIterator} - An instance of queryIterator to handle reading feed. - */ - public queryTriggers(collectionLink: string, query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator; - - /** - * Delete the document object. - * @param documentLink - The self-link of the document. - * @param [options] - The request options. - * @param callback - The callback for the request. - */ - public deleteDocument(documentLink: string, options: RequestOptions, callback: RequestCallback): void; - - /** - * Delete the database object. - * @param databaseLink - The self-link of the database. - * @param [options] - The request options. - * @param callback - The callback for the request. - */ - public deleteDatabase(databaseLink: string, options: RequestOptions, callback: RequestCallback): void; - - /** - * Delete the collection object. - * @param collectionLink - The self-link of the collection. - * @param [options] - The request options. - * @param callback - The callback for the request. - */ - public deleteCollection(collectionLink: string, options: RequestOptions, callback: RequestCallback): void; - - /** - * Delete the StoredProcedure object. - * @param procedureLink - The self-link of the stored procedure. - * @param [options] - The request options. - * @param callback - The callback for the request. - */ - public deleteStoredProcedure(procedureLink: string, options: RequestOptions, callback: RequestCallback): void; - - /** - * Replace the document object. - * @param {string} documentLink - The self-link of the document. - * @param {object} document - Represent the new document body. - * @param {RequestOptions} [options] - The request options. - * @param {RequestCallback} callback - The callback for the request. - */ - public replaceDocument(documentLink: string, document: NewDocument, options: RequestOptions, callback: RequestCallback>): void; - - /** - * Replace the StoredProcedure object. - * @param procedureLink - The self-link of the stored procedure. - * @param procedure - Represent the new procedure body. - * @param [options] - The request options. - * @param callback - The callback for the request. - */ - public replaceStoredProcedure(procedureLink: string, procedure: Procedure, options: RequestOptions, callback: RequestCallback): void; - } -} \ No newline at end of file + /** + * Replace the StoredProcedure object. + * @param procedureLink - The self-link of the stored procedure. + * @param procedure - Represent the new procedure body. + * @param [options] - The request options. + * @param callback - The callback for the request. + */ + public replaceStoredProcedure(procedureLink: string, procedure: Procedure, options: RequestOptions, callback: RequestCallback): void; +} diff --git a/dot-case/dot-case.d.ts b/dot-case/dot-case.d.ts index 93921f56e2..8f11ee3b3c 100644 --- a/dot-case/dot-case.d.ts +++ b/dot-case/dot-case.d.ts @@ -3,7 +3,6 @@ // Definitions by: Sam Saint-Pettersen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "dot-case" { - function dotCase(string: string, locale?: string): string; - export = dotCase; -} + +declare function dotCase(string: string, locale?: string): string; +export = dotCase; diff --git a/dot-prop/dot-prop.d.ts b/dot-prop/dot-prop.d.ts index 9ad2eb1a9d..0d765bedbc 100644 --- a/dot-prop/dot-prop.d.ts +++ b/dot-prop/dot-prop.d.ts @@ -3,7 +3,6 @@ // Definitions by: Sam Verschueren // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "dot-prop" { - export function get(object: any, path: string): any; - export function set(object: any, path: string, value: any): void; -} + +declare export function get(object: any, path: string): any; +declare export function set(object: any, path: string, value: any): void; diff --git a/draft-js/draft-js.d.ts b/draft-js/draft-js.d.ts index ac5eb21f33..7ab650acde 100644 --- a/draft-js/draft-js.d.ts +++ b/draft-js/draft-js.d.ts @@ -2,276 +2,274 @@ // Project: https://github.com/facebook/draft-js // Definitions by: Pavel Evsegneev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "draft-js" { - namespace Draft { - interface IEditor { - new(): Editor - } - interface EditorState { - getCurrentContent(): ContentState, - getSelection(): SelectionState, - getCurrentInlineStyle(): any, - getBlockTree(): any, - - createEmpty(decorator?: any): EditorState, - createWithContent(contentState: ContentState, decorator?: any): EditorState, - create(config: any): EditorState, - push(editorState: EditorState, contentState: ContentState, actionType: string): EditorState, - undo(editorState: EditorState): EditorState, - redo(editorState: EditorState): EditorState, - acceptSelection(editorState: EditorState, selectionState: SelectionState): EditorState, - forceSelection(editorState: EditorState, selectionState: SelectionState): EditorState, - - moveFocusToEnd(editorState: EditorState): EditorState - } - - interface CompositeDecorator { - getDecorations(): Array, - getComponentForKey(): any, - getPropsForKey(): any - } - - interface Entity { - create(type: string, mutability: string, data?: Object): EntityInstance, - add(instance: EntityInstance): string, - get(key: string): EntityInstance, - mergeData(key: string, toMerge: any): EntityInstance, - replaceData(key: string, newData: any): EntityInstance - } - - interface EntityInstance { - getData(): any, - getKey(): string, - getMutability(): string - } - - interface BlockMapBuilder { - createFromArray(blocks: Array): BlockMap - } - - interface CharacterMetadata { - create(config?: any): CharacterMetadata, - - applyStyle(record: CharacterMetadata, - style: string): CharacterMetadata, - - removeStyle(record: CharacterMetadata, - style: string): CharacterMetadata, - - applyEntity(record: CharacterMetadata, - entityKey?: string): CharacterMetadata, - - getStyle(): any, - hasStyle(style: string): boolean, - - getEntity(): string - } - - interface IContentBlock { - new(draftContentBlock: any): ContentBlock; - } - interface ContentBlock { - key: string, - type: string, - text: string, - characterList: any, - depth: number, - - getKey(): string, - getType(): string, - getText(): string, - getCharacterList(): any, - getLength(): number, - getDepth(): number, - getInlineStyleAt(offset: number): any, - getEntityAt(offset: number): string, - findStyleRanges(filterFn: Function, callback: Function): void, - findEntityRanges(filterFn: Function, callback: Function): void - - } - - interface ContentState { - createFromText(text: string): ContentState, - createFromBlockArray(blocks: Array): ContentState, - - getBlockMap(): BlockMap, - getSelectionBefore(): SelectionState, - getSelectionAfter(): SelectionState, - - getBlockForKey(key: string): ContentBlock, - getKeyBefore(key: string): string, - getKeyAfter(key: string): string, - - getBlockBefore(key: string): ContentBlock, - getBlockAfter(key: string): ContentBlock, - - getBlocksAsArray(): Array, - - getPlainText(): string, - hasText(): boolean, - - set(key: string, value: any): ContentState, - toJS(): any - } - - interface ISelectionState { - new(draftSelectionState: any): SelectionState; - createEmpty(blockKey: string): SelectionState; - } - - interface SelectionState { - getStartKey(): string, - getStartOffset(): number, - getEndKey(): string, - getEndOffset(): number, - getAnchorKey(): string, - getAnchorOffset(): number, - getFocusKey(): string, - getFocusOffset(): number, - - getIsBackward(): boolean, - getHasFocus(): boolean, - isCollapsed(): boolean, - - hasEdgeWithin(blockKey: string, start: number, end: number): boolean, - serialize(): string, - - get(key: string): any, - set(key: string, value: any): SelectionState - } - - interface BlockMap { - get(key: string): ContentBlock, - set(key: string, value: any): BlockMap, - delete(key: string): BlockMap, - find(cb: any): ContentBlock - } - - interface Modifier { - replaceText(contentState: ContentState, - rangeToReplace: SelectionState, - text: string, - inlineStyle?: any, - entityKey?: string): ContentState, - - insertText(contentState: ContentState, - targetRange: SelectionState, - text: string, - inlineStyle?: any, - entityKey?: string): ContentState, - - moveText(contentState: ContentState, - removalRange: SelectionState, - targetRange: SelectionState): ContentState, - - replaceWithFragment(contentState: ContentState, - targetRange: SelectionState, - fragment: BlockMap): ContentState, - - removeRange(contentState: ContentState, - rangeToRemove: SelectionState, - removalDirection: string): ContentState, - - splitBlock(contentState: ContentState, - selectionState: SelectionState): ContentState, - - applyInlineStyle(contentState: ContentState, - selectionState: SelectionState, - inlineStyle: string): ContentState, - - removeInlineStyle(contentState: ContentState, - selectionState: SelectionState, - inlineStyle: string): ContentState, - - setBlockType(contentState: ContentState, - selectionState: SelectionState, - blockType: string): ContentState, - - applyEntity(contentState: ContentState, - selectionState: SelectionState, - entityKey: string): ContentState - } - - interface RichUtils { - currentBlockContainsLink(editorState: EditorState): boolean, - getCurrentBlockType(editor: EditorState): string, - handleKeyCommand(editorState: EditorState, command: string): any, - insertSoftNewline(editorState: EditorState): EditorState, - onBackspace(editorState: EditorState): EditorState, - onDelete(editorState: EditorState): EditorState, - onTab(event: Event, editorState: EditorState, maxDepth: number): EditorState, - toggleBlockType(editorState: EditorState, blockType: string): EditorState, - toggleCode(editorState: EditorState): EditorState, - toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState, - tryToRemoveBlockStyle(editorState: EditorState): EditorState - } - - interface EditorProps { - editorState: EditorState, - onChange(editorState: EditorState): void, - - placeholder?: string, - textAlignment?: any, - blockRendererFn?: (ContentBlock: ContentBlock) => any, - blockStyleFn?: (ContentBlock: ContentBlock) => string, - customStyleMap?: any, - - readOnly?: boolean, - spellCheck?: boolean, - stripPastedStyles?: boolean, - - handleReturn?: (e: any) => boolean, - handleKeyCommand?: (command: string) => boolean, - handleBeforeInput?: (chars: string) => boolean, - handlePastedFiles?: (files: Array) => boolean, - handleDroppedFiles?: (selection: SelectionState, files: Array) => boolean, - handleDrop?: (selection: SelectionState, dataTransfer: any, isInternal: any) => boolean, - - onEscape?: (e: any) => void, - onTab?: (e: any) => void, - onUpArrow?: (e: any) => void, - onDownArrow?: (e: any) => void, - - suppressContentEditableWarning?: any, - - onBlur?: (e: any) => void, - onFocus?: (e: any) => void - } - - interface Editor { - props: EditorProps - state: any, - refs: any, - context: any, - setState(): any, - render(): any, - forceUpdate(): any - } - - var Editor: IEditor; - var EditorState: EditorState; - - var CompositeDecorator: CompositeDecorator; - var Entity: Entity; - var EntityInstance: EntityInstance; - - var BlockMapBuilder: BlockMapBuilder; - var CharacterMetadata: CharacterMetadata; - var ContentBlock: IContentBlock; - var ContentState: ContentState; - var SelectionState: ISelectionState; - - var Modifier: Modifier; - var RichUtils: RichUtils; - - function convertFromRaw(rawState: any): Array; - - function convertToRaw(contentState: ContentState): any; - - function genKey(): string +declare namespace Draft { + interface IEditor { + new (): Editor } - export = Draft; + interface EditorState { + getCurrentContent(): ContentState, + getSelection(): SelectionState, + getCurrentInlineStyle(): any, + getBlockTree(): any, + createEmpty(decorator?: any): EditorState, + createWithContent(contentState: ContentState, decorator?: any): EditorState, + create(config: any): EditorState, + push(editorState: EditorState, contentState: ContentState, actionType: string): EditorState, + undo(editorState: EditorState): EditorState, + redo(editorState: EditorState): EditorState, + acceptSelection(editorState: EditorState, selectionState: SelectionState): EditorState, + forceSelection(editorState: EditorState, selectionState: SelectionState): EditorState, + + moveFocusToEnd(editorState: EditorState): EditorState + } + + interface CompositeDecorator { + getDecorations(): Array, + getComponentForKey(): any, + getPropsForKey(): any + } + + interface Entity { + create(type: string, mutability: string, data?: Object): EntityInstance, + add(instance: EntityInstance): string, + get(key: string): EntityInstance, + mergeData(key: string, toMerge: any): EntityInstance, + replaceData(key: string, newData: any): EntityInstance + } + + interface EntityInstance { + getData(): any, + getKey(): string, + getMutability(): string + } + + interface BlockMapBuilder { + createFromArray(blocks: Array): BlockMap + } + + interface CharacterMetadata { + create(config?: any): CharacterMetadata, + + applyStyle(record: CharacterMetadata, + style: string): CharacterMetadata, + + removeStyle(record: CharacterMetadata, + style: string): CharacterMetadata, + + applyEntity(record: CharacterMetadata, + entityKey?: string): CharacterMetadata, + + getStyle(): any, + hasStyle(style: string): boolean, + + getEntity(): string + } + + interface IContentBlock { + new (draftContentBlock: any): ContentBlock; + } + interface ContentBlock { + key: string, + type: string, + text: string, + characterList: any, + depth: number, + + getKey(): string, + getType(): string, + getText(): string, + getCharacterList(): any, + getLength(): number, + getDepth(): number, + getInlineStyleAt(offset: number): any, + getEntityAt(offset: number): string, + findStyleRanges(filterFn: Function, callback: Function): void, + findEntityRanges(filterFn: Function, callback: Function): void + + } + + interface ContentState { + createFromText(text: string): ContentState, + createFromBlockArray(blocks: Array): ContentState, + + getBlockMap(): BlockMap, + getSelectionBefore(): SelectionState, + getSelectionAfter(): SelectionState, + + getBlockForKey(key: string): ContentBlock, + getKeyBefore(key: string): string, + getKeyAfter(key: string): string, + + getBlockBefore(key: string): ContentBlock, + getBlockAfter(key: string): ContentBlock, + + getBlocksAsArray(): Array, + + getPlainText(): string, + hasText(): boolean, + + set(key: string, value: any): ContentState, + toJS(): any + } + + interface ISelectionState { + new (draftSelectionState: any): SelectionState; + createEmpty(blockKey: string): SelectionState; + } + + interface SelectionState { + getStartKey(): string, + getStartOffset(): number, + getEndKey(): string, + getEndOffset(): number, + getAnchorKey(): string, + getAnchorOffset(): number, + getFocusKey(): string, + getFocusOffset(): number, + + getIsBackward(): boolean, + getHasFocus(): boolean, + isCollapsed(): boolean, + + hasEdgeWithin(blockKey: string, start: number, end: number): boolean, + serialize(): string, + + get(key: string): any, + set(key: string, value: any): SelectionState + } + + interface BlockMap { + get(key: string): ContentBlock, + set(key: string, value: any): BlockMap, + delete(key: string): BlockMap, + find(cb: any): ContentBlock + } + + interface Modifier { + replaceText(contentState: ContentState, + rangeToReplace: SelectionState, + text: string, + inlineStyle?: any, + entityKey?: string): ContentState, + + insertText(contentState: ContentState, + targetRange: SelectionState, + text: string, + inlineStyle?: any, + entityKey?: string): ContentState, + + moveText(contentState: ContentState, + removalRange: SelectionState, + targetRange: SelectionState): ContentState, + + replaceWithFragment(contentState: ContentState, + targetRange: SelectionState, + fragment: BlockMap): ContentState, + + removeRange(contentState: ContentState, + rangeToRemove: SelectionState, + removalDirection: string): ContentState, + + splitBlock(contentState: ContentState, + selectionState: SelectionState): ContentState, + + applyInlineStyle(contentState: ContentState, + selectionState: SelectionState, + inlineStyle: string): ContentState, + + removeInlineStyle(contentState: ContentState, + selectionState: SelectionState, + inlineStyle: string): ContentState, + + setBlockType(contentState: ContentState, + selectionState: SelectionState, + blockType: string): ContentState, + + applyEntity(contentState: ContentState, + selectionState: SelectionState, + entityKey: string): ContentState + } + + interface RichUtils { + currentBlockContainsLink(editorState: EditorState): boolean, + getCurrentBlockType(editor: EditorState): string, + handleKeyCommand(editorState: EditorState, command: string): any, + insertSoftNewline(editorState: EditorState): EditorState, + onBackspace(editorState: EditorState): EditorState, + onDelete(editorState: EditorState): EditorState, + onTab(event: Event, editorState: EditorState, maxDepth: number): EditorState, + toggleBlockType(editorState: EditorState, blockType: string): EditorState, + toggleCode(editorState: EditorState): EditorState, + toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState, + tryToRemoveBlockStyle(editorState: EditorState): EditorState + } + + interface EditorProps { + editorState: EditorState, + onChange(editorState: EditorState): void, + + placeholder?: string, + textAlignment?: any, + blockRendererFn?: (ContentBlock: ContentBlock) => any, + blockStyleFn?: (ContentBlock: ContentBlock) => string, + customStyleMap?: any, + + readOnly?: boolean, + spellCheck?: boolean, + stripPastedStyles?: boolean, + + handleReturn?: (e: any) => boolean, + handleKeyCommand?: (command: string) => boolean, + handleBeforeInput?: (chars: string) => boolean, + handlePastedFiles?: (files: Array) => boolean, + handleDroppedFiles?: (selection: SelectionState, files: Array) => boolean, + handleDrop?: (selection: SelectionState, dataTransfer: any, isInternal: any) => boolean, + + onEscape?: (e: any) => void, + onTab?: (e: any) => void, + onUpArrow?: (e: any) => void, + onDownArrow?: (e: any) => void, + + suppressContentEditableWarning?: any, + + onBlur?: (e: any) => void, + onFocus?: (e: any) => void + } + + interface Editor { + props: EditorProps + state: any, + refs: any, + context: any, + setState(): any, + render(): any, + forceUpdate(): any + } + + var Editor: IEditor; + var EditorState: EditorState; + + var CompositeDecorator: CompositeDecorator; + var Entity: Entity; + var EntityInstance: EntityInstance; + + var BlockMapBuilder: BlockMapBuilder; + var CharacterMetadata: CharacterMetadata; + var ContentBlock: IContentBlock; + var ContentState: ContentState; + var SelectionState: ISelectionState; + + var Modifier: Modifier; + var RichUtils: RichUtils; + + function convertFromRaw(rawState: any): Array; + + function convertToRaw(contentState: ContentState): any; + + function genKey(): string } + +export = Draft; diff --git a/dts-bundle/dts-bundle.d.ts b/dts-bundle/dts-bundle.d.ts index 501e0da200..fc3cde458b 100644 --- a/dts-bundle/dts-bundle.d.ts +++ b/dts-bundle/dts-bundle.d.ts @@ -3,21 +3,20 @@ // Definitions by: Asana // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "dts-bundle" { - interface Options { - name: string; - main: string; - baseDir?: string; - exclude?: RegExp; - externals?: boolean; - indent?: string; - newLine?: string; - out?: string; - prefix?: string; - removeSource?: boolean; - separator?: string; - verbose?: boolean; - } - export function bundle(opts: Options): void; -} \ No newline at end of file +interface Options { + name: string; + main: string; + baseDir?: string; + exclude?: RegExp; + externals?: boolean; + indent?: string; + newLine?: string; + out?: string; + prefix?: string; + removeSource?: boolean; + separator?: string; + verbose?: boolean; +} + +declare export function bundle(opts: Options): void; diff --git a/dustjs-linkedin/dustjs-linkedin.d.ts b/dustjs-linkedin/dustjs-linkedin.d.ts index 70bd288a39..b81ebcdd5f 100644 --- a/dustjs-linkedin/dustjs-linkedin.d.ts +++ b/dustjs-linkedin/dustjs-linkedin.d.ts @@ -13,156 +13,155 @@ // Fell free to include other methods. If possible let me know about. // -declare module "dustjs-linkedin" { + + +/** +* A template compiled into a js function. +*/ +export interface Template { + (chk: Chunk, ctx: Context): Chunk; +} + +export interface Chunk { + /** + * Writes data to this chunk's buffer. + */ + write(data: string): Chunk; /** - * A template compiled into a js function. + * Writes data to this chunk's buffer and marks it as flushable. This method must be called on any chunks created via chunk.map. Do not call this method on a handler's main chunk -- dust.render and dust.stream take care of this for you. */ - export interface Template { - (chk: Chunk, ctx: Context): Chunk; - } - - export interface Chunk { - /** - * Writes data to this chunk's buffer. - */ - write(data: string): Chunk; - - /** - * Writes data to this chunk's buffer and marks it as flushable. This method must be called on any chunks created via chunk.map. Do not call this method on a handler's main chunk -- dust.render and dust.stream take care of this for you. - */ - end(data: string): Chunk; - - /** - * Creates a new chunk and passes it to callback. Use map to wrap asynchronous functions and to partition the template for streaming. - */ - map(callback: (chunk: Chunk) => any): Chunk; - - /** - * Convenience method to apply filters to a stream. - */ - tap(callback: (value: any) => any): Chunk; - - /** - * Removes the head tap function from the list. - */ - untap(): Chunk; - - /** - * Renders a template block, such as a default block or an else block. - */ - render(body: any, context: Context): Chunk; - - /** - * Sets an error on this chunk and immediately flushes the output. - */ - setError(err: any): Chunk; - } - - export interface Context { - /** - * Retrieves the value at key from the context stack. - */ - get (key: string): any; - - /** - * Pushes an arbitrary value onto the context stack and returns a new context instance. Specify index and/or length to enable enumeration helpers. - */ - push(head: any, idx?: number, len?: number): Context; - - /** - * Returns a new context instance consisting only of the value at head, plus any previously defined global object. - */ - rebase(head: any): Context; - - /** - * Returns the head of the context stack. - */ - current(): any; - } - - export interface Stream { - flush(): void; - emit(evt: string, data: any): void; - - /* - * Registers an event listener. Streams accept a single listener for a given event. - * @param evt the event. Possible values are data, end, error (maybe more, look in the source). - */ - on(evt: string, callback: (data?: any) => any); - - pipe(stream: Stream): Stream; - } + end(data: string): Chunk; /** - * register a template into the cache. - * @param name the unique template name. - * @param tmpl the template function. + * Creates a new chunk and passes it to callback. Use map to wrap asynchronous functions and to partition the template for streaming. */ - export function register(name: string, tmpl: Template): void; + map(callback: (chunk: Chunk) => any): Chunk; /** - * compile a template body into a string of JavaScript source code - * @param source the template string - * @param name the name used to register the compiled template into the internal cache. See render(). - * @strip strip whitespaces from the output. Defaults to false. + * Convenience method to apply filters to a stream. */ - export function compile(source: string, name: string, strip?: boolean): string; + tap(callback: (value: any) => any): Chunk; /** - * Compiles source directly into a JavaScript function that takes a context and an optional callback (see dust.renderSource). Registers the template under [name] if this argument is supplied. - * @param source the template string - * @param name the template name (optional). + * Removes the head tap function from the list. */ - export function compileFn(source: string, name?: string): Template; + untap(): Chunk; /** - * Evaluates a compiled source string. + * Renders a template block, such as a default block or an else block. */ - export function loadSource(compiled: string): Template; + render(body: any, context: Context): Chunk; /** - * Renders the named template and calls callback on completion.context may be a plain object or an instance of dust.Context. - * @param name the template name. - * @param context a plain object or an instance of dust.Context. + * Sets an error on this chunk and immediately flushes the output. */ - export function render(name: string, context: any, callback: (err: any, out: string) => any); - export function render(name: string, context: Context, callback: (err: any, out: string) => any); + setError(err: any): Chunk; +} + +export interface Context { + /** + * Retrieves the value at key from the context stack. + */ + get(key: string): any; /** - * Compiles and renders source, invoking callback on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required. - * @param source the template string. - * @param context a plain object or an instance of dust.Context. - * @param callback (optional). If supplied the callback will be called passing the result string. If omitted, renderSource() will return a dust.Stream object. + * Pushes an arbitrary value onto the context stack and returns a new context instance. Specify index and/or length to enable enumeration helpers. */ - export function renderSource(source: string, context: any): Stream; - export function renderSource(source: string, context: Context): Stream; - export function renderSource(source: string, context: any, callback: (err: any, out: string) => any): void; - export function renderSource(source: string, context: Context, callback: (err: any, out: string) => any): void; + push(head: any, idx?: number, len?: number): Context; /** - * Streams the named template. context may be a plain object or an instance of dust.Context. Returns an instance of dust.Stream. - * @param name the template name. - * @param context a plain object or an instance of dust.Context. + * Returns a new context instance consisting only of the value at head, plus any previously defined global object. */ - export function stream(name: string, context: any): Stream; - export function stream(name: string, context: Context): Stream; + rebase(head: any): Context; /** - * Manufactures a dust.Context instance with its global object set to object. - * @param global a plain object or an instance of dust.Context. + * Returns the head of the context stack. */ - export function makeBase(global: any): Context; - export function makeBase(global: Context): Context; + current(): any; +} - export function escapeHtml(html: string): string; - export function escapeJs(js: string): string; +export interface Stream { + flush(): void; + emit(evt: string, data: any): void; - var helpers: { - [key: string]: (chk: Chunk, ctx: Context, bodies?: any, params?: any) => any; - }; + /* + * Registers an event listener. Streams accept a single listener for a given event. + * @param evt the event. Possible values are data, end, error (maybe more, look in the source). + */ + on(evt: string, callback: (data?: any) => any); - var filters: { - [key: string]: (value: string) => string; - }; -} \ No newline at end of file + pipe(stream: Stream): Stream; +} + +/** +* register a template into the cache. +* @param name the unique template name. +* @param tmpl the template function. +*/ +declare export function register(name: string, tmpl: Template): void; + +/** +* compile a template body into a string of JavaScript source code +* @param source the template string +* @param name the name used to register the compiled template into the internal cache. See render(). +* @strip strip whitespaces from the output. Defaults to false. +*/ +declare export function compile(source: string, name: string, strip?: boolean): string; + +/** +* Compiles source directly into a JavaScript function that takes a context and an optional callback (see dust.renderSource). Registers the template under [name] if this argument is supplied. +* @param source the template string +* @param name the template name (optional). +*/ +declare export function compileFn(source: string, name?: string): Template; + +/** +* Evaluates a compiled source string. +*/ +declare export function loadSource(compiled: string): Template; + +/** +* Renders the named template and calls callback on completion.context may be a plain object or an instance of dust.Context. +* @param name the template name. +* @param context a plain object or an instance of dust.Context. +*/ +declare export function render(name: string, context: any, callback: (err: any, out: string) => any); +declare export function render(name: string, context: Context, callback: (err: any, out: string) => any); + +/** +* Compiles and renders source, invoking callback on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required. +* @param source the template string. +* @param context a plain object or an instance of dust.Context. +* @param callback (optional). If supplied the callback will be called passing the result string. If omitted, renderSource() will return a dust.Stream object. +*/ +declare export function renderSource(source: string, context: any): Stream; +declare export function renderSource(source: string, context: Context): Stream; +declare export function renderSource(source: string, context: any, callback: (err: any, out: string) => any): void; +declare export function renderSource(source: string, context: Context, callback: (err: any, out: string) => any): void; + +/** +* Streams the named template. context may be a plain object or an instance of dust.Context. Returns an instance of dust.Stream. +* @param name the template name. +* @param context a plain object or an instance of dust.Context. +*/ +declare export function stream(name: string, context: any): Stream; +declare export function stream(name: string, context: Context): Stream; + +/** +* Manufactures a dust.Context instance with its global object set to object. +* @param global a plain object or an instance of dust.Context. +*/ +declare export function makeBase(global: any): Context; +declare export function makeBase(global: Context): Context; + +declare export function escapeHtml(html: string): string; +declare export function escapeJs(js: string): string; + +declare var helpers: { + [key: string]: (chk: Chunk, ctx: Context, bodies?: any, params?: any) => any; +}; + +declare var filters: { + [key: string]: (value: string) => string; +}; diff --git a/easy-api-request/easy-api-request.d.ts b/easy-api-request/easy-api-request.d.ts index 46accbb37c..a3378b312e 100644 --- a/easy-api-request/easy-api-request.d.ts +++ b/easy-api-request/easy-api-request.d.ts @@ -9,107 +9,106 @@ /// /// -declare module "easy-api-request" { - import stream = require('stream'); - import http = require('http'); - import request = require('request'); - import bunyan = require('bunyan'); - import express = require('express'); - export function create(opts: { - name: any; - config: { - url: string; - internal?: boolean; - headers?: string[]; - cookies?: string[]; - replyCookies?: string[]; - jSend?: boolean; - opts?: Object; - }; - }): void; +import stream = require('stream'); +import http = require('http'); +import request = require('request'); +import bunyan = require('bunyan'); +import express = require('express'); - import Q = require('q'); - interface Result { - response: http.IncomingMessage; - body: any; - err?: any; - data?: any; - } - class BaseRequest { - protected base: request.Request; - protected req: express.Request; - protected log: bunyan.Logger; - protected replyCookies: string[]; - protected jSend: boolean; - constructor(opts: any); - _parseOptions(args: IArguments, type: string): { - opts: any; - cb: any; - }; - _do(args: IArguments, type?: string): any; - _request(opts?: any, cb?:any): any; +declare export function create(opts: { + name: any; + config: { + url: string; + internal?: boolean; + headers?: string[]; + cookies?: string[]; + replyCookies?: string[]; + jSend?: boolean; + opts?: Object; + }; +}): void; - get(url?: any, opts?: any, cb?: any): any; - post(url?: any, opts?: any, cb?: any): any; - patch(url?: any, opts?: any, cb?: any): any; - del(url?: any, opts?: any, cb?: any): any; - } - - class StreamRequest extends BaseRequest { - _request(opts: Object): stream.Stream; - - get(url: string, params: Object): stream.Stream; - get(opts: Object): stream.Stream; - get(url: string): stream.Stream; - - post(url: string, params: Object): stream.Stream; - post(opts: Object): stream.Stream; - post(url: string): stream.Stream; - - patch(url: string, params: Object): stream.Stream; - patch(opts: Object): stream.Stream; - patch(url: string): stream.Stream; - - del(url: string, params: Object): stream.Stream; - del(opts: Object): stream.Stream; - del(url: string): stream.Stream; - } - - class CBPromiseRequest extends BaseRequest { - _request(opts: Object): stream.Stream; - - get(url: string, params: Object, cb:(err?:any, resp?: Result) => void): void; - get(url: string, cb:(err?:any, resp?: Result) => void): void; - get(opts: Object, cb:(err?:any, resp?: Result) => void): void; - get(url: string, params: Object): Q.Promise; - get(opts: Object): Q.Promise; - get(url: string): Q.Promise; - - post(url: string, params: Object, cb:(err?:any, resp?: Result) => void): void; - post(url: string, cb:(err?:any, resp?: Result) => void): void; - post(opts: Object, cb:(err?:any, resp?: Result) => void): void; - post(url: string, params: Object): Q.Promise; - post(opts: Object): Q.Promise; - post(url: string): Q.Promise; - - patch(url: string, params: Object, cb:(err?:any, resp?: Result) => void): void; - patch(url: string, cb:(err?:any, resp?: Result) => void): void; - patch(opts: Object, cb:(err?:any, resp?: Result) => void): void; - patch(url: string, params: Object): Q.Promise; - patch(opts: Object): Q.Promise; - patch(url: string): Q.Promise; - - del(url: string, params: Object, cb:(err?:any, resp?: Result) => void): void; - del(url: string, cb:(err?:any, resp?: Result) => void): void; - del(opts: Object, cb:(err?:any, resp?: Result) => void): void; - del(url: string, params: Object): Q.Promise; - del(opts: Object): Q.Promise; - del(url: string): Q.Promise; - } - - export interface RequestMaker { - (): CBPromiseRequest; - (stream: boolean): StreamRequest | CBPromiseRequest; - } +import Q = require('q'); +interface Result { + response: http.IncomingMessage; + body: any; + err?: any; + data?: any; +} +declare class BaseRequest { + protected base: request.Request; + protected req: express.Request; + protected log: bunyan.Logger; + protected replyCookies: string[]; + protected jSend: boolean; + constructor(opts: any); + _parseOptions(args: IArguments, type: string): { + opts: any; + cb: any; + }; + _do(args: IArguments, type?: string): any; + _request(opts?: any, cb?: any): any; + + get(url?: any, opts?: any, cb?: any): any; + post(url?: any, opts?: any, cb?: any): any; + patch(url?: any, opts?: any, cb?: any): any; + del(url?: any, opts?: any, cb?: any): any; +} + +declare class StreamRequest extends BaseRequest { + _request(opts: Object): stream.Stream; + + get(url: string, params: Object): stream.Stream; + get(opts: Object): stream.Stream; + get(url: string): stream.Stream; + + post(url: string, params: Object): stream.Stream; + post(opts: Object): stream.Stream; + post(url: string): stream.Stream; + + patch(url: string, params: Object): stream.Stream; + patch(opts: Object): stream.Stream; + patch(url: string): stream.Stream; + + del(url: string, params: Object): stream.Stream; + del(opts: Object): stream.Stream; + del(url: string): stream.Stream; +} + +declare class CBPromiseRequest extends BaseRequest { + _request(opts: Object): stream.Stream; + + get(url: string, params: Object, cb: (err?: any, resp?: Result) => void): void; + get(url: string, cb: (err?: any, resp?: Result) => void): void; + get(opts: Object, cb: (err?: any, resp?: Result) => void): void; + get(url: string, params: Object): Q.Promise; + get(opts: Object): Q.Promise; + get(url: string): Q.Promise; + + post(url: string, params: Object, cb: (err?: any, resp?: Result) => void): void; + post(url: string, cb: (err?: any, resp?: Result) => void): void; + post(opts: Object, cb: (err?: any, resp?: Result) => void): void; + post(url: string, params: Object): Q.Promise; + post(opts: Object): Q.Promise; + post(url: string): Q.Promise; + + patch(url: string, params: Object, cb: (err?: any, resp?: Result) => void): void; + patch(url: string, cb: (err?: any, resp?: Result) => void): void; + patch(opts: Object, cb: (err?: any, resp?: Result) => void): void; + patch(url: string, params: Object): Q.Promise; + patch(opts: Object): Q.Promise; + patch(url: string): Q.Promise; + + del(url: string, params: Object, cb: (err?: any, resp?: Result) => void): void; + del(url: string, cb: (err?: any, resp?: Result) => void): void; + del(opts: Object, cb: (err?: any, resp?: Result) => void): void; + del(url: string, params: Object): Q.Promise; + del(opts: Object): Q.Promise; + del(url: string): Q.Promise; +} + +export interface RequestMaker { + (): CBPromiseRequest; + (stream: boolean): StreamRequest | CBPromiseRequest; } diff --git a/easy-table/easy-table-0.2.0.d.ts b/easy-table/easy-table-0.2.0.d.ts index 46fc170c16..1aaf7df01a 100644 --- a/easy-table/easy-table-0.2.0.d.ts +++ b/easy-table/easy-table-0.2.0.d.ts @@ -3,39 +3,38 @@ // Definitions by: Bart van der Schoor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "easy-table" { - class EasyTable { - constructor(); - cell(label: string, value: any, printer?: EasyTable.CellPrinter, width?: number):void; - newRow(): void; - toString(): string; - printTransposed(): string; - print(): string; - sort(fields: string): void; - sort(comparer: (a: any, b: any) => number): void; - total(label: string, accumulator: EasyTable.Accumulator, totalPrinter: EasyTable.CellPrinter): void; - } +declare class EasyTable { + constructor(); - namespace EasyTable { - function printArray(array: any[], cellPrinter?: CellPrinter, tablePrinter?: Printer): string; - function printObject(object: any, cellPrinter?: CellPrinter, tablePrinter?: Printer): string; - - //printer helpers - function Number(length: number): CellPrinter; - function RightPadder(char: string): CellPrinter; - function LeftPadder(char: string): CellPrinter; - - interface CellPrinter extends Function { - (obj: any, cell: (label: string, value: any, width?: number) => void):string; - } - interface Printer extends Function { - (table: EasyTable):string; - } - interface Accumulator extends Function { - (sum: number, val: number, index: number, length: number):number; - } - } - - export = EasyTable; + cell(label: string, value: any, printer?: EasyTable.CellPrinter, width?: number): void; + newRow(): void; + toString(): string; + printTransposed(): string; + print(): string; + sort(fields: string): void; + sort(comparer: (a: any, b: any) => number): void; + total(label: string, accumulator: EasyTable.Accumulator, totalPrinter: EasyTable.CellPrinter): void; } + +declare namespace EasyTable { + function printArray(array: any[], cellPrinter?: CellPrinter, tablePrinter?: Printer): string; + function printObject(object: any, cellPrinter?: CellPrinter, tablePrinter?: Printer): string; + + //printer helpers + function Number(length: number): CellPrinter; + function RightPadder(char: string): CellPrinter; + function LeftPadder(char: string): CellPrinter; + + interface CellPrinter extends Function { + (obj: any, cell: (label: string, value: any, width?: number) => void): string; + } + interface Printer extends Function { + (table: EasyTable): string; + } + interface Accumulator extends Function { + (sum: number, val: number, index: number, length: number): number; + } +} + +export = EasyTable; diff --git a/easy-table/easy-table.d.ts b/easy-table/easy-table.d.ts index ff5bf0928a..f75d74861b 100644 --- a/easy-table/easy-table.d.ts +++ b/easy-table/easy-table.d.ts @@ -3,221 +3,219 @@ // Definitions by: Niklas Mollenhauer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "easy-table" -{ - class EasyTable { - /** - * String to separate columns - */ - public separator: string; +declare class EasyTable { - /** - * Default printer - */ - public static string(value: any): string; + /** + * String to separate columns + */ + public separator: string; - /** - * Create a printer which right aligns the content by padding with `ch` on the left - * - * @param {String} ch - * @returns {Function} - */ - public static leftPadder(ch: string): CellPrinter; + /** + * Default printer + */ + public static string(value: any): string; - public static padLeft: CellPrinter; + /** + * Create a printer which right aligns the content by padding with `ch` on the left + * + * @param {String} ch + * @returns {Function} + */ + public static leftPadder(ch: string): CellPrinter; - /** - * Create a printer which pads with `ch` on the right - * - * @param {String} ch - * @returns {Function} - */ - public static rightPadder(ch: string): CellPrinter; + public static padLeft: CellPrinter; - // public static padRight: CellPrinter; + /** + * Create a printer which pads with `ch` on the right + * + * @param {String} ch + * @returns {Function} + */ + public static rightPadder(ch: string): CellPrinter; - /** - * Create a printer for numbers - * - * Will do right alignment and optionally fix the number of digits after decimal point - * - * @param {Number} [digits] - Number of digits for fixpoint notation - * @returns {Function} - */ - public static number(digits?: number): CellPrinter; + // public static padRight: CellPrinter; - public constructor(); + /** + * Create a printer for numbers + * + * Will do right alignment and optionally fix the number of digits after decimal point + * + * @param {Number} [digits] - Number of digits for fixpoint notation + * @returns {Function} + */ + public static number(digits?: number): CellPrinter; - /** - * Push the current row to the table and start a new one - * - * @returns {Table} `this` - */ - public newRow(): EasyTable; + public constructor(); - /** - * Write cell in the current row - * - * @param {String} col - Column name - * @param {Any} val - Cell value - * @param {Function} [printer] - Printer function to format the value - * @returns {Table} `this` - */ - public cell(col: string, val: T, printer?: CellPrinter): EasyTable; + /** + * Push the current row to the table and start a new one + * + * @returns {Table} `this` + */ + public newRow(): EasyTable; - /** - * Get list of columns in printing order - * - * @returns {string[]} - */ - public columns(): string[]; + /** + * Write cell in the current row + * + * @param {String} col - Column name + * @param {Any} val - Cell value + * @param {Function} [printer] - Printer function to format the value + * @returns {Table} `this` + */ + public cell(col: string, val: T, printer?: CellPrinter): EasyTable; - /** - * Format just rows, i.e. print the table without headers and totals - * - * @returns {String} String representaion of the table - */ - public print(): string; + /** + * Get list of columns in printing order + * + * @returns {string[]} + */ + public columns(): string[]; - /** - * Format the table - * - * @returns {String} - */ - public toString(): string; + /** + * Format just rows, i.e. print the table without headers and totals + * + * @returns {String} String representaion of the table + */ + public print(): string; - /** - * Push delimeter row to the table (with each cell filled with dashs during printing) - * - * @param {String[]} [cols] - * @returns {Table} `this` - */ - public pushDelimeter(cols?: string[]): EasyTable; + /** + * Format the table + * + * @returns {String} + */ + public toString(): string; - /** - * Compute all totals and yield the results to `cb` - * - * @param {Function} cb - Callback function with signature `(column, value, printer)` - */ - public forEachTotal(cb: (column: string, value: T, printer: CellPrinter) => void): void; + /** + * Push delimeter row to the table (with each cell filled with dashs during printing) + * + * @param {String[]} [cols] + * @returns {Table} `this` + */ + public pushDelimeter(cols?: string[]): EasyTable; - /** - * Format the table so that each row represents column and each column represents row - * - * @param {IPrintColumnOptions} [opts] - * @returns {String} - */ - public printTransposed(opts?: PrintColumnOptions): string; + /** + * Compute all totals and yield the results to `cb` + * + * @param {Function} cb - Callback function with signature `(column, value, printer)` + */ + public forEachTotal(cb: (column: string, value: T, printer: CellPrinter) => void): void; - /** - * Sort the table - * - * @param {Function|string[]} [cmp] - Either compare function or a list of columns to sort on - * @returns {Table} `this` - */ - public sort(cmp?: string[]): EasyTable; - /** - * Sort the table - * - * @param {Function|string[]} [cmp] - Either compare function or a list of columns to sort on - * @returns {Table} `this` - */ - public sort(cmp?: CompareFunction): EasyTable; + /** + * Format the table so that each row represents column and each column represents row + * + * @param {IPrintColumnOptions} [opts] + * @returns {String} + */ + public printTransposed(opts?: PrintColumnOptions): string; - /** - * Add a total for the column - * - * @param {String} col - column name - * @param {Object} [opts] - * @returns {Table} `this` - */ - public total(col: string, opts?: TotalOptions): EasyTable; - /** - * Predefined helpers for totals - */ - public static aggr: Aggregators; + /** + * Sort the table + * + * @param {Function|string[]} [cmp] - Either compare function or a list of columns to sort on + * @returns {Table} `this` + */ + public sort(cmp?: string[]): EasyTable; + /** + * Sort the table + * + * @param {Function|string[]} [cmp] - Either compare function or a list of columns to sort on + * @returns {Table} `this` + */ + public sort(cmp?: CompareFunction): EasyTable; - /** - * Print the array or object - * - * @param {Array|Object} obj - Object to print - * @param {Function|Object} [format] - Format options - * @param {Function} [cb] - Table post processing and formating - * @returns {String} - */ - public static print(obj: T | T[], format?: FormatFunction | FormatObject, cb?: TablePostProcessing): string; + /** + * Add a total for the column + * + * @param {String} col - column name + * @param {Object} [opts] + * @returns {Table} `this` + */ + public total(col: string, opts?: TotalOptions): EasyTable; + /** + * Predefined helpers for totals + */ + public static aggr: Aggregators; - /** - * Same as `Table.print()` but yields the result to `console.log()` - */ - public static log(obj: T | T[], format?: FormatFunction | FormatObject, cb?: TablePostProcessing): void; - /** - * Same as `.toString()` but yields the result to `console.log()` - */ - public log(): void; - } + /** + * Print the array or object + * + * @param {Array|Object} obj - Object to print + * @param {Function|Object} [format] - Format options + * @param {Function} [cb] - Table post processing and formating + * @returns {String} + */ + public static print(obj: T | T[], format?: FormatFunction | FormatObject, cb?: TablePostProcessing): string; - type CellPrinter = (val: T, width: number) => string; - type CompareFunction = (a: T, b: T) => number; - type ReduceFunction = (acc: T, val: T, idx: number, length: number) => T; - type FormatFunction = (obj: T, cell: (name: string, val: any) => void) => void; - type TablePostProcessing = (result: EasyTable) => string; - - interface PrintColumnOptions { - /** - * Column separation string - */ - separator?: string; - /** - * Printer to format column names - */ - namePrinter?: CellPrinter; - } - - interface Aggregators { - /** - * Create a printer which formats the value with `printer`, - * adds the `prefix` to it and right aligns the whole thing - * - * @param {String} prefix - * @param {Function} printer - * @returns {printer} - */ - printer(prefix: string, printer: CellPrinter): CellPrinter; - /** - * Sum reduction - */ - sum: any; - /** - * Average reduction - */ - avg: any; - } - - interface TotalOptions { - /** - * reduce(acc, val, idx, length) function to compute the total value - */ - reduce?: ReduceFunction; - /** - * Printer to format the total cell - */ - printer?: CellPrinter; - /** - * Initial value for reduction - */ - init?: T; - } - - interface FormatObject { - [key: string]: ColumnFormat; - } - - interface ColumnFormat { - name?: string; - printer?: CellPrinter - } - - export = EasyTable; + /** + * Same as `Table.print()` but yields the result to `console.log()` + */ + public static log(obj: T | T[], format?: FormatFunction | FormatObject, cb?: TablePostProcessing): void; + /** + * Same as `.toString()` but yields the result to `console.log()` + */ + public log(): void; } + +type CellPrinter = (val: T, width: number) => string; +type CompareFunction = (a: T, b: T) => number; +type ReduceFunction = (acc: T, val: T, idx: number, length: number) => T; +type FormatFunction = (obj: T, cell: (name: string, val: any) => void) => void; +type TablePostProcessing = (result: EasyTable) => string; + +interface PrintColumnOptions { + /** + * Column separation string + */ + separator?: string; + /** + * Printer to format column names + */ + namePrinter?: CellPrinter; +} + +interface Aggregators { + /** + * Create a printer which formats the value with `printer`, + * adds the `prefix` to it and right aligns the whole thing + * + * @param {String} prefix + * @param {Function} printer + * @returns {printer} + */ + printer(prefix: string, printer: CellPrinter): CellPrinter; + /** + * Sum reduction + */ + sum: any; + /** + * Average reduction + */ + avg: any; +} + +interface TotalOptions { + /** + * reduce(acc, val, idx, length) function to compute the total value + */ + reduce?: ReduceFunction; + /** + * Printer to format the total cell + */ + printer?: CellPrinter; + /** + * Initial value for reduction + */ + init?: T; +} + +interface FormatObject { + [key: string]: ColumnFormat; +} + +interface ColumnFormat { + name?: string; + printer?: CellPrinter +} + +export = EasyTable; diff --git a/easy-xapi-supertest/easy-xapi-supertest.d.ts b/easy-xapi-supertest/easy-xapi-supertest.d.ts index 5a8525e0a4..995f2fa581 100644 --- a/easy-xapi-supertest/easy-xapi-supertest.d.ts +++ b/easy-xapi-supertest/easy-xapi-supertest.d.ts @@ -5,25 +5,24 @@ /// -declare module "easy-xapi-supertest" { - import express = require('express'); - export interface BodyAgent { - send(data: Object): any; - attach(arg1: any, arg2?: any): any; - } +import express = require('express'); - export interface Agent { - get(url:string): any; - delete(url:string): any; - post(url:string): BodyAgent; - patch(url:string): BodyAgent; - put(url:string): BodyAgent; - } - - interface getAgent { - (...args:any[]): Agent - } - - export function getAgentFactory(app: express.Application, transform?: Function): getAgent; +export interface BodyAgent { + send(data: Object): any; + attach(arg1: any, arg2?: any): any; } + +export interface Agent { + get(url: string): any; + delete(url: string): any; + post(url: string): BodyAgent; + patch(url: string): BodyAgent; + put(url: string): BodyAgent; +} + +interface getAgent { + (...args: any[]): Agent +} + +declare export function getAgentFactory(app: express.Application, transform?: Function): getAgent; diff --git a/easy-xapi-utils/easy-xapi-utils.d.ts b/easy-xapi-utils/easy-xapi-utils.d.ts index b49a7d37f5..3af9fec5ff 100644 --- a/easy-xapi-utils/easy-xapi-utils.d.ts +++ b/easy-xapi-utils/easy-xapi-utils.d.ts @@ -7,10 +7,9 @@ /// /// -declare module "easy-xapi-utils" { - import express = require('express'); - export function isLoggedIn(role?: string): express.RequestHandler; - export function isLoggedOut(): express.RequestHandler; - export function hasRole(role: string): express.RequestHandler; -} +import express = require('express'); + +declare export function isLoggedIn(role?: string): express.RequestHandler; +declare export function isLoggedOut(): express.RequestHandler; +declare export function hasRole(role: string): express.RequestHandler; diff --git a/ejs-locals/ejs-locals.d.ts b/ejs-locals/ejs-locals.d.ts index 2cf598b266..6398ee199f 100644 --- a/ejs-locals/ejs-locals.d.ts +++ b/ejs-locals/ejs-locals.d.ts @@ -3,9 +3,8 @@ // Definitions by: jt000 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "ejs-locals" { - function ejsLocals(): Function; - export = ejsLocals; -} \ No newline at end of file +declare function ejsLocals(): Function; + +export = ejsLocals; diff --git a/ejs/ejs.d.ts b/ejs/ejs.d.ts index 6e2347fbc5..e77656a418 100644 --- a/ejs/ejs.d.ts +++ b/ejs/ejs.d.ts @@ -4,88 +4,87 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "ejs" { - namespace Ejs { - type Data = { [name: string]: any }; - type Dependencies = string[]; - var cache: Cache; - var localsName: string; - function resolveInclude(name: string, filename: string): string; - function compile(template: string, opts?: Options): (TemplateFunction); - function render(template: string, data?: Data, opts?: Options): string; - function renderFile(path: string, data?: Data, opts?: Options, cb?: Function): any;// TODO RenderFileCallback return type - function clearCache(): any; - function TemplateFunction(data: Data): any; - interface TemplateFunction { - dependencies: Dependencies; - } - interface Options { - cache?: any; - filename?: string; - context?: any; - compileDebug?: boolean; - client?: boolean; - delimiter?: string; - debug?: any; - _with?: boolean; - } - class Template { - constructor(text: string, opts: Options); - opts: Options; - templateText: string; - mode: string; - truncate: boolean; - currentLine: number; - source: string; - dependencies: Dependencies; - createRegex(): RegExp; - compile(): TemplateFunction; - generateSource(): any; - parseTemplateText(): string[]; - scanLine(line: string): any; - - } - namespace Template { - interface MODES { - EVAL: string; - ESCAPED: string; - RAW: string; - COMMENT: string; - LITERAL: string; - } - } - function escapeRegexChars(s: string): string; - function escapeXML(markup: string): string; - function shallowCopy(to: T1, fro: any): T1; - interface Cache { - _data: { [name: string]: any }; - set(key: string, val: any): any; - get(key: string): any; - } - var cache: Cache; - function resolve(from1: string, to: string): string; - function resolve(from1: string, from2: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, from8: string, to: string): string; - function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, from8: string, from9: string, to: string): string; - function resolve(...args: string[]): string; - function normalize(path: string): string; - function isAbsolute(path: string): boolean; - function join(...args: string[]): string; - function relative(from: string, to: string): string; - var sep: string; - var delimiter: string; - function dirname(path: string): string; - function basename(path: string): string; - function extname(path: string): string; - function filter(xs: any, f: any): any; // TODO WHUT? +declare namespace Ejs { + type Data = { [name: string]: any }; + type Dependencies = string[]; + var cache: Cache; + var localsName: string; + function resolveInclude(name: string, filename: string): string; + function compile(template: string, opts?: Options): (TemplateFunction); + function render(template: string, data?: Data, opts?: Options): string; + function renderFile(path: string, data?: Data, opts?: Options, cb?: Function): any;// TODO RenderFileCallback return type + function clearCache(): any; + function TemplateFunction(data: Data): any; + interface TemplateFunction { + dependencies: Dependencies; + } + interface Options { + cache?: any; + filename?: string; + context?: any; + compileDebug?: boolean; + client?: boolean; + delimiter?: string; + debug?: any; + _with?: boolean; + } + class Template { + constructor(text: string, opts: Options); + opts: Options; + templateText: string; + mode: string; + truncate: boolean; + currentLine: number; + source: string; + dependencies: Dependencies; + createRegex(): RegExp; + compile(): TemplateFunction; + generateSource(): any; + parseTemplateText(): string[]; + scanLine(line: string): any; } - export = Ejs; + namespace Template { + interface MODES { + EVAL: string; + ESCAPED: string; + RAW: string; + COMMENT: string; + LITERAL: string; + } + } + function escapeRegexChars(s: string): string; + function escapeXML(markup: string): string; + function shallowCopy(to: T1, fro: any): T1; + interface Cache { + _data: { [name: string]: any }; + set(key: string, val: any): any; + get(key: string): any; + } + var cache: Cache; + function resolve(from1: string, to: string): string; + function resolve(from1: string, from2: string, to: string): string; + function resolve(from1: string, from2: string, from3: string, to: string): string; + function resolve(from1: string, from2: string, from3: string, from4: string, to: string): string; + function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, to: string): string; + function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, to: string): string; + function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, to: string): string; + function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, from8: string, to: string): string; + function resolve(from1: string, from2: string, from3: string, from4: string, from5: string, from6: string, from7: string, from8: string, from9: string, to: string): string; + function resolve(...args: string[]): string; + function normalize(path: string): string; + function isAbsolute(path: string): boolean; + function join(...args: string[]): string; + function relative(from: string, to: string): string; + var sep: string; + var delimiter: string; + function dirname(path: string): string; + function basename(path: string): string; + function extname(path: string): string; + function filter(xs: any, f: any): any; // TODO WHUT? + + } +export = Ejs; diff --git a/electron-json-storage/electron-json-storage.d.ts b/electron-json-storage/electron-json-storage.d.ts index 0ea790638f..8a622ab459 100644 --- a/electron-json-storage/electron-json-storage.d.ts +++ b/electron-json-storage/electron-json-storage.d.ts @@ -3,11 +3,10 @@ // Definitions by: Sam Saint-Pettersen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "electron-json-storage" { - export function get(key: string, callback: (error: any, data: Object) => void): void; - export function set(key: string, json: Object, callback: (error: any) => void): void; - export function has(key: string, callback: (error: any, hasKey: boolean) => void): void; - export function keys(callback: (error: any, keys: string[]) => void): void; - export function remove(key: string, callback: (error: any) => void): void; - export function clear(callback: (error: any) => void): void; -} + +declare export function get(key: string, callback: (error: any, data: Object) => void): void; +declare export function set(key: string, json: Object, callback: (error: any) => void): void; +declare export function has(key: string, callback: (error: any, hasKey: boolean) => void): void; +declare export function keys(callback: (error: any, keys: string[]) => void): void; +declare export function remove(key: string, callback: (error: any) => void): void; +declare export function clear(callback: (error: any) => void): void; diff --git a/element-resize-event/element-resize-event.d.ts b/element-resize-event/element-resize-event.d.ts index 3152568f8a..e500d2e7f9 100644 --- a/element-resize-event/element-resize-event.d.ts +++ b/element-resize-event/element-resize-event.d.ts @@ -3,7 +3,6 @@ // Definitions by: Rogier Schouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "element-resize-event" { - function elementResizeEvent(domNode: Element, callback: () => void): void; - export = elementResizeEvent; -} + +declare function elementResizeEvent(domNode: Element, callback: () => void): void; +export = elementResizeEvent; diff --git a/email-addresses/email-addresses.d.ts b/email-addresses/email-addresses.d.ts index c8cd74d1a0..f8ff9455d7 100644 --- a/email-addresses/email-addresses.d.ts +++ b/email-addresses/email-addresses.d.ts @@ -3,7 +3,6 @@ // Definitions by: John Grimsey // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "email-addresses" { - function parseOneAddress(opts: any): any; - function parseAddressList(opts: any): any; -} + +declare function parseOneAddress(opts: any): any; +declare function parseAddressList(opts: any): any; diff --git a/email-validator/email-validator.d.ts b/email-validator/email-validator.d.ts index 299ebb19f6..cfb077eb53 100644 --- a/email-validator/email-validator.d.ts +++ b/email-validator/email-validator.d.ts @@ -3,6 +3,5 @@ // Definitions by: Paul Lessing // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "email-validator" { - export function validate(email: String): boolean; -} + +declare export function validate(email: String): boolean; diff --git a/encoding-japanese/encoding-japanese.d.ts b/encoding-japanese/encoding-japanese.d.ts index 0392926694..40740871cf 100644 --- a/encoding-japanese/encoding-japanese.d.ts +++ b/encoding-japanese/encoding-japanese.d.ts @@ -5,45 +5,43 @@ /// -declare module "encoding-japanese" { - export type Encoding = - "UTF32" | "UTF16" | "UTF16BE" | - "UTF16LE" | "BINARY" | "ASCII" | - "JIS" | "UTF8" | "EUCJP" | - "SJIS" | "UNICODE" | "AUTO"; - type RawType = string | Uint8Array | number[] | Buffer; - interface ConvertOptions { - to: Encoding; - from?: Encoding; - type?: "string" | "arraybuffer" | "array"; - bom?: boolean | string; - } +export type Encoding = + "UTF32" | "UTF16" | "UTF16BE" | + "UTF16LE" | "BINARY" | "ASCII" | + "JIS" | "UTF8" | "EUCJP" | + "SJIS" | "UNICODE" | "AUTO"; +type RawType = string | Uint8Array | number[] | Buffer; - export function detect(data: RawType, encodings?: Encoding | Encoding[]): Encoding; - export function convert(data: RawType, to: Encoding, from?: Encoding): number[]; - export function convert(data: RawType, options: ConvertOptions): string | ArrayBuffer | number[]; - export function urlEncode(data: number[] | Uint8Array): string; - export function urlDecode(data: string): number[]; - export function base64Encode(data: number[] | Uint8Array): string; - export function base64Decode(data: string): number[]; - export function codeToString(data: number[] | Uint8Array): string; - export function stringToCode(data: string): number[]; - export function toHankakuCase(data: number[]): number[]; - export function toHankakuCase(data: string): string; - export function toZenkakuCase(data: number[]): number[]; - export function toZenkakuCase(data: string): string; - export function toHiraganaCase(data: number[]): number[]; - export function toHiraganaCase(data: string): string; - export function toKatakanaCase(data: number[]): number[]; - export function toKatakanaCase(data: string): string; - export function toHankanaCase(data: number[]): number[]; - export function toHankanaCase(data: string): string; - export function toZenkanaCase(data: number[]): number[]; - export function toZenkanaCase(data: string): string; - export function toHankakuSpace(data: number[]): number[]; - export function toHankakuSpace(data: string): string; - export function toZenkakuSpace(data: number[]): number[]; - export function toZenkakuSpace(data: string): string; +interface ConvertOptions { + to: Encoding; + from?: Encoding; + type?: "string" | "arraybuffer" | "array"; + bom?: boolean | string; } +declare export function detect(data: RawType, encodings?: Encoding | Encoding[]): Encoding; +declare export function convert(data: RawType, to: Encoding, from?: Encoding): number[]; +declare export function convert(data: RawType, options: ConvertOptions): string | ArrayBuffer | number[]; +declare export function urlEncode(data: number[] | Uint8Array): string; +declare export function urlDecode(data: string): number[]; +declare export function base64Encode(data: number[] | Uint8Array): string; +declare export function base64Decode(data: string): number[]; +declare export function codeToString(data: number[] | Uint8Array): string; +declare export function stringToCode(data: string): number[]; +declare export function toHankakuCase(data: number[]): number[]; +declare export function toHankakuCase(data: string): string; +declare export function toZenkakuCase(data: number[]): number[]; +declare export function toZenkakuCase(data: string): string; +declare export function toHiraganaCase(data: number[]): number[]; +declare export function toHiraganaCase(data: string): string; +declare export function toKatakanaCase(data: number[]): number[]; +declare export function toKatakanaCase(data: string): string; +declare export function toHankanaCase(data: number[]): number[]; +declare export function toHankanaCase(data: string): string; +declare export function toZenkanaCase(data: number[]): number[]; +declare export function toZenkanaCase(data: string): string; +declare export function toHankakuSpace(data: number[]): number[]; +declare export function toHankakuSpace(data: string): string; +declare export function toZenkakuSpace(data: number[]): number[]; +declare export function toZenkakuSpace(data: string): string; diff --git a/enzyme/enzyme.d.ts b/enzyme/enzyme.d.ts index 9047fbf728..b4fe19737e 100644 --- a/enzyme/enzyme.d.ts +++ b/enzyme/enzyme.d.ts @@ -5,407 +5,406 @@ /// -declare module "enzyme" { - import {ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes} from "react"; - export class ElementClass extends Component { - } +import {ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes} from "react"; + +declare export class ElementClass extends Component { +} + +/** + * Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the + * following three categories: + * + * 1. A Valid CSS Selector + * 2. A React Component Constructor + * 3. A React Component's displayName + */ +export type EnzymeSelector = String | typeof ElementClass; + +interface CommonWrapper { + /** + * Find every node in the render tree that matches the provided selector. + * @param selector The selector to match. + */ + find(component: ComponentClass): CommonWrapper; + find(statelessComponent: StatelessComponent): CommonWrapper; + find(selector: string): CommonWrapper; /** - * Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the - * following three categories: + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (wrapper: CommonWrapper) => Boolean): CommonWrapper; + + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(component: ComponentClass): CommonWrapper; + filter(statelessComponent: StatelessComponent): CommonWrapper; + filter(selector: string): CommonWrapper; + + /** + * Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true. + * @param predicate + */ + filterWhere(predicate: (wrapper: this) => Boolean): this; + + /** + * Returns whether or not the current wrapper has a node anywhere in it's render tree that looks like the one passed in. + * @param node + */ + contains(node: ReactElement): Boolean; + + /** + * Returns whether or not the current node has a className prop including the passed in class name. + * @param className + */ + hasClass(className: String): Boolean; + + /** + * Returns whether or not the current node matches a provided selector. + * @param selector + */ + is(selector: EnzymeSelector): Boolean; + + /** + * Returns a new wrapper with only the nodes of the current wrapper that don't match the provided selector. + * This method is effectively the negation or inverse of filter. + * @param selector + */ + not(selector: EnzymeSelector): this; + + /** + * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector + * can be provided and it will filter the children by this selector. + * @param [selector] + */ + children(component: ComponentClass): CommonWrapper; + children(statelessComponent: StatelessComponent): CommonWrapper; + children(selector: string): CommonWrapper; + children(): CommonWrapper; + + /** + * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the + * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. * - * 1. A Valid CSS Selector - * 2. A React Component Constructor - * 3. A React Component's displayName + * Note: can only be called on a wrapper of a single node. + * @param [selector] */ - export type EnzymeSelector = String | typeof ElementClass; - - interface CommonWrapper { - /** - * Find every node in the render tree that matches the provided selector. - * @param selector The selector to match. - */ - find(component: ComponentClass): CommonWrapper; - find(statelessComponent: StatelessComponent): CommonWrapper; - find(selector: string): CommonWrapper; - - /** - * Finds every node in the render tree that returns true for the provided predicate function. - * @param predicate - */ - findWhere(predicate: (wrapper: CommonWrapper) => Boolean): CommonWrapper; - - /** - * Removes nodes in the current wrapper that do not match the provided selector. - * @param selector The selector to match. - */ - filter(component: ComponentClass): CommonWrapper; - filter(statelessComponent: StatelessComponent): CommonWrapper; - filter(selector: string): CommonWrapper; - - /** - * Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true. - * @param predicate - */ - filterWhere(predicate: (wrapper: this) => Boolean): this; - - /** - * Returns whether or not the current wrapper has a node anywhere in it's render tree that looks like the one passed in. - * @param node - */ - contains(node: ReactElement): Boolean; - - /** - * Returns whether or not the current node has a className prop including the passed in class name. - * @param className - */ - hasClass(className: String): Boolean; - - /** - * Returns whether or not the current node matches a provided selector. - * @param selector - */ - is(selector: EnzymeSelector): Boolean; - - /** - * Returns a new wrapper with only the nodes of the current wrapper that don't match the provided selector. - * This method is effectively the negation or inverse of filter. - * @param selector - */ - not(selector: EnzymeSelector): this; - - /** - * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector - * can be provided and it will filter the children by this selector. - * @param [selector] - */ - children(component: ComponentClass): CommonWrapper; - children(statelessComponent: StatelessComponent): CommonWrapper; - children(selector: string): CommonWrapper; - children(): CommonWrapper; - - /** - * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the - * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. - * - * Note: can only be called on a wrapper of a single node. - * @param [selector] - */ - parents(component: ComponentClass): CommonWrapper; - parents(statelessComponent: StatelessComponent): CommonWrapper; - parents(selector: string): CommonWrapper; - parents(): CommonWrapper; - - /** - * Returns a wrapper with the direct parent of the node in the current wrapper. - */ - parent(): CommonWrapper; - - /** - * Returns a wrapper of the first element that matches the selector by traversing up through the current node's - * ancestors in the tree, starting with itself. - * - * Note: can only be called on a wrapper of a single node. - * @param selector - */ - closest(component: ComponentClass): CommonWrapper; - closest(statelessComponent: StatelessComponent): CommonWrapper; - closest(selector: string): CommonWrapper; - - /** - * Returns a string of the rendered text of the current render tree. This function should be looked at with - * skepticism if being used to test what the actual HTML output of the component will be. If that is what you - * would like to test, use enzyme's render function instead. - * - * Note: can only be called on a wrapper of a single node. - */ - text(): String; - - /** - * Returns a string of the rendered HTML markup of the current render tree. - * - * Note: can only be called on a wrapper of a single node. - */ - html(): String; - - /** - * Returns the node at a given index of the current wrapper. - * @param index - */ - get(index: number): ReactElement; - - /** - * Returns a wrapper around the node at a given index of the current wrapper. - * @param index - */ - at(index: number): this; - - /** - * Reduce the set of matched nodes to the first in the set. - */ - first(): this; - - /** - * Reduce the set of matched nodes to the last in the set. - */ - last(): this; - - /** - * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. - * @param [key] - */ - state(key?: String): any; - - /** - * Returns the props hash for the current node of the wrapper. - * - * NOTE: can only be called on a wrapper of a single node. - */ - props(): P; - - /** - * Returns the prop value for the node of the current wrapper with the provided key. - * - * NOTE: can only be called on a wrapper of a single node. - * @param key - */ - prop(key: String): any; - - /** - * Simulate events. - * Returns itself. - * @param event - * @param args? - */ - simulate(event: string, ...args: any[]): this; - - /** - * A method to invoke setState() on the root component instance similar to how you might in the definition of - * the component, and re-renders. This method is useful for testing your component in hard to achieve states, - * however should be used sparingly. If possible, you should utilize your component's external API in order to - * get it into whatever state you want to test, in order to be as accurate of a test as possible. This is not - * always practical, however. - * Returns itself. - * - * NOTE: can only be called on a wrapper instance that is also the root instance. - * @param state - */ - setState(state: S): this; - - /** - * A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test - * how the component behaves over time with changing props. Calling this, for instance, will call the - * componentWillReceiveProps lifecycle method. - * - * Similar to setState, this method accepts a props object and will merge it in with the already existing props. - * Returns itself. - * - * NOTE: can only be called on a wrapper instance that is also the root instance. - * @param state - */ - setProps(props: P): this; - - /** - * A method that sets the context of the root component, and re-renders. Useful for when you are wanting to - * test how the component behaves over time with changing contexts. - * Returns itself. - * - * NOTE: can only be called on a wrapper instance that is also the root instance. - * @param state - */ - setContext(context: Object): this; - - /** - * Gets the instance of the component being rendered as the root node passed into shallow(). - * - * NOTE: can only be called on a wrapper instance that is also the root instance. - */ - instance(): Component; - - /** - * Forces a re-render. Useful to run before checking the render output if something external may be updating - * the state of the component somewhere. - * Returns itself. - * - * NOTE: can only be called on a wrapper instance that is also the root instance. - */ - update(): this; - - /** - * Returns an html-like string of the wrapper for debugging purposes. Useful to print out to the console when - * tests are not passing when you expect them to. - */ - debug(): String; - - /** - * Returns the type of the current node of this wrapper. If it's a composite component, this will be the - * component constructor. If it's native DOM node, it will be a string of the tag name. - * - * Note: can only be called on a wrapper of a single node. - */ - type(): String | Function; - - /** - * Iterates through each node of the current wrapper and executes the provided function with a wrapper around - * the corresponding node passed in as the first argument. - * - * Returns itself. - * @param fn A callback to be run for every node in the collection. Should expect a ShallowWrapper as the first - * argument, and will be run with a context of the original instance. - */ - forEach(fn: (wrapper: this) => any): this; - - /** - * Maps the current array of nodes to another array. Each node is passed in as a ShallowWrapper to the map - * function. - * Returns an array of the returned values from the mapping function.. - * @param fn A mapping function to be run for every node in the collection, the results of which will be mapped - * to the returned array. Should expect a ShallowWrapper as the first argument, and will be run - * with a context of the original instance. - */ - map(fn: (wrapper: this) => V): V[]; - - /** - * Applies the provided reducing function to every node in the wrapper to reduce to a single value. Each node - * is passed in as a ShallowWrapper, and is processed from left to right. - * @param fn - * @param initialValue - */ - reduce(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R[]; - - /** - * Applies the provided reducing function to every node in the wrapper to reduce to a single value. - * Each node is passed in as a ShallowWrapper, and is processed from right to left. - * @param fn - * @param initialValue - */ - reduceRight(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R[]; - - /** - * Returns whether or not any of the nodes in the wrapper match the provided selector. - * @param selector - */ - some(selector: EnzymeSelector): Boolean; - - /** - * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. - * @param fn - */ - someWhere(fn: (wrapper: this) => Boolean): Boolean; - - /** - * Returns whether or not all of the nodes in the wrapper match the provided selector. - * @param selector - */ - every(selector: EnzymeSelector): Boolean; - - /** - * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. - * @param fn - */ - everyWhere(fn: (wrapper: this) => Boolean): Boolean; - - length: number; - } - - export interface ShallowWrapper extends CommonWrapper { - shallow(): ShallowWrapper; - render(): CheerioWrapper; - - /** - * Find every node in the render tree that matches the provided selector. - * @param selector The selector to match. - */ - find(component: ComponentClass): ShallowWrapper; - find(statelessComponent: (props: P2) => JSX.Element): ShallowWrapper; - find(selector: string): ShallowWrapper; - - /** - * Removes nodes in the current wrapper that do not match the provided selector. - * @param selector The selector to match. - */ - filter(component: ComponentClass): ShallowWrapper; - filter(statelessComponent: StatelessComponent): ShallowWrapper; - filter(selector: string): ShallowWrapper; - - /** - * Finds every node in the render tree that returns true for the provided predicate function. - * @param predicate - */ - findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ShallowWrapper; - - /** - * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector - * can be provided and it will filter the children by this selector. - * @param [selector] - */ - children(component: ComponentClass): ShallowWrapper; - children(statelessComponent: StatelessComponent): ShallowWrapper; - children(selector: string): ShallowWrapper; - children(): ShallowWrapper; - - /** - * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the - * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. - * - * Note: can only be called on a wrapper of a single node. - * @param [selector] - */ - parents(component: ComponentClass): ShallowWrapper; - parents(statelessComponent: StatelessComponent): ShallowWrapper; - parents(selector: string): ShallowWrapper; - parents(): ShallowWrapper; - - /** - * Returns a wrapper of the first element that matches the selector by traversing up through the current node's - * ancestors in the tree, starting with itself. - * - * Note: can only be called on a wrapper of a single node. - * @param selector - */ - closest(component: ComponentClass): ShallowWrapper; - closest(statelessComponent: StatelessComponent): ShallowWrapper; - closest(selector: string): ShallowWrapper; - - /** - * Returns a wrapper with the direct parent of the node in the current wrapper. - */ - parent(): ShallowWrapper; - } - - export interface ReactWrapper extends CommonWrapper { - - } - - export interface CheerioWrapper extends CommonWrapper { - - } + parents(component: ComponentClass): CommonWrapper; + parents(statelessComponent: StatelessComponent): CommonWrapper; + parents(selector: string): CommonWrapper; + parents(): CommonWrapper; /** - * Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that - * your tests aren't indirectly asserting on behavior of child components. - * @param node - * @param [options] + * Returns a wrapper with the direct parent of the node in the current wrapper. */ - export function shallow(node: ReactElement

, options?: any): ShallowWrapper; + parent(): CommonWrapper; /** - * Mounts and renders a react component into the document and provides a testing wrapper around it. - * @param node - * @param [options] + * Returns a wrapper of the first element that matches the selector by traversing up through the current node's + * ancestors in the tree, starting with itself. + * + * Note: can only be called on a wrapper of a single node. + * @param selector */ - export function mount(node: ReactElement

, options?: any): ReactWrapper; + closest(component: ComponentClass): CommonWrapper; + closest(statelessComponent: StatelessComponent): CommonWrapper; + closest(selector: string): CommonWrapper; /** - * Render react components to static HTML and analyze the resulting HTML structure. - * @param node - * @param [options] + * Returns a string of the rendered text of the current render tree. This function should be looked at with + * skepticism if being used to test what the actual HTML output of the component will be. If that is what you + * would like to test, use enzyme's render function instead. + * + * Note: can only be called on a wrapper of a single node. */ - export function render(node: ReactElement

, options?: any): CheerioWrapper; + text(): String; - export function describeWithDOM(description: String, fn: Function): void; + /** + * Returns a string of the rendered HTML markup of the current render tree. + * + * Note: can only be called on a wrapper of a single node. + */ + html(): String; - export function spyLifecycle(component: typeof Component): void; -} \ No newline at end of file + /** + * Returns the node at a given index of the current wrapper. + * @param index + */ + get(index: number): ReactElement; + + /** + * Returns a wrapper around the node at a given index of the current wrapper. + * @param index + */ + at(index: number): this; + + /** + * Reduce the set of matched nodes to the first in the set. + */ + first(): this; + + /** + * Reduce the set of matched nodes to the last in the set. + */ + last(): this; + + /** + * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. + * @param [key] + */ + state(key?: String): any; + + /** + * Returns the props hash for the current node of the wrapper. + * + * NOTE: can only be called on a wrapper of a single node. + */ + props(): P; + + /** + * Returns the prop value for the node of the current wrapper with the provided key. + * + * NOTE: can only be called on a wrapper of a single node. + * @param key + */ + prop(key: String): any; + + /** + * Simulate events. + * Returns itself. + * @param event + * @param args? + */ + simulate(event: string, ...args: any[]): this; + + /** + * A method to invoke setState() on the root component instance similar to how you might in the definition of + * the component, and re-renders. This method is useful for testing your component in hard to achieve states, + * however should be used sparingly. If possible, you should utilize your component's external API in order to + * get it into whatever state you want to test, in order to be as accurate of a test as possible. This is not + * always practical, however. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + * @param state + */ + setState(state: S): this; + + /** + * A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test + * how the component behaves over time with changing props. Calling this, for instance, will call the + * componentWillReceiveProps lifecycle method. + * + * Similar to setState, this method accepts a props object and will merge it in with the already existing props. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + * @param state + */ + setProps(props: P): this; + + /** + * A method that sets the context of the root component, and re-renders. Useful for when you are wanting to + * test how the component behaves over time with changing contexts. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + * @param state + */ + setContext(context: Object): this; + + /** + * Gets the instance of the component being rendered as the root node passed into shallow(). + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + */ + instance(): Component; + + /** + * Forces a re-render. Useful to run before checking the render output if something external may be updating + * the state of the component somewhere. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + */ + update(): this; + + /** + * Returns an html-like string of the wrapper for debugging purposes. Useful to print out to the console when + * tests are not passing when you expect them to. + */ + debug(): String; + + /** + * Returns the type of the current node of this wrapper. If it's a composite component, this will be the + * component constructor. If it's native DOM node, it will be a string of the tag name. + * + * Note: can only be called on a wrapper of a single node. + */ + type(): String | Function; + + /** + * Iterates through each node of the current wrapper and executes the provided function with a wrapper around + * the corresponding node passed in as the first argument. + * + * Returns itself. + * @param fn A callback to be run for every node in the collection. Should expect a ShallowWrapper as the first + * argument, and will be run with a context of the original instance. + */ + forEach(fn: (wrapper: this) => any): this; + + /** + * Maps the current array of nodes to another array. Each node is passed in as a ShallowWrapper to the map + * function. + * Returns an array of the returned values from the mapping function.. + * @param fn A mapping function to be run for every node in the collection, the results of which will be mapped + * to the returned array. Should expect a ShallowWrapper as the first argument, and will be run + * with a context of the original instance. + */ + map(fn: (wrapper: this) => V): V[]; + + /** + * Applies the provided reducing function to every node in the wrapper to reduce to a single value. Each node + * is passed in as a ShallowWrapper, and is processed from left to right. + * @param fn + * @param initialValue + */ + reduce(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R[]; + + /** + * Applies the provided reducing function to every node in the wrapper to reduce to a single value. + * Each node is passed in as a ShallowWrapper, and is processed from right to left. + * @param fn + * @param initialValue + */ + reduceRight(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R[]; + + /** + * Returns whether or not any of the nodes in the wrapper match the provided selector. + * @param selector + */ + some(selector: EnzymeSelector): Boolean; + + /** + * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. + * @param fn + */ + someWhere(fn: (wrapper: this) => Boolean): Boolean; + + /** + * Returns whether or not all of the nodes in the wrapper match the provided selector. + * @param selector + */ + every(selector: EnzymeSelector): Boolean; + + /** + * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. + * @param fn + */ + everyWhere(fn: (wrapper: this) => Boolean): Boolean; + + length: number; +} + +export interface ShallowWrapper extends CommonWrapper { + shallow(): ShallowWrapper; + render(): CheerioWrapper; + + /** + * Find every node in the render tree that matches the provided selector. + * @param selector The selector to match. + */ + find(component: ComponentClass): ShallowWrapper; + find(statelessComponent: (props: P2) => JSX.Element): ShallowWrapper; + find(selector: string): ShallowWrapper; + + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(component: ComponentClass): ShallowWrapper; + filter(statelessComponent: StatelessComponent): ShallowWrapper; + filter(selector: string): ShallowWrapper; + + /** + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ShallowWrapper; + + /** + * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector + * can be provided and it will filter the children by this selector. + * @param [selector] + */ + children(component: ComponentClass): ShallowWrapper; + children(statelessComponent: StatelessComponent): ShallowWrapper; + children(selector: string): ShallowWrapper; + children(): ShallowWrapper; + + /** + * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the + * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. + * + * Note: can only be called on a wrapper of a single node. + * @param [selector] + */ + parents(component: ComponentClass): ShallowWrapper; + parents(statelessComponent: StatelessComponent): ShallowWrapper; + parents(selector: string): ShallowWrapper; + parents(): ShallowWrapper; + + /** + * Returns a wrapper of the first element that matches the selector by traversing up through the current node's + * ancestors in the tree, starting with itself. + * + * Note: can only be called on a wrapper of a single node. + * @param selector + */ + closest(component: ComponentClass): ShallowWrapper; + closest(statelessComponent: StatelessComponent): ShallowWrapper; + closest(selector: string): ShallowWrapper; + + /** + * Returns a wrapper with the direct parent of the node in the current wrapper. + */ + parent(): ShallowWrapper; +} + +export interface ReactWrapper extends CommonWrapper { + +} + +export interface CheerioWrapper extends CommonWrapper { + +} + +/** + * Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that + * your tests aren't indirectly asserting on behavior of child components. + * @param node + * @param [options] + */ +declare export function shallow(node: ReactElement

, options?: any): ShallowWrapper; + +/** + * Mounts and renders a react component into the document and provides a testing wrapper around it. + * @param node + * @param [options] + */ +declare export function mount(node: ReactElement

, options?: any): ReactWrapper; + +/** + * Render react components to static HTML and analyze the resulting HTML structure. + * @param node + * @param [options] + */ +declare export function render(node: ReactElement

, options?: any): CheerioWrapper; + +declare export function describeWithDOM(description: String, fn: Function): void; + +declare export function spyLifecycle(component: typeof Component): void; diff --git a/errorhandler/errorhandler.d.ts b/errorhandler/errorhandler.d.ts index bb1674c1e5..247383ca14 100644 --- a/errorhandler/errorhandler.d.ts +++ b/errorhandler/errorhandler.d.ts @@ -5,28 +5,27 @@ /// -declare module "errorhandler" { - import * as express from 'express'; - function errorHandler(options?: errorHandler.Options): express.ErrorRequestHandler; +import * as express from 'express'; - namespace errorHandler { - interface LoggingCallback { - (err: Error, str: string, req: express.Request, res: express.Response): void; - } +declare function errorHandler(options?: errorHandler.Options): express.ErrorRequestHandler; - interface Options { - /** - * Defaults to true. - * - * Possible values: - * true : Log errors using console.error(str). - * false : Only send the error back in the response. - * A function : pass the error to a function for handling. - */ - log: boolean | LoggingCallback; - } +declare namespace errorHandler { + interface LoggingCallback { + (err: Error, str: string, req: express.Request, res: express.Response): void; } - export = errorHandler; + interface Options { + /** + * Defaults to true. + * + * Possible values: + * true : Log errors using console.error(str). + * false : Only send the error back in the response. + * A function : pass the error to a function for handling. + */ + log: boolean | LoggingCallback; + } } + +export = errorHandler; diff --git a/escape-html/escape-html.d.ts b/escape-html/escape-html.d.ts index f3b57e005a..fc81a2179a 100644 --- a/escape-html/escape-html.d.ts +++ b/escape-html/escape-html.d.ts @@ -3,9 +3,8 @@ // Definitions by: Elisée MAURER // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "escape-html" { - function escapeHTML(text: string): string; - namespace escapeHTML {} - export = escapeHTML; -} +declare function escapeHTML(text: string): string; +declare namespace escapeHTML { } + +export = escapeHTML; diff --git a/escape-latex/escape-latex.d.ts b/escape-latex/escape-latex.d.ts index 5835bad0d9..3f29741aae 100644 --- a/escape-latex/escape-latex.d.ts +++ b/escape-latex/escape-latex.d.ts @@ -3,7 +3,6 @@ // Definitions by: Oliver Schneider // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'escape-latex' { - function lescape(texString: string): string; - export = lescape; -} \ No newline at end of file + +declare function lescape(texString: string): string; +export = lescape; diff --git a/escape-string-regexp/escape-string-regexp.d.ts b/escape-string-regexp/escape-string-regexp.d.ts index 6e04533087..4e3ac47458 100644 --- a/escape-string-regexp/escape-string-regexp.d.ts +++ b/escape-string-regexp/escape-string-regexp.d.ts @@ -3,10 +3,8 @@ // Definitions by: kruncher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "escape-string-regexp" { - function escapeStringRegexp(str: string): string; - export = escapeStringRegexp; +declare function escapeStringRegexp(str: string): string; -} +export = escapeStringRegexp; diff --git a/event-loop-lag/event-loop-lag.d.ts b/event-loop-lag/event-loop-lag.d.ts index fa1b1d8215..81ac388ee1 100644 --- a/event-loop-lag/event-loop-lag.d.ts +++ b/event-loop-lag/event-loop-lag.d.ts @@ -3,12 +3,11 @@ // Definitions by: Rogier Schouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "event-loop-lag" { - - /** - * Accepts a number of milliseconds representing how often to refresh the event loop lag measurement and returns a function you can call to receive the latest lag measurement in milliseconds. - */ - function lag(interval: number): () => number; - - export = lag; -} + + +/** + * Accepts a number of milliseconds representing how often to refresh the event loop lag measurement and returns a function you can call to receive the latest lag measurement in milliseconds. + */ +declare function lag(interval: number): () => number; + +export = lag; diff --git a/event-stream/event-stream.d.ts b/event-stream/event-stream.d.ts index 85d676d339..e53066e16f 100644 --- a/event-stream/event-stream.d.ts +++ b/event-stream/event-stream.d.ts @@ -5,138 +5,136 @@ /// -declare module 'event-stream' -{ - import * as stream from 'stream'; - /** - * Create a through stream from an asynchronous function - * - * @param asyncFunction - */ - export function map(asyncFunction: Function): stream.Stream; +import * as stream from 'stream'; - /** - * Same as map, but the callback is called synchronously. Based on es.through - * @param syncFunction - */ - export function mapSync(syncFunction: Function): stream.Stream; +/** + * Create a through stream from an asynchronous function + * + * @param asyncFunction + */ +declare export function map(asyncFunction: Function): stream.Stream; - /** - * Break up a stream and reassemble it so that each line is a chunk. matcher may be a String, or a RegExp - * - * @param matcher - */ - export function split(matcher: string | RegExp): stream.Stream; +/** + * Same as map, but the callback is called synchronously. Based on es.through + * @param syncFunction + */ +declare export function mapSync(syncFunction: Function): stream.Stream; - /** - * Create a through stream that emits separator between each chunk, just like Array#join - * - * @param separator - */ - export function join(separator: string): stream.Stream; +/** + * Break up a stream and reassemble it so that each line is a chunk. matcher may be a String, or a RegExp + * + * @param matcher + */ +declare export function split(matcher: string | RegExp): stream.Stream; - /** - * Merges streams into one and returns it. Incoming data will be emitted as soon it comes into - no ordering will be applied - * (for example: data1 data1 data2 data1 data2 - where data1 and data2 is data from two streams). - * Counts how many streams were passed to it and emits end only when all streams emitted end. - * - * @param stream - */ - export function concat(...stream: stream.Stream[]): stream.Stream; +/** + * Create a through stream that emits separator between each chunk, just like Array#join + * + * @param separator + */ +declare export function join(separator: string): stream.Stream; - /** - * Merges streams into one and returns it. Incoming data will be emitted as soon it comes into - no ordering will be applied - * (for example: data1 data1 data2 data1 data2 - where data1 and data2 is data from two streams). - * Counts how many streams were passed to it and emits end only when all streams emitted end. - * - * @param stream - */ - export function concat(streamArray:stream.Stream[]): stream.Stream; +/** + * Merges streams into one and returns it. Incoming data will be emitted as soon it comes into - no ordering will be applied + * (for example: data1 data1 data2 data1 data2 - where data1 and data2 is data from two streams). + * Counts how many streams were passed to it and emits end only when all streams emitted end. + * + * @param stream + */ +declare export function concat(...stream: stream.Stream[]): stream.Stream; - /** - * Merges streams into one and returns it. Incoming data will be emitted as soon it comes into - no ordering will be applied - * (for example: data1 data1 data2 data1 data2 - where data1 and data2 is data from two streams). - * Counts how many streams were passed to it and emits end only when all streams emitted end. - * - * @param stream - */ - export function merge(...stream: stream.Stream[]): stream.Stream; +/** + * Merges streams into one and returns it. Incoming data will be emitted as soon it comes into - no ordering will be applied + * (for example: data1 data1 data2 data1 data2 - where data1 and data2 is data from two streams). + * Counts how many streams were passed to it and emits end only when all streams emitted end. + * + * @param stream + */ +declare export function concat(streamArray: stream.Stream[]): stream.Stream; - /** - * Merges streams into one and returns it. Incoming data will be emitted as soon it comes into - no ordering will be applied - * (for example: data1 data1 data2 data1 data2 - where data1 and data2 is data from two streams). - * Counts how many streams were passed to it and emits end only when all streams emitted end. - * - * @param stream - */ - export function merge(streamArray: stream.Stream[]): stream.Stream; +/** + * Merges streams into one and returns it. Incoming data will be emitted as soon it comes into - no ordering will be applied + * (for example: data1 data1 data2 data1 data2 - where data1 and data2 is data from two streams). + * Counts how many streams were passed to it and emits end only when all streams emitted end. + * + * @param stream + */ +declare export function merge(...stream: stream.Stream[]): stream.Stream; - /** - * Replace all occurrences of from with to - * @param from - * @param to - */ - export function replace(from: string | RegExp, to: string | RegExp): stream.Stream; +/** + * Merges streams into one and returns it. Incoming data will be emitted as soon it comes into - no ordering will be applied + * (for example: data1 data1 data2 data1 data2 - where data1 and data2 is data from two streams). + * Counts how many streams were passed to it and emits end only when all streams emitted end. + * + * @param stream + */ +declare export function merge(streamArray: stream.Stream[]): stream.Stream; - /** - * Convenience function for parsing JSON chunks. For newline separated JSON, use with es.split. - * By default it logs parsing errors by console.error; for another behaviour, transforms created by es.parse({error: true}) - * will emit error events for exceptions thrown from JSON.parse, unmodified. - */ - export function parse(): any; +/** + * Replace all occurrences of from with to + * @param from + * @param to + */ +declare export function replace(from: string | RegExp, to: string | RegExp): stream.Stream; - /** - * convert javascript objects into lines of text. The text will have whitespace escaped and have a \n appended, so it will be compatible with es.parse - */ - export function stringify(): stream.Stream; +/** + * Convenience function for parsing JSON chunks. For newline separated JSON, use with es.split. + * By default it logs parsing errors by console.error; for another behaviour, transforms created by es.parse({error: true}) + * will emit error events for exceptions thrown from JSON.parse, unmodified. + */ +declare export function parse(): any; - /** - * create a readable stream (that respects pause) from an async function. - * - * @param asyncFunction - */ - export function readable(asyncFunction: Function): stream.Stream; +/** + * convert javascript objects into lines of text. The text will have whitespace escaped and have a \n appended, so it will be compatible with es.parse + */ +declare export function stringify(): stream.Stream; - /** - * Create a readable stream from an Array. - * - * @param array - */ - export function readArray(array: any[]): stream.Stream; +/** + * create a readable stream (that respects pause) from an async function. + * + * @param asyncFunction + */ +declare export function readable(asyncFunction: Function): stream.Stream; - /** - * create a writeable stream from a callback - * - * @param callback - */ - export function writeArray(callback: Function): stream.Stream; +/** + * Create a readable stream from an Array. + * + * @param array + */ +declare export function readArray(array: any[]): stream.Stream; - /** - * A stream that buffers all chunks when paused - */ - export function pause(): stream.Stream | void; +/** + * create a writeable stream from a callback + * + * @param callback + */ +declare export function writeArray(callback: Function): stream.Stream; - /** - * Takes a writable stream and a readable stream and makes them appear as a readable writable stream. - * - * @param writeStream - * @param readStream - */ - export function duplex(writeStream: stream.Writable, readStream: stream.Readable): stream.Stream; +/** + * A stream that buffers all chunks when paused + */ +declare export function pause(): stream.Stream | void; - /** - * Create a through stream from a child process - * - * @param child_process - */ - export function child(child_process: any): stream.Stream; +/** + * Takes a writable stream and a readable stream and makes them appear as a readable writable stream. + * + * @param writeStream + * @param readStream + */ +declare export function duplex(writeStream: stream.Writable, readStream: stream.Readable): stream.Stream; - /** - * waits for stream to emit 'end'. joins chunks of a stream into a single string or buffer. - * Takes an optional callback, which will be passed the complete string/buffer when it receives the 'end' event. - * - * @param callback - */ - export function wait(callback: Function): stream.Stream; -} \ No newline at end of file +/** + * Create a through stream from a child process + * + * @param child_process + */ +declare export function child(child_process: any): stream.Stream; + +/** + * waits for stream to emit 'end'. joins chunks of a stream into a single string or buffer. + * Takes an optional callback, which will be passed the complete string/buffer when it receives the 'end' event. + * + * @param callback + */ +declare export function wait(callback: Function): stream.Stream; diff --git a/evernote/evernote.d.ts b/evernote/evernote.d.ts index d8a2fe0ac4..8e4dafaeaa 100644 --- a/evernote/evernote.d.ts +++ b/evernote/evernote.d.ts @@ -5,6318 +5,6317 @@ /// -declare module "evernote" { - import { Thrift } from "thrift"; - namespace Evernote { - interface Callback { - (err: EDAMUserException|EDAMSystemException|EDAMNotFoundException, v: T): void - } - - interface ClientConfig { - consumerKey?: string - consumerSecret?: string - sandbox?: boolean - token?: string - serviceHost?: string - additionalHeaders?: { [k: string]: string } - secret?: string - } - - class Client { - static "new": (config: ClientConfig) => Client - constructor(config: ClientConfig); - getNoteStore(): NoteStoreClient; - getUserStore(): UserStoreClient; - } - - - /** - * Numeric codes indicating the type of error that occurred on the - * service. - *

- *
UNKNOWN
- *
No information available about the error
- *
BAD_DATA_FORMAT
- *
The format of the request data was incorrect
- *
PERMISSION_DENIED
- *
Not permitted to perform action
- *
INTERNAL_ERROR
- *
Unexpected problem with the service
- *
DATA_REQUIRED
- *
A required parameter/field was absent
- *
LIMIT_REACHED
- *
Operation denied due to data model limit
- *
QUOTA_REACHED
- *
Operation denied due to user storage limit
- *
INVALID_AUTH
- *
Username and/or password incorrect
- *
AUTH_EXPIRED
- *
Authentication token expired
- *
DATA_CONFLICT
- *
Change denied due to data model conflict
- *
ENML_VALIDATION
- *
Content of submitted note was malformed
- *
SHARD_UNAVAILABLE
- *
Service shard with account data is temporarily down
- *
LEN_TOO_SHORT
- *
Operation denied due to data model limit, where something such - * as a string length was too short
- *
LEN_TOO_LONG
- *
Operation denied due to data model limit, where something such - * as a string length was too long
- *
TOO_FEW
- *
Operation denied due to data model limit, where there were - * too few of something.
- *
TOO_MANY
- *
Operation denied due to data model limit, where there were - * too many of something.
- *
UNSUPPORTED_OPERATION
- *
Operation denied because it is currently unsupported.
- *
TAKEN_DOWN
- *
Operation denied because access to the corresponding object is - * prohibited in response to a take-down notice.
- *
RATE_LIMIT_REACHED
- *
Operation denied because the calling application has reached - * its hourly API call limit for this user.
- *
- */ - enum EDAMErrorCode { - 'UNKNOWN' = 1, - 'BAD_DATA_FORMAT' = 2, - 'PERMISSION_DENIED' = 3, - 'INTERNAL_ERROR' = 4, - 'DATA_REQUIRED' = 5, - 'LIMIT_REACHED' = 6, - 'QUOTA_REACHED' = 7, - 'INVALID_AUTH' = 8, - 'AUTH_EXPIRED' = 9, - 'DATA_CONFLICT' = 10, - 'ENML_VALIDATION' = 11, - 'SHARD_UNAVAILABLE' = 12, - 'LEN_TOO_SHORT' = 13, - 'LEN_TOO_LONG' = 14, - 'TOO_FEW' = 15, - 'TOO_MANY' = 16, - 'UNSUPPORTED_OPERATION' = 17, - 'TAKEN_DOWN' = 18, - 'RATE_LIMIT_REACHED' = 19, - } - - /** - * This exception is thrown by EDAM procedures when a call fails as a result of - * a problem that a caller may be able to resolve. For example, if the user - * attempts to add a note to their account which would exceed their storage - * quota, this type of exception may be thrown to indicate the source of the - * error so that they can choose an alternate action. - * - * This exception would not be used for internal system errors that do not - * reflect user actions, but rather reflect a problem within the service that - * the user cannot resolve. - * - * errorCode: The numeric code indicating the type of error that occurred. - * must be one of the values of EDAMErrorCode. - * - * parameter: If the error applied to a particular input parameter, this will - * indicate which parameter. - */ - class EDAMUserException extends Thrift.TException { - errorCode: EDAMErrorCode; - parameter: string; - - constructor(args?: { errorCode: EDAMErrorCode; parameter?: string; }); - } - - /** - * This exception is thrown by EDAM procedures when a call fails as a result of - * a problem in the service that could not be changed through caller action. - * - * errorCode: The numeric code indicating the type of error that occurred. - * must be one of the values of EDAMErrorCode. - * - * message: This may contain additional information about the error - * - * rateLimitDuration: Indicates the minimum number of seconds that an application should - * expect subsequent API calls for this user to fail. The application should not retry - * API requests for the user until at least this many seconds have passed. Present only - * when errorCode is RATE_LIMIT_REACHED, - */ - class EDAMSystemException extends Thrift.TException { - errorCode: EDAMErrorCode; - message: string; - rateLimitDuration: number; - - constructor(args?: { errorCode: EDAMErrorCode; message?: string; rateLimitDuration?: number; }); - } - - /** - * This exception is thrown by EDAM procedures when a caller asks to perform - * an operation on an object that does not exist. This may be thrown based on an invalid - * primary identifier (e.g. a bad GUID), or when the caller refers to an object - * by another unique identifier (e.g. a User's email address). - * - * identifier: A description of the object that was not found on the server. - * For example, "Note.notebookGuid" when a caller attempts to create a note in a - * notebook that does not exist in the user's account. - * - * key: The value passed from the client in the identifier, which was not - * found. For example, the GUID that was not found. - */ - class EDAMNotFoundException extends Thrift.TException { - identifier: string; - key: string; - - constructor(args?: { identifier?: string; key?: string; }); - } - /** - * Minimum length of any string-based attribute, in Unicode chars - */ - var EDAM_ATTRIBUTE_LEN_MIN: number; - - /** - * Maximum length of any string-based attribute, in Unicode chars - */ - var EDAM_ATTRIBUTE_LEN_MAX: number; - - /** - * Any string-based attribute must match the provided regular expression. - * This excludes all Unicode line endings and control characters. - */ - var EDAM_ATTRIBUTE_REGEX: string; - - /** - * The maximum number of values that can be stored in a list-based attribute - * (e.g. see UserAttributes.recentMailedAddresses) - */ - var EDAM_ATTRIBUTE_LIST_MAX: number; - - /** - * The maximum number of entries that can be stored in a map-based attribute - * such as applicationData fields in Resources and Notes. - */ - var EDAM_ATTRIBUTE_MAP_MAX: number; - - /** - * The minimum length of a GUID generated by the Evernote service - */ - var EDAM_GUID_LEN_MIN: number; - - /** - * The maximum length of a GUID generated by the Evernote service - */ - var EDAM_GUID_LEN_MAX: number; - - /** - * GUIDs generated by the Evernote service will match the provided pattern - */ - var EDAM_GUID_REGEX: string; - - /** - * The minimum length of any email address - */ - var EDAM_EMAIL_LEN_MIN: number; - - /** - * The maximum length of any email address - */ - var EDAM_EMAIL_LEN_MAX: number; - - /** - * A regular expression that matches the part of an email address before - * the '@' symbol. - */ - var EDAM_EMAIL_LOCAL_REGEX: string; - - /** - * A regular expression that matches the part of an email address after - * the '@' symbol. - */ - var EDAM_EMAIL_DOMAIN_REGEX: string; - - /** - * A regular expression that must match any email address given to Evernote. - * Email addresses must comply with RFC 2821 and 2822. - */ - var EDAM_EMAIL_REGEX: string; - - /** - * A regular expression that must match any VAT ID given to Evernote. - * ref http://en.wikipedia.org/wiki/VAT_identification_number - * ref http://my.safaribooksonline.com/book/programming/regular-expressions/9780596802837/4dot-validation-and-formatting/id2995136 - */ - var EDAM_VAT_REGEX: string; - - /** - * The minimum length of a timezone specification string - */ - var EDAM_TIMEZONE_LEN_MIN: number; - - /** - * The maximum length of a timezone specification string - */ - var EDAM_TIMEZONE_LEN_MAX: number; - - /** - * Any timezone string given to Evernote must match the provided pattern. - * This permits either a locale-based standard timezone or a GMT offset. - * E.g.:
    - *
  • America/Los_Angeles
  • - *
  • GMT+08:00
  • - *
- */ - var EDAM_TIMEZONE_REGEX: string; - - /** - * The minimum length of any MIME type string given to Evernote - */ - var EDAM_MIME_LEN_MIN: number; - - /** - * The maximum length of any MIME type string given to Evernote - */ - var EDAM_MIME_LEN_MAX: number; - - /** - * Any MIME type string given to Evernote must match the provided pattern. - * E.g.: image/gif - */ - var EDAM_MIME_REGEX: string; - - /** - * Canonical MIME type string for GIF image resources - */ - var EDAM_MIME_TYPE_GIF: string; - - /** - * Canonical MIME type string for JPEG image resources - */ - var EDAM_MIME_TYPE_JPEG: string; - - /** - * Canonical MIME type string for PNG image resources - */ - var EDAM_MIME_TYPE_PNG: string; - - /** - * Canonical MIME type string for WAV audio resources - */ - var EDAM_MIME_TYPE_WAV: string; - - /** - * Canonical MIME type string for MP3 audio resources - */ - var EDAM_MIME_TYPE_MP3: string; - - /** - * Canonical MIME type string for AMR audio resources - */ - var EDAM_MIME_TYPE_AMR: string; - - /** - * Canonical MIME type string for AAC audio resources - */ - var EDAM_MIME_TYPE_AAC: string; - - /** - * Canonical MIME type string for MP4 audio resources - */ - var EDAM_MIME_TYPE_M4A: string; - - /** - * Canonical MIME type string for MP4 video resources - */ - var EDAM_MIME_TYPE_MP4_VIDEO: string; - - /** - * Canonical MIME type string for Evernote Ink resources - */ - var EDAM_MIME_TYPE_INK: string; - - /** - * Canonical MIME type string for PDF resources - */ - var EDAM_MIME_TYPE_PDF: string; - - /** - * MIME type used for attachments of an unspecified type - */ - var EDAM_MIME_TYPE_DEFAULT: string; - - /** - * The set of resource MIME types that are expected to be handled - * correctly by all of the major Evernote client applications. - */ - var EDAM_MIME_TYPES: string[]; - - /** - * The set of MIME types that Evernote will parse and index for - * searching. With exception of images, and PDFs, which are - * handled in a different way. - */ - var EDAM_INDEXABLE_RESOURCE_MIME_TYPES: string[]; - - /** - * The minimum length of a user search query string in Unicode chars - */ - var EDAM_SEARCH_QUERY_LEN_MIN: number; - - /** - * The maximum length of a user search query string in Unicode chars - */ - var EDAM_SEARCH_QUERY_LEN_MAX: number; - - /** - * Search queries must match the provided pattern. This is used for - * both ad-hoc queries and SavedSearch.query fields. - * This excludes all control characters and line/paragraph separators. - */ - var EDAM_SEARCH_QUERY_REGEX: string; - - /** - * The exact length of a MD5 hash checksum, in binary bytes. - * This is the exact length that must be matched for any binary hash - * value. - */ - var EDAM_HASH_LEN: number; - - /** - * The minimum length of an Evernote username - */ - var EDAM_USER_USERNAME_LEN_MIN: number; - - /** - * The maximum length of an Evernote username - */ - var EDAM_USER_USERNAME_LEN_MAX: number; - - /** - * Any Evernote User.username field must match this pattern. This - * restricts usernames to a format that could permit use as a domain - * name component. E.g. "username.whatever.evernote.com" - */ - var EDAM_USER_USERNAME_REGEX: string; - - /** - * Minimum length of the User.name field - */ - var EDAM_USER_NAME_LEN_MIN: number; - - /** - * Maximum length of the User.name field - */ - var EDAM_USER_NAME_LEN_MAX: number; - - /** - * The User.name field must match this pattern, which excludes line - * endings and control characters. - */ - var EDAM_USER_NAME_REGEX: string; - - /** - * The minimum length of a Tag.name, in Unicode characters - */ - var EDAM_TAG_NAME_LEN_MIN: number; - - /** - * The maximum length of a Tag.name, in Unicode characters - */ - var EDAM_TAG_NAME_LEN_MAX: number; - - /** - * All Tag.name fields must match this pattern. - * This excludes control chars, commas or line/paragraph separators. - * The string may not begin or end with whitespace. - */ - var EDAM_TAG_NAME_REGEX: string; - - /** - * The minimum length of a Note.title, in Unicode characters - */ - var EDAM_NOTE_TITLE_LEN_MIN: number; - - /** - * The maximum length of a Note.title, in Unicode characters - */ - var EDAM_NOTE_TITLE_LEN_MAX: number; - - /** - * All Note.title fields must match this pattern. - * This excludes control chars or line/paragraph separators. - * The string may not begin or end with whitespace. - */ - var EDAM_NOTE_TITLE_REGEX: string; - - /** - * Minimum length of a Note.content field. - * Note.content fields must comply with the ENML DTD. - */ - var EDAM_NOTE_CONTENT_LEN_MIN: number; - - /** - * Maximum length of a Note.content field - * Note.content fields must comply with the ENML DTD. - */ - var EDAM_NOTE_CONTENT_LEN_MAX: number; - - /** - * Minimum length of an application name, which is the key in an - * applicationData LazyMap found in entities such as Resources and - * Notes. - */ - var EDAM_APPLICATIONDATA_NAME_LEN_MIN: number; - - /** - * Maximum length of an application name, which is the key in an - * applicationData LazyMap found in entities such as Resources and - * Notes. - */ - var EDAM_APPLICATIONDATA_NAME_LEN_MAX: number; - - /** - * Minimum length of an applicationData value in a LazyMap, found - * in entities such as Resources and Notes. - */ - var EDAM_APPLICATIONDATA_VALUE_LEN_MIN: number; - - /** - * Maximum length of an applicationData value in a LazyMap, found - * in entities such as Resources and Notes. Note, however, that - * the sum of the size of hte key and value is constrained by - * EDAM_APPLICATIONDATA_ENTRY_LEN_MAX, so the maximum length, in - * practice, depends upon the key value being used. - */ - var EDAM_APPLICATIONDATA_VALUE_LEN_MAX: number; - - /** - * The total length of an entry in an applicationData LazyMap, which - * is the sum of the length of the key and the value for the entry. - */ - var EDAM_APPLICATIONDATA_ENTRY_LEN_MAX: number; - - /** - * An application name must match this regex. An application - * name is the key portion of an entry in an applicationData - * map as found in entities such as Resources and Notes. - * Note that even if both the name and value regexes match, - * it is still necessary to check the sum of the lengths - * against EDAM_APPLICATIONDATA_ENTRY_LEN_MAX. - */ - var EDAM_APPLICATIONDATA_NAME_REGEX: string; - - /** - * An applicationData map value must match this regex. - * Note that even if both the name and value regexes match, - * it is still necessary to check the sum of the lengths - * against EDAM_APPLICATIONDATA_ENTRY_LEN_MAX. - */ - var EDAM_APPLICATIONDATA_VALUE_REGEX: string; - - /** - * The minimum length of a Notebook.name, in Unicode characters - */ - var EDAM_NOTEBOOK_NAME_LEN_MIN: number; - - /** - * The maximum length of a Notebook.name, in Unicode characters - */ - var EDAM_NOTEBOOK_NAME_LEN_MAX: number; - - /** - * All Notebook.name fields must match this pattern. - * This excludes control chars or line/paragraph separators. - * The string may not begin or end with whitespace. - */ - var EDAM_NOTEBOOK_NAME_REGEX: string; - - /** - * The minimum length of a Notebook.stack, in Unicode characters - */ - var EDAM_NOTEBOOK_STACK_LEN_MIN: number; - - /** - * The maximum length of a Notebook.stack, in Unicode characters - */ - var EDAM_NOTEBOOK_STACK_LEN_MAX: number; - - /** - * All Notebook.stack fields must match this pattern. - * This excludes control chars or line/paragraph separators. - * The string may not begin or end with whitespace. - */ - var EDAM_NOTEBOOK_STACK_REGEX: string; - - /** - * The minimum length of a public notebook URI component - */ - var EDAM_PUBLISHING_URI_LEN_MIN: number; - - /** - * The maximum length of a public notebook URI component - */ - var EDAM_PUBLISHING_URI_LEN_MAX: number; - - /** - * A public notebook URI component must match the provided pattern - */ - var EDAM_PUBLISHING_URI_REGEX: string; - - /** - * The set of strings that may not be used as a publishing URI - */ - var EDAM_PUBLISHING_URI_PROHIBITED: string[]; - - /** - * The minimum length of a Publishing.publicDescription field. - */ - var EDAM_PUBLISHING_DESCRIPTION_LEN_MIN: number; - - /** - * The maximum length of a Publishing.publicDescription field. - */ - var EDAM_PUBLISHING_DESCRIPTION_LEN_MAX: number; - - /** - * Any public notebook's Publishing.publicDescription field must match - * this pattern. - * No control chars or line/paragraph separators, and can't start or - * end with whitespace. - */ - var EDAM_PUBLISHING_DESCRIPTION_REGEX: string; - - /** - * The minimum length of a SavedSearch.name field - */ - var EDAM_SAVED_SEARCH_NAME_LEN_MIN: number; - - /** - * The maximum length of a SavedSearch.name field - */ - var EDAM_SAVED_SEARCH_NAME_LEN_MAX: number; - - /** - * SavedSearch.name fields must match this pattern. - * No control chars or line/paragraph separators, and can't start or - * end with whitespace. - */ - var EDAM_SAVED_SEARCH_NAME_REGEX: string; - - /** - * The minimum length of an Evernote user password - */ - var EDAM_USER_PASSWORD_LEN_MIN: number; - - /** - * The maximum length of an Evernote user password - */ - var EDAM_USER_PASSWORD_LEN_MAX: number; - - /** - * Evernote user passwords must match this regular expression - */ - var EDAM_USER_PASSWORD_REGEX: string; - - /** - * The maximum length of an Evernote Business URI - */ - var EDAM_BUSINESS_URI_LEN_MAX: number; - - /** - * The maximum number of Tags per Note - */ - var EDAM_NOTE_TAGS_MAX: number; - - /** - * The maximum number of Resources per Note - */ - var EDAM_NOTE_RESOURCES_MAX: number; - - /** - * Maximum number of Tags per account - */ - var EDAM_USER_TAGS_MAX: number; - - /** - * Maximum number of Tags per business account. - */ - var EDAM_BUSINESS_TAGS_MAX: number; - - /** - * Maximum number of SavedSearches per account - */ - var EDAM_USER_SAVED_SEARCHES_MAX: number; - - /** - * Maximum number of Notes per user - */ - var EDAM_USER_NOTES_MAX: number; - - /** - * Maximum number of Notes per business account - */ - var EDAM_BUSINESS_NOTES_MAX: number; - - /** - * Maximum number of Notebooks per user - */ - var EDAM_USER_NOTEBOOKS_MAX: number; - - /** - * Maximum number of Notebooks in a business account - */ - var EDAM_BUSINESS_NOTEBOOKS_MAX: number; - - /** - * Maximum number of recent email addresses that are maintained - * (see UserAttributes.recentMailedAddresses) - */ - var EDAM_USER_RECENT_MAILED_ADDRESSES_MAX: number; - - /** - * The number of emails of any type that can be sent by a user with a Free - * account from the service per day. If an email is sent to two different - * recipients, this counts as two emails. - */ - var EDAM_USER_MAIL_LIMIT_DAILY_FREE: number; - - /** - * The number of emails of any type that can be sent by a user with a Premium - * account from the service per day. If an email is sent to two different - * recipients, this counts as two emails. - */ - var EDAM_USER_MAIL_LIMIT_DAILY_PREMIUM: number; - - /** - * The number of bytes of new data that may be uploaded to a Free user's - * account each month. - */ - var EDAM_USER_UPLOAD_LIMIT_FREE: number; - - /** - * The number of bytes of new data that may be uploaded to a Premium user's - * account each month. - */ - var EDAM_USER_UPLOAD_LIMIT_PREMIUM: number; - - /** - * The number of bytes of new data that may be uploaded to a Business user's - * personal account each month. Note that content uploaded into the Business - * notebooks by the user does not count against this limit. - */ - var EDAM_USER_UPLOAD_LIMIT_BUSINESS: number; - - /** - * Maximum total size of a Note that can be added to a Free account. - * The size of a note is calculated as: - * ENML content length (in Unicode characters) plus the sum of all resource - * sizes (in bytes). - */ - var EDAM_NOTE_SIZE_MAX_FREE: number; - - /** - * Maximum total size of a Note that can be added to a Premium account. - * The size of a note is calculated as: - * ENML content length (in Unicode characters) plus the sum of all resource - * sizes (in bytes). - */ - var EDAM_NOTE_SIZE_MAX_PREMIUM: number; - - /** - * Maximum size of a resource, in bytes, for Free accounts - */ - var EDAM_RESOURCE_SIZE_MAX_FREE: number; - - /** - * Maximum size of a resource, in bytes, for Premium accounts - */ - var EDAM_RESOURCE_SIZE_MAX_PREMIUM: number; - - /** - * Maximum number of linked notebooks per account, for a free - * account. - */ - var EDAM_USER_LINKED_NOTEBOOK_MAX: number; - - /** - * Maximum number of linked notebooks per account, for a premium - * account. Users who are part of an active business are also - * covered under "premium". - */ - var EDAM_USER_LINKED_NOTEBOOK_MAX_PREMIUM: number; - - /** - * Maximum number of shared notebooks per notebook - */ - var EDAM_NOTEBOOK_SHARED_NOTEBOOK_MAX: number; - - /** - * The minimum length of the content class attribute of a note. - */ - var EDAM_NOTE_CONTENT_CLASS_LEN_MIN: number; - - /** - * The maximum length of the content class attribute of a note. - */ - var EDAM_NOTE_CONTENT_CLASS_LEN_MAX: number; - - /** - * The regular expression that the content class of a note must match - * to be valid. - */ - var EDAM_NOTE_CONTENT_CLASS_REGEX: string; - - /** - * The content class prefix used for all notes created by Evernote Hello. - * This prefix can be used to assemble individual content class strings, - * or can be used to create a wildcard search to get all notes created by - * Hello. When performing a wildcard search via filtered sync chunks or - * search strings, the * character must be appended to this constant. - */ - var EDAM_HELLO_APP_CONTENT_CLASS_PREFIX: string; - - /** - * The content class prefix used for all notes created by Evernote Food. - * This prefix can be used to assemble individual content class strings, - * or can be used to create a wildcard search to get all notes created by - * Food. When performing a wildcard search via filtered sync chunks or - * search strings, the * character must be appended to this constant. - */ - var EDAM_FOOD_APP_CONTENT_CLASS_PREFIX: string; - - /** - * The content class prefix used for structured notes created by Evernote - * Hello that represents an encounter with a person. When performing a - * wildcard search via filtered sync chunks or search strings, the * - * character must be appended to this constant. - */ - var EDAM_CONTENT_CLASS_HELLO_ENCOUNTER: string; - - /** - * The content class prefix used for structured notes created by Evernote - * Hello that represents the user's profile. When performing a - * wildcard search via filtered sync chunks or search strings, the * - * character must be appended to this constant. - */ - var EDAM_CONTENT_CLASS_HELLO_PROFILE: string; - - /** - * The content class prefix used for structured notes created by - * Evernote Food that captures the experience of a particular meal. - * When performing a wildcard search via filtered sync chunks or search - * strings, the * character must be appended to this constant. - */ - var EDAM_CONTENT_CLASS_FOOD_MEAL: string; - - /** - * The content class prefix used for structured notes created by Evernote - * Skitch. When performing a wildcard search via filtered sync chunks - * or search strings, the * character must be appended to this constant. - */ - var EDAM_CONTENT_CLASS_SKITCH_PREFIX: string; - - /** - * The content class value used for structured image notes created by Evernote - * Skitch. - */ - var EDAM_CONTENT_CLASS_SKITCH: string; - - /** - * The content class value used for structured PDF notes created by Evernote - * Skitch. - */ - var EDAM_CONTENT_CLASS_SKITCH_PDF: string; - - /** - * The content class prefix used for structured notes created by Evernote - * Penultimate. When performing a wildcard search via filtered sync chunks - * or search strings, the * character must be appended to this constant. - */ - var EDAM_CONTENT_CLASS_PENULTIMATE_PREFIX: string; - - /** - * The content class value used for structured notes created by Evernote - * Penultimate that represents a Penultimate notebook. - */ - var EDAM_CONTENT_CLASS_PENULTIMATE_NOTEBOOK: string; - - /** - * The minimum length of the plain text in a findRelated query, assuming that - * plaintext is being provided. - */ - var EDAM_RELATED_PLAINTEXT_LEN_MIN: number; - - /** - * The maximum length of the plain text in a findRelated query, assuming that - * plaintext is being provided. - */ - var EDAM_RELATED_PLAINTEXT_LEN_MAX: number; - - /** - * The maximum number of notes that will be returned from a findRelated() - * query. - */ - var EDAM_RELATED_MAX_NOTES: number; - - /** - * The maximum number of notebooks that will be returned from a findRelated() - * query. - */ - var EDAM_RELATED_MAX_NOTEBOOKS: number; - - /** - * The maximum number of tags that will be returned from a findRelated() query. - */ - var EDAM_RELATED_MAX_TAGS: number; - - /** - * The minimum length, in Unicode characters, of a description for a business - * notebook. - */ - var EDAM_BUSINESS_NOTEBOOK_DESCRIPTION_LEN_MIN: number; - - /** - * The maximum length, in Unicode characters, of a description for a business - * notebook. - */ - var EDAM_BUSINESS_NOTEBOOK_DESCRIPTION_LEN_MAX: number; - - /** - * All business notebook descriptions must match this pattern. - * This excludes control chars or line/paragraph separators. - * The string may not begin or end with whitespace. - */ - var EDAM_BUSINESS_NOTEBOOK_DESCRIPTION_REGEX: string; - - /** - * The maximum length of a business phone number. - */ - var EDAM_BUSINESS_PHONE_NUMBER_LEN_MAX: number; - - /** - * Minimum length of a preference name - */ - var EDAM_PREFERENCE_NAME_LEN_MIN: number; - - /** - * Maximum length of a preference name - */ - var EDAM_PREFERENCE_NAME_LEN_MAX: number; - - /** - * Minimum length of a preference value - */ - var EDAM_PREFERENCE_VALUE_LEN_MIN: number; - - /** - * Maximum length of a preference value - */ - var EDAM_PREFERENCE_VALUE_LEN_MAX: number; - - /** - * Maximum number of name/value pairs allowed - */ - var EDAM_MAX_PREFERENCES: number; - - /** - * Maximum number of values per preference name - */ - var EDAM_MAX_VALUES_PER_PREFERENCE: number; - - /** - * A preference name must match this regex. - */ - var EDAM_PREFERENCE_NAME_REGEX: string; - - /** - * A preference value must match this regex. - */ - var EDAM_PREFERENCE_VALUE_REGEX: string; - - /** - * The name of the preferences entry that contains shortcuts. - */ - var EDAM_PREFERENCE_SHORTCUTS: string; - - /** - * The maximum number of shortcuts that a user may have. - */ - var EDAM_PREFERENCE_SHORTCUTS_MAX_VALUES: number; - - /** - * Maximum length of the device identifier string associated with long sessions. - */ - var EDAM_DEVICE_ID_LEN_MAX: number; - - /** - * Regular expression for device identifier strings associated with long sessions. - */ - var EDAM_DEVICE_ID_REGEX: string; - - /** - * Maximum length of the device description string associated with long sessions. - */ - var EDAM_DEVICE_DESCRIPTION_LEN_MAX: number; - - /** - * Regular expression for device description strings associated with long sessions. - */ - var EDAM_DEVICE_DESCRIPTION_REGEX: string; - - /** - * Maximum number of search suggestions that can be returned - */ - var EDAM_SEARCH_SUGGESTIONS_MAX: number; - - /** - * Maximum length of the search suggestion prefix - */ - var EDAM_SEARCH_SUGGESTIONS_PREFIX_LEN_MAX: number; - - /** - * Minimum length of the search suggestion prefix - */ - var EDAM_SEARCH_SUGGESTIONS_PREFIX_LEN_MIN: number; - class NoteStoreClient { - seqid: number; - - /** - * Asks the NoteStore to provide information about the status of the user - * account corresponding to the provided authentication token. - */ - getSyncState(cb: Callback): void; - - /** - * Asks the NoteStore to provide information about the status of the user - * account corresponding to the provided authentication token. - * This version of 'getSyncState' allows the client to upload coarse- - * grained usage metrics to the service. - * - * @param clientMetrics see the documentation of the ClientUsageMetrics - * structure for an explanation of the fields that clients can pass to - * the service. - */ - getSyncStateWithMetrics(clientMetrics: ClientUsageMetrics, cb: Callback): void; - - /** - * Asks the NoteStore to provide the state of the account in order of - * last modification. This request retrieves one block of the server's - * state so that a client can make several small requests against a large - * account rather than getting the entire state in one big message. - * This call gives fine-grained control of the data that will - * be received by a client by omitting data elements that a client doesn't - * need. This may reduce network traffic and sync times. - * - * @param afterUSN - * The client can pass this value to ask only for objects that - * have been updated after a certain point. This allows the client to - * receive updates after its last checkpoint rather than doing a full - * synchronization on every pass. The default value of "0" indicates - * that the client wants to get objects from the start of the account. - * - * @param maxEntries - * The maximum number of modified objects that should be - * returned in the result SyncChunk. This can be used to limit the size - * of each individual message to be friendly for network transfer. - * - * @param filter - * The caller must set some of the flags in this structure to specify which - * data types should be returned during the synchronization. See - * the SyncChunkFilter structure for information on each flag. - * - * @throws EDAMUserException
    - *
  • BAD_DATA_FORMAT "afterUSN" - if negative - *
  • - *
  • BAD_DATA_FORMAT "maxEntries" - if less than 1 - *
  • - *
- */ - getFilteredSyncChunk(afterUSN: number, maxEntries: number, filter: SyncChunkFilter, cb: Callback): void; - - /** - * Asks the NoteStore to provide information about the status of a linked - * notebook that has been shared with the caller, or that is public to the - * world. - * This will return a result that is similar to getSyncState, but may omit - * SyncState.uploaded if the caller doesn't have permission to write to - * the linked notebook. - * - * This function must be called on the shard that owns the referenced - * notebook. (I.e. the shardId in /shard/shardId/edam/note must be the - * same as LinkedNotebook.shardId.) - * - * @param authenticationToken - * This should be an authenticationToken for the guest who has received - * the invitation to the share. (I.e. this should not be the result of - * NoteStore.authenticateToSharedNotebook) - * - * @param linkedNotebook - * This structure should contain identifying information and permissions - * to access the notebook in question. - */ - getLinkedNotebookSyncState(linkedNotebook: LinkedNotebook, cb: Callback): void; - - /** - * Asks the NoteStore to provide information about the contents of a linked - * notebook that has been shared with the caller, or that is public to the - * world. - * This will return a result that is similar to getSyncChunk, but will only - * contain entries that are visible to the caller. I.e. only that particular - * Notebook will be visible, along with its Notes, and Tags on those Notes. - * - * This function must be called on the shard that owns the referenced - * notebook. (I.e. the shardId in /shard/shardId/edam/note must be the - * same as LinkedNotebook.shardId.) - * - * @param authenticationToken - * This should be an authenticationToken for the guest who has received - * the invitation to the share. (I.e. this should not be the result of - * NoteStore.authenticateToSharedNotebook) - * - * @param linkedNotebook - * This structure should contain identifying information and permissions - * to access the notebook in question. This must contain the valid fields - * for either a shared notebook (e.g. shareKey) - * or a public notebook (e.g. username, uri) - * - * @param afterUSN - * The client can pass this value to ask only for objects that - * have been updated after a certain point. This allows the client to - * receive updates after its last checkpoint rather than doing a full - * synchronization on every pass. The default value of "0" indicates - * that the client wants to get objects from the start of the account. - * - * @param maxEntries - * The maximum number of modified objects that should be - * returned in the result SyncChunk. This can be used to limit the size - * of each individual message to be friendly for network transfer. - * Applications should not request more than 256 objects at a time, - * and must handle the case where the service returns less than the - * requested number of objects in a given request even though more - * objects are available on the service. - * - * @param fullSyncOnly - * If true, then the client only wants initial data for a full sync. - * In this case, the service will not return any expunged objects, - * and will not return any Resources, since these are also provided - * in their corresponding Notes. - * - * @throws EDAMUserException
    - *
  • BAD_DATA_FORMAT "afterUSN" - if negative - *
  • - *
  • BAD_DATA_FORMAT "maxEntries" - if less than 1 - *
  • - *
- * - * @throws EDAMNotFoundException
    - *
  • "LinkedNotebook" - if the provided information doesn't match any - * valid notebook - *
  • - *
  • "LinkedNotebook.uri" - if the provided public URI doesn't match any - * valid notebook - *
  • - *
  • "SharedNotebook.id" - if the provided information indicates a - * shared notebook that no longer exists - *
  • - *
- */ - getLinkedNotebookSyncChunk(linkedNotebook: LinkedNotebook, afterUSN: number, maxEntries: number, fullSyncOnly: boolean, cb: Callback): void; - - /** - * Returns a list of all of the notebooks in the account. - */ - listNotebooks(cb: Callback): void; - - /** - * Returns the current state of the notebook with the provided GUID. - * The notebook may be active or deleted (but not expunged). - * - * @param guid - * The GUID of the notebook to be retrieved. - * - * @throws EDAMUserException
    - *
  • BAD_DATA_FORMAT "Notebook.guid" - if the parameter is missing - *
  • - *
  • PERMISSION_DENIED "Notebook" - private notebook, user doesn't own - *
  • - *
- * - * @throws EDAMNotFoundException
    - *
  • "Notebook.guid" - tag not found, by GUID - *
  • - *
- */ - getNotebook(guid: string, cb: Callback): void; - - /** - * Returns the notebook that should be used to store new notes in the - * user's account when no other notebooks are specified. - */ - getDefaultNotebook(cb: Callback): void; - - /** - * Asks the service to make a notebook with the provided name. - * - * @param notebook - * The desired fields for the notebook must be provided on this - * object. The name of the notebook must be set, and either the 'active' - * or 'defaultNotebook' fields may be set by the client at creation. - * If a notebook exists in the account with the same name (via - * case-insensitive compare), this will throw an EDAMUserException. - * - * @return - * The newly created Notebook. The server-side GUID will be - * saved in this object's 'guid' field. - * - * @throws EDAMUserException
    - *
  • BAD_DATA_FORMAT "Notebook.name" - invalid length or pattern - *
  • - *
  • BAD_DATA_FORMAT "Notebook.stack" - invalid length or pattern - *
  • - *
  • BAD_DATA_FORMAT "Publishing.uri" - if publishing set but bad uri - *
  • - *
  • BAD_DATA_FORMAT "Publishing.publicDescription" - if too long - *
  • - *
  • DATA_CONFLICT "Notebook.name" - name already in use - *
  • - *
  • DATA_CONFLICT "Publishing.uri" - if URI already in use - *
  • - *
  • DATA_REQUIRED "Publishing.uri" - if publishing set but uri missing - *
  • - *
  • LIMIT_REACHED "Notebook" - at max number of notebooks - *
  • - *
- */ - createNotebook(notebook: Notebook, cb: Callback): void; - - /** - * Submits notebook changes to the service. The provided data must include - * the notebook's guid field for identification. - * - * @param notebook - * The notebook object containing the requested changes. - * - * @return - * The Update Sequence Number for this change within the account. - * - * @throws EDAMUserException
    - *
  • BAD_DATA_FORMAT "Notebook.name" - invalid length or pattern - *
  • - *
  • BAD_DATA_FORMAT "Notebook.stack" - invalid length or pattern - *
  • - *
  • BAD_DATA_FORMAT "Publishing.uri" - if publishing set but bad uri - *
  • - *
  • BAD_DATA_FORMAT "Publishing.publicDescription" - if too long - *
  • - *
  • DATA_CONFLICT "Notebook.name" - name already in use - *
  • - *
  • DATA_CONFLICT "Publishing.uri" - if URI already in use - *
  • - *
  • DATA_REQUIRED "Publishing.uri" - if publishing set but uri missing - *
  • - *
- * - * @throws EDAMNotFoundException
    - *
  • "Notebook.guid" - not found, by GUID - *
  • - *
- */ - updateNotebook(notebook: Notebook, cb: Callback): void; - - /** - * Permanently removes the notebook from the user's account. - * After this action, the notebook is no longer available for undeletion, etc. - * If the notebook contains any Notes, they will be moved to the current - * default notebook and moved into the trash (i.e. Note.active=false). - *

- * NOTE: This function is generally not available to third party applications. - * Calls will result in an EDAMUserException with the error code - * PERMISSION_DENIED. - * - * @param guid - * The GUID of the notebook to delete. - * - * @return - * The Update Sequence Number for this change within the account. - * - * @throws EDAMUserException

    - *
  • BAD_DATA_FORMAT "Notebook.guid" - if the parameter is missing - *
  • - *
  • LIMIT_REACHED "Notebook" - trying to expunge the last Notebook - *
  • - *
  • PERMISSION_DENIED "Notebook" - private notebook, user doesn't own - *
  • - *
- */ - expungeNotebook(guid: string, cb: Callback): void; - - /** - * Returns a list of the tags in the account. Evernote does not support - * the undeletion of tags, so this will only include active tags. - */ - listTags(cb: Callback): void; - - /** - * Returns a list of the tags that are applied to at least one note within - * the provided notebook. If the notebook is public, the authenticationToken - * may be ignored. - * - * @param notebookGuid - * the GUID of the notebook to use to find tags - * - * @throws EDAMNotFoundException
    - *
  • "Notebook.guid" - notebook not found by GUID - *
  • - *
- */ - listTagsByNotebook(notebookGuid: string, cb: Callback): void; - - /** - * Returns the current state of the Tag with the provided GUID. - * - * @param guid - * The GUID of the tag to be retrieved. - * - * @throws EDAMUserException
    - *
  • BAD_DATA_FORMAT "Tag.guid" - if the parameter is missing - *
  • - *
  • PERMISSION_DENIED "Tag" - private Tag, user doesn't own - *
  • - *
- * - * @throws EDAMNotFoundException
    - *
  • "Tag.guid" - tag not found, by GUID - *
  • - *
- */ - getTag(guid: string, cb: Callback): void; - - /** - * Asks the service to make a tag with a set of information. - * - * @param tag - * The desired list of fields for the tag are specified in this - * object. The caller must specify the tag name, and may provide - * the parentGUID. - * - * @return - * The newly created Tag. The server-side GUID will be - * saved in this object. - * - * @throws EDAMUserException
    - *
  • BAD_DATA_FORMAT "Tag.name" - invalid length or pattern - *
  • - *
  • BAD_DATA_FORMAT "Tag.parentGuid" - malformed GUID - *
  • - *
  • DATA_CONFLICT "Tag.name" - name already in use - *
  • - *
  • LIMIT_REACHED "Tag" - at max number of tags - *
  • - *
- * - * @throws EDAMNotFoundException
    - *
  • "Tag.parentGuid" - not found, by GUID - *
  • - *
- */ - createTag(tag: Tag, cb: Callback): void; - - /** - * Submits tag changes to the service. The provided data must include - * the tag's guid field for identification. The service will apply - * updates to the following tag fields: name, parentGuid - * - * @param tag - * The tag object containing the requested changes. - * - * @return - * The Update Sequence Number for this change within the account. - * - * @throws EDAMUserException
    - *
  • BAD_DATA_FORMAT "Tag.name" - invalid length or pattern - *
  • - *
  • BAD_DATA_FORMAT "Tag.parentGuid" - malformed GUID - *
  • - *
  • DATA_CONFLICT "Tag.name" - name already in use - *
  • - *
  • DATA_CONFLICT "Tag.parentGuid" - can't set parent: circular - *
  • - *
  • PERMISSION_DENIED "Tag" - user doesn't own tag - *
  • - *
- * - * @throws EDAMNotFoundException
    - *
  • "Tag.guid" - tag not found, by GUID - *
  • - *
  • "Tag.parentGuid" - parent not found, by GUID - *
  • - *
- */ - updateTag(tag: Tag, cb: Callback): void; - - /** - * Removes the provided tag from every note that is currently tagged with - * this tag. If this operation is successful, the tag will still be in - * the account, but it will not be tagged on any notes. - * - * This function is not indended for use by full synchronizing clients, since - * it does not provide enough result information to the client to reconcile - * the local state without performing a follow-up sync from the service. This - * is intended for "thin clients" that need to efficiently support this as - * a UI operation. - * - * @param guid - * The GUID of the tag to remove from all notes. - * - * @throws EDAMUserException
    - *
  • BAD_DATA_FORMAT "Tag.guid" - if the guid parameter is missing - *
  • - *
  • PERMISSION_DENIED "Tag" - user doesn't own tag - *
  • - *
- * - * @throws EDAMNotFoundException
    - *
  • "Tag.guid" - tag not found, by GUID - *
  • - *
- */ - untagAll(guid: string, cb: Callback): void; - - /** - * Permanently deletes the tag with the provided GUID, if present. - *

- * NOTE: This function is generally not available to third party applications. - * Calls will result in an EDAMUserException with the error code - * PERMISSION_DENIED. - * - * @param guid - * The GUID of the tag to delete. - * - * @return - * The Update Sequence Number for this change within the account. - * - * @throws EDAMUserException

    - *
  • BAD_DATA_FORMAT "Tag.guid" - if the guid parameter is missing - *
  • - *
  • PERMISSION_DENIED "Tag" - user doesn't own tag - *
  • - *
- * - * @throws EDAMNotFoundException
    - *
  • "Tag.guid" - tag not found, by GUID - *
  • - *
- */ - expungeTag(guid: string, cb: Callback): void; - - /** - * Returns a list of the searches in the account. Evernote does not support - * the undeletion of searches, so this will only include active searches. - */ - listSearches(cb: Callback): void; - - /** - * Returns the current state of the search with the provided GUID. - * - * @param guid - * The GUID of the search to be retrieved. - * - * @throws EDAMUserException