diff --git a/types/adone/adone.d.ts b/types/adone/adone.d.ts index a4f102752c..34540761b5 100644 --- a/types/adone/adone.d.ts +++ b/types/adone/adone.d.ts @@ -1,85 +1,133 @@ /// -declare const _null: symbol; -export { _null as null }; -export function noop(): void; -export function identity(x: T): T; -export function truly(): true; -export function falsely(): false; -export const ok: "OK"; -export const bad: "BAD"; -export const exts: [".js", ".tjs", ".ajs"]; -export function log(...args: any[]): void; -export function fatal(...args: any[]): void; -export function error(...args: any[]): void; -export function warn(...args: any[]): void; -export function info(...args: any[]): void; -export function debug(...args: any[]): void; -export function trace(...args: any[]): void; -export function o(...props: any[]): object; -export const Date: typeof global.Date; -export const hrtime: typeof global.process.hrtime; -export const setTimeout: typeof global.setTimeout; -export const setInterval: typeof global.setInterval; -export const setImmediate: typeof global.setImmediate; -export const clearTimeout: typeof global.clearTimeout; -export const clearInterval: typeof global.clearInterval; -export const clearImmediate: typeof global.clearImmediate; -interface LazifyOptions { - configurable: boolean; +declare namespace adone { + const _null: symbol; + export { _null as null }; + export function noop(): void; + export function identity(x: T): T; + export function truly(): true; + export function falsely(): false; + export const ok: "OK"; + export const bad: "BAD"; + export const exts: [".js", ".tjs", ".ajs"]; + export function log(...args: any[]): void; + export function fatal(...args: any[]): void; + export function error(...args: any[]): void; + export function warn(...args: any[]): void; + export function info(...args: any[]): void; + export function debug(...args: any[]): void; + export function trace(...args: any[]): void; + export function o(...props: any[]): object; + export const Date: typeof global.Date; + export const hrtime: typeof global.process.hrtime; + export const setTimeout: typeof global.setTimeout; + export const setInterval: typeof global.setInterval; + export const setImmediate: typeof global.setImmediate; + export const clearTimeout: typeof global.clearTimeout; + export const clearInterval: typeof global.clearInterval; + export const clearImmediate: typeof global.clearImmediate; + + namespace I { + interface LazifyOptions { + /** + * Whether the new properties are configurable, false by default + */ + configurable?: boolean; + + /** + * Whether the new properties are writable, false by default + */ + writable?: boolean; + + /** + * A custom mapper for values, by default returns the exported object (module.exports), + * but if the object is a transpiled es module and the default export is defined, + * it returns the default export + * + * @param key property + * @param mod module.exports + */ + mapper?(key: string, mod: any): any; + } + } + + /** + * Extends the given object(or creates a new one) with the given lazyfied properties + */ + export function lazify(modules: object, obj?: object, require?: (path: string) => any, options?: I.LazifyOptions): object; + + /** + * Defines or extends the private part of the given object with the given lazyfied properties + */ + export function lazifyPrivate(modules: object, obj?: object, require?: (path: string) => any, options?: I.LazifyOptions): object; + + /** + * Defines the private part of the given object with the given modules + */ + export function definePrivate(modules: object, obj: object): object; + + /** + * Returns the private part of the given object + */ + export function private(obj: object): any; + + namespace I { + interface Tag { + set(Class: object, tag: string): void; + has(obj: object, tag: string): boolean; + define(tag: string, predicate?: string): void; + SUBSYSTEM: symbol; + APPLICATION: symbol; + TRANSFORM: symbol; + CORE_STREAM: symbol; + LOGGER: symbol; + LONG: symbol; + BIGNUMBER: symbol; + EXBUFFER: symbol; + EXDATE: symbol; + CONFIGURATION: symbol; + GENESIS_NETRON: symbol; + GENESIS_PEER: symbol; + NETRON: symbol; + NETRON_PEER: symbol; + NETRON_ADAPTER: symbol; + NETRON_DEFINITION: symbol; + NETRON_DEFINITIONS: symbol; + NETRON_REFERENCE: symbol; + NETRON_INTERFACE: symbol; + NETRON_STUB: symbol; + NETRON_REMOTESTUB: symbol; + NETRON_STREAM: symbol; + FAST_STREAM: symbol; + FAST_FS_STREAM: symbol; + FAST_FS_MAP_STREAM: symbol; + } + } + export const tag: I.Tag; + export function bind(libName: string): object; + export function getAssetAbsolutePath(relPath: string): string; + export function loadAsset(relPath: string): string | Buffer; + export function require(path: string): object; + export const package: object; + + namespace I { + interface Runtime { + term: object; // TODO + logger: object; // TODO + app: object; // TODO + } + } + + export const runtime: I.Runtime; + + export const homePath: string; + export const rootPath: string; + export const etcPath: string; + export const config: object; + export const emptyBuffer: Buffer; + + export const assert: assertion.I.AssertFunction; + export const expect: assertion.I.ExpectFunction; + + export const std: typeof nodestd; } -export function lazify(modules: object, obj?: object, require?: (path: string) => any, options?: LazifyOptions): object; -interface Tag { - set(Class: object, tag: string): void; - has(obj: object, tag: string): boolean; - define(tag: string, predicate?: string): void; - SUBSYSTEM: symbol; - APPLICATION: symbol; - TRANSFORM: symbol; - CORE_STREAM: symbol; - LOGGER: symbol; - LONG: symbol; - BIGNUMBER: symbol; - EXBUFFER: symbol; - EXDATE: symbol; - CONFIGURATION: symbol; - GENESIS_NETRON: symbol; - GENESIS_PEER: symbol; - NETRON: symbol; - NETRON_PEER: symbol; - NETRON_ADAPTER: symbol; - NETRON_DEFINITION: symbol; - NETRON_DEFINITIONS: symbol; - NETRON_REFERENCE: symbol; - NETRON_INTERFACE: symbol; - NETRON_STUB: symbol; - NETRON_REMOTESTUB: symbol; - NETRON_STREAM: symbol; - FAST_STREAM: symbol; - FAST_FS_STREAM: symbol; - FAST_FS_MAP_STREAM: symbol; -} -export const tag: Tag; -export function run(App: object, ignoreArgs?: boolean): Promise; -export function bind(libName: string): object; -export function getAssetAbsolutePath(relPath: string): string; -export function loadAsset(relPath: string): string | Buffer; -export function require(path: string): object; -export const package: object; - -import * as std from "./glosses/std"; -export { std }; - -export * from "./glosses/common"; -export * from "./glosses/math"; -export * from "./glosses/utils"; -export * from "./glosses/assertion"; -export * from "./glosses/promise"; -export * from "./glosses/shani"; - -import "./glosses/shani-global"; - -export const assert: adone.assertion.I.AssertFunction; -export const expect: adone.assertion.I.ExpectFunction; - -export as namespace adone; diff --git a/types/adone/glosses/application.d.ts b/types/adone/glosses/application.d.ts new file mode 100644 index 0000000000..6b2b783d68 --- /dev/null +++ b/types/adone/glosses/application.d.ts @@ -0,0 +1,5 @@ +declare namespace adone { + namespace application { + function run(app: object, ignoreArgs?: boolean): Promise; + } +} diff --git a/types/adone/glosses/archives.d.ts b/types/adone/glosses/archives.d.ts new file mode 100644 index 0000000000..3f059ff14d --- /dev/null +++ b/types/adone/glosses/archives.d.ts @@ -0,0 +1,670 @@ +declare namespace adone { + /** + * Various archivers + */ + namespace archive { + /** + * tar archiver + */ + namespace tar { + namespace I { + interface Header { + /** + * File path + */ + name: string; + + /** + * Type of entry, file by default + */ + type: "file" | "directory" | "link" | "symlink" | "block-device" | "character-device" | "fifo" | "contiguous-file"; + + /** + * Entry mode, 0755 for dirs and 0644 by default + */ + mode: number; + + /** + * Last modified date for entry, now by default + */ + mtime: number; + + /** + * Entry size, 0 by default + */ + size: number; + + /** + * Linked file name + */ + linkname: string; + + /** + * uid for entry owner, 0 by default + */ + uid: number; + + /** + * gid for entry owner, 9 by default + */ + gid: number; + + /** + * uname of entry owner, null by default + */ + uname: string; + + /** + * gname of entry owner, null by default + */ + gname: string; + + /** + * device minor versio, 0 by default + */ + devmajor: number; + + /** + * device minor version, 0 by default + */ + devminor: number; + } + + type Optional = { + [P in keyof T]?: T[P]; + }; + + interface OptionalHeader extends Optional
{ + /** + * File path + */ + name: string; + } + + interface CommonOptions { + /** + * Entries filter + */ + ignore?(name: string): boolean; + + /** + * Header mapper, called for each each entry + */ + map?(header: Header): Header | undefined; + + /** + * Set the dmode and fmode to writable + */ + readable?: boolean; + + /** + * Set the dmode and fmode to writable + */ + writable?: boolean; + + /** + * Strip the parts of paths of files + */ + strip?: number; + + /** + * Ensure that packed directories have the corresponding modes + */ + dmode?: number; + + /** + * Ensure that packed files have the corresponding modes + */ + fmode?: number; + + /** + * A custom umask, process.umask() by default + */ + umask?: number; + } + + interface PackOptions extends CommonOptions { + /** + * Input read stream modifier, called for each entry + */ + mapStream?(stream: fs.I.ReadStream, header: Header): nodestd.stream.Readable; + + /** + * Pack the contents of the symlink instead of the link itself, false by default + */ + dereference?: boolean; + + /** + * Specifies which entries to pack, all by default + */ + entries?: string[]; + + /** + * Whether to sort entries before packing + */ + sort?: boolean; + + /** + * set false to ignore errors due to unsupported entry types (like device files), true by default + */ + strict?: boolean; + + /** + * A custom initial pack stream + */ + pack?: RawPackStream; + } + + type Writable = nodestd.stream.Writable; + + interface LinkSink extends Writable { + linkname: string; + } + + interface UnpackOptions extends CommonOptions { + /** + * Input read stream modifier, called for each entry + */ + mapStream?(stream: UnpackSourceStream, header: Header): nodestd.stream.Readable; + + /** + * Whether to change time properties of files + */ + utimes?: boolean; + + /** + * Whether to change owner of the files + */ + chown?: boolean; + + /** + * A custom unpack stream + */ + unpack?: RawUnpackStream; + + /** + * Copies a file if cannot create a link + */ + hardlinkAsFilesFallback?: boolean; + } + + interface UnpackSourceStream extends nodestd.stream.PassThrough { + _parent: RawUnpackStream; + } + } + + /** + * Represents a raw tar unpack stream + */ + class RawPackStream extends nodestd.stream.Readable { + entry(header: I.OptionalHeader, buffer: Buffer, callback?: (err: any) => void): I.Writable; + entry(header: I.OptionalHeader & { type: "symblink", linkname: string }, callback?: (err: any) => void): I.Writable; + entry(header: I.OptionalHeader & { type: "symlink" }, callback?: (err: any) => void): I.LinkSink; + entry(header: I.OptionalHeader, callback?: (err: any) => void): I.Writable; + + finalize(): void; + + destroy(err?: any): void; + } + + /** + * Represents a raw writable unpack stream + */ + class RawUnpackStream extends nodestd.stream.Writable { + on(event: string, listener: (...args: any[]) => void): this; + on(event: "entry", listener: (header: I.Header, stream: I.UnpackSourceStream, next: (err?: any) => void) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: nodestd.stream.Readable) => void): this; + on(event: "unpipe", listener: (src: nodestd.stream.Readable) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "entry", listener: (header: I.Header, stream: I.UnpackSourceStream, next: (err?: any) => void) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: nodestd.stream.Readable) => void): this; + once(event: "unpipe", listener: (src: nodestd.stream.Readable) => void): this; + } + + /** + * Creates a pack stream for the files from the given directory + * + * @param cwd directory to pack + */ + function packStream(cwd: string, options?: I.PackOptions): RawPackStream; + + /** + * Creates an unpack stream to the given direcotry + * + * @param cwd direcotry to unpack to + */ + function unpackStream(cwd: string, options?: I.UnpackOptions): RawUnpackStream; + } + + /** + * zip archiver + */ + namespace zip { + /** + * zip packer + */ + namespace pack { + class ZipFile { + /** + * A readable stream that will produce the contents of the zip file + */ + outputStream: nodestd.stream.Readable; + + /** + * Adds a file from the file system at realPath into the zipfile as metadataPath + * + * @param path path to the file + * @param metadataPath path to the file inside the archive + */ + addFile(path: string, metadataPath: string, options?: { + /** + * Overrides the value that will be obtained from stat + */ + mtime?: number, + + /** + * Overrides the value that will be obtained from stat + */ + mode?: number, + + /** + * If true, the file data will be deflated (compression method 8). + * + * If false, the file data will be stored (compression method 0) + */ + compress?: boolean, + + /** + * Use ZIP64 format in this entry's Data Descriptor and Central Directory Record + * regardless of if it's required or not (this may be useful for testing.). + * Otherwise, packer will use ZIP64 format where necessary. + */ + forceZip64Format?: boolean + }): this; + + /** + * Adds a file to the zip file whose content is read from readStream + * + * @param stream a readable stream for the file + * @param metadataPath path to the file inside the archive + */ + addReadStream(stream: nodestd.stream.Readable, metadataPath: string, options?: { + /** + * Defines modified date, now by default + */ + mtime?: number, + + /** + * Defines file mode, 0o100664 by default + */ + mode?: number, + + /** + * If true, the file data will be deflated (compression method 8). + * + * If false, the file data will be stored (compression method 0) + */ + compress?: boolean, + + /** + * Use ZIP64 format in this entry's Data Descriptor and Central Directory Record + * regardless of if it's required or not (this may be useful for testing.). + * Otherwise, packer will use ZIP64 format where necessary. + */ + forceZip64Format?: boolean, + + /** + * If given, it will be checked against the actual number of bytes in the readStream, + * and an error will be emitted if there is a mismatch + */ + size?: number + }): this; + + /** + * Adds a file to the zip file whose content is buffer + * + * @param buffer the file's contents, must be at most 0x3fffffff bytes long + * @param metadataPath path to the file inside the archive + */ + addBuffer(buffer: Buffer, metadataPath: string, options?: { + /** + * Defines modified date, now by default + */ + mtime?: number, + + /** + * Defines file mode, 0o100664 by default + */ + mode?: number, + + /** + * If true, the file data will be deflated (compression method 8). + * + * If false, the file data will be stored (compression method 0) + */ + compress?: boolean, + + /** + * Use ZIP64 format in this entry's Data Descriptor and Central Directory Record + * regardless of if it's required or not (this may be useful for testing.). + * Otherwise, packer will use ZIP64 format where necessary. + */ + forceZip64Format?: boolean + }): this; + + /** + * Adds an entry to the zip file that indicates a directory should be created, + * even if no other items in the zip file are contained in the directory + */ + addEmptyDirectory(metadataPath: string, options?: { + /** + * Defines modified date, now by default + */ + mtime?: number, + + /** + * Defines file mode, 0o40775 by default + */ + mode?: number + }): this; + + /** + * Indicates that no more files will be added via addFile(), addReadStream(), or addBuffer(). + * Some time after calling this function, outputStream will be ended. + * + * @returns the final guessed size of the file, can be -1 if it is hard to guess before processing. This will happend + * only if compression is enabled, or a stream with no size hint given + */ + end(options?: { + /** + * If true, packet will include the ZIP64 End of Central Directory Locator and ZIP64 End of Central Directory Record + * regardless of whether or not they are required (this may be useful for testing.). + * Otherwise, packer will include these structures if necessary + */ + forceZip64Format?: boolean + }): Promise; + } + } + + /** + * zip unpacker + */ + namespace unpack { + namespace I { + interface ExtraField { + id: number; + data: Buffer; + } + + interface Entry { + versionMadeBy: number; + versionNeededToExtract: number; + generalPurposeBitFlag: number; + compressionMethod: number; + lastModFileTime: number; + lastModFileDate: number; + crc32: number; + compressedSize: number; + uncompressedSize: number; + fileNameLength: number; + extraFieldLength: number; + fileCommentLength: number; + internalFileAttributes: number; + externalFileAttributes: number; + relativeOffsetOfLocalHeader: number; + + /** + * The bytes for the file name are decoded with UTF-8 if generalPurposeBitFlag & 0x800, otherwise with CP437. + * Alternatively, this field may be populated from the Info-ZIP Unicode Path Extra Field (see extraFields). + */ + fileName: StringType; + + extraFields: ExtraField[]; + + /** + * Comment decoded with the charset indicated by generalPurposeBitFlag & 0x800 as with the fileName + */ + fileComment: StringType; + + getLastModDate(): adone.I.datetime.Datetime; + + /** + * Whether this entry is encrypted with "Traditional Encryption" + */ + isEncrypted(): boolean; + + /** + * Whether the entry is compressed + */ + isCompressed(): boolean; + } + + interface ZipFile extends event.EventEmitter { + /** + * true until close() is called; then it's false + */ + isOpen: boolean; + + /** + * Total number of central directory records + */ + entryCount: number; + + /** + * Always decoded with CP437 per the spec + */ + comment: StringType; + + /** + * Causes all future calls to openReadStream() to fail, + * and closes the fd after all streams created by openReadStream() have emitted their end events + */ + close(): void; + + readEntry(): Promise; + + /** + * Opens a read stream for the given entry + */ + openReadStream(entry: Entry, options?: { + /** + * The option must be omitted when the entry is not compressed (see isCompressed()), + * and either true (or omitted) or false when the entry is compressed. + * Specifying decompress: false for a compressed entry causes the read stream + * to provide the raw compressed file data without going through a zlib inflate transform + */ + decompress?: boolean, + + /** + * The option must be null (or omitted) for non-encrypted entries, + * and false for encrypted entries. Omitting the option for an encrypted entry will result in an err. + */ + decrypt?: boolean, + + /** + * The start byte offset (inclusive) into this entry's file data + */ + start?: number, + + /** + * The end byte offset (exclusive) into this entry's file data + */ + end?: number, + }): Promise; + + /** + * Emitted for each entry. + * + * If decodeStrings is true, entries emitted via this event have already passed file name validation + * + * If validateEntrySizes is true and this entry's compressionMethod is 0 (stored without compression), + * this entry has already passed entry size validation + */ + on(event: "entry", listener: (entry: Entry) => void): this; + + /** + * Emitted after the last entry event has been emitted + */ + on(event: "end", listener: () => void): this; + + /** + * Emitted after the fd is actually closed + */ + on(event: "close", listener: () => void): this; + + /** + * Emitted in the case of errors with reading the zip file + */ + on(event: "error", listener: (err: any) => void): this; + + /** + * Emitted for each entry. + * + * If decodeStrings is true, entries emitted via this event have already passed file name validation + * + * If validateEntrySizes is true and this entry's compressionMethod is 0 (stored without compression), + * this entry has already passed entry size validation + */ + once(event: "entry", listener: (entry: Entry) => void): this; + + /** + * Emitted after the last entry event has been emitted + */ + once(event: "end", listener: () => void): this; + + /** + * Emitted after the fd is actually closed + */ + once(event: "close", listener: () => void): this; + + /** + * Emitted in the case of errors with reading the zip file + */ + once(event: "error", listener: (err: any) => void): this; + } + + interface CommonOptions { + /** + * Indicates that entries should be read only when readEntry() is called. + * If lazyEntries is false, entry events will be emitted as fast as possible + * to allow pipe()-ing file data from all entries in parallel. + * + * Default is false + */ + lazyEntries?: boolean; + + /** + * Causes unpacker to decode strings with CP437 or UTF-8 as required by the spec. + * + * When turned off zipfile.comment, entry.fileName, and entry.fileComment will be Buffer, + * any Info-ZIP Unicode Path Extra Field will be ignored, automatic file name validation will not be performed + */ + decodeStrings?: boolean; + + /** + * Ensures that an entry's reported uncompressed size matches its actual uncompressed size + */ + validateEntrySizes?: boolean; + } + + interface PathOptions extends CommonOptions { + /** + * Autocloses the file after the last entry reading or when an error occurs + * + * Default is true + */ + autoClose?: boolean; + } + + interface FdOptions extends CommonOptions { + /** + * Autocloses the file after the last entry reading or when an error occurs + * + * Default is false + */ + autoClose?: boolean; + } + + type BufferOptions = CommonOptions; + + interface RandomAccessReaderOptions extends CommonOptions { + /** + * Autocloses the file after the last entry reading or when an error occurs + * + * Default is true + */ + autoClose?: boolean; + } + } + + /** + * Opens a file and creates a zipfile unpacker + */ + function open(path: string, options: I.PathOptions & { decodeStrings: false }): I.ZipFile; + + /** + * Opens a file and creates a zipfile unpacker + */ + function open(path: string, options?: I.PathOptions): I.ZipFile; + + /** + * Creates a zipfile unpacker for the given fd + */ + function fromFd(fd: number, options: I.FdOptions & { decodeStrings: false }): I.ZipFile; + + /** + * Creates a zipfile unpacker for the given fd + */ + function fromFd(fd: number, options?: I.FdOptions): I.ZipFile; + + /** + * Creates a zipfile unpacker for the given buffer + */ + function fromBuffer(buffer: Buffer, options: I.BufferOptions & { decodeStrings: false }): I.ZipFile; + + /** + * Creates a zipfile unpacker for the given buffer + */ + function fromBuffer(buffer: Buffer, options?: I.BufferOptions): I.ZipFile; + + /** + * Creates a zipfile unpacker for the given random access reader. + * This method of reading a zip file allows clients to implement their own back-end file system + * + * @param totalSize Indicates the total file size of the zip file + */ + function fromRandomAccessReader( + reader: fs.AbstractRandomAccessReader, + totalSize: number, + options: I.RandomAccessReaderOptions & { decodeStrings: false } + ): I.ZipFile; + + /** + * Creates a zipfile unpacker for the given random access reader. + * This method of reading a zip file allows clients to implement their own back-end file system + * + * @param totalSize Indicates the total file size of the zip file + */ + function fromRandomAccessReader( + reader: fs.AbstractRandomAccessReader, + totalSize: number, + options?: I.RandomAccessReaderOptions + ): I.ZipFile; + + /** + * Returns null or a String error message depending on the validity of fileName + */ + function validateFileName(filename: string): string | null; + } + } + } +} diff --git a/types/adone/glosses/assertion.d.ts b/types/adone/glosses/assertion.d.ts index 4e8bfc593a..e7ba662791 100644 --- a/types/adone/glosses/assertion.d.ts +++ b/types/adone/glosses/assertion.d.ts @@ -1,1074 +1,1074 @@ -import adone from "adone"; +declare namespace adone { + /** + * assertion functions + */ + namespace assertion { + namespace I { + interface assertion { + AssertionError: AssertionError; + config: Config; + use: UseFunction; + loadMockInterface: LoadInterfaceFunction; + loadExpectInterface: LoadInterfaceFunction; + loadAssertInterface: LoadInterfaceFunction; + assert: AssertFunction; + expect: ExpectFunction; + } -/** - * assertion functions - */ -export namespace assertion { - namespace I { - interface assertion { - AssertionError: AssertionError; - config: Config; - use: UseFunction; - loadMockInterface: LoadInterfaceFunction; - loadExpectInterface: LoadInterfaceFunction; - loadAssertInterface: LoadInterfaceFunction; - assert: AssertFunction; - expect: ExpectFunction; + interface Config { + /** + * Include stack in Assertion error message + */ + includeStack: boolean; + /** + * Include `showDiff` flag in the thrown errors + */ + showDiff: boolean; + /** + * Length threshold for actual and expected values in assertion errors + */ + truncateThreshold: number; + /** + * use Proxy to throw an error when a non-existent property is read + */ + useProxy: boolean; + /** + * properties that should be ignored instead of throwing an error if they do not exist on the assertion + */ + proxyExcludedKeys: string[]; + } + + type PossibleTypes = util.I.PossibleTypes | "array"; + + type UseFunction = (fn: () => void) => assertion; + + type LoadInterfaceFunction = () => assertion; + + interface AssertFunction { + /** + * Asserts that value is truthy + */ + (value: any, message?: string): void; + /** + * Throws an AssertionError, like node.js + */ + fail(actual?: any, expected?: any, message?: string, operator?: any): void; + /** + * Asserts that value is truthy + */ + isOk(value: any, message?: string): void; + /** + * Asserts that value is truthy + */ + ok(value: any, message?: string): void; + /** + * Asserts that value is falsy + */ + isNotOk(value: any, message?: string): void; + /** + * Asserts that value is falsy + */ + notOk(value: any, message?: string): void; + /** + * Asserts non-strict equality + */ + equal(actual: any, expected: any, message?: string): void; + /** + * Asserts non-strict inequality + */ + notEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts strict equality + */ + strictEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts strict inequality + */ + notStrictEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts that actual is deeply equal to expected + */ + deepEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts that actual is deeply equal to expected + */ + deepStrictEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts that actual and expected have the same length and the same members (===) + */ + equalArrays(actual: any[], expected: any[], message?: string): void; + /** + * Asserts that actual is not deeply equal to expected + */ + notDeepEqual(actual: any, expected: any, message?: string): void; + /** + * Asserts that value > above + */ + isAbove(value: any, above: any, message?: string): void; + /** + * Asserts that value >= atLeast + */ + isAtLeast(value: any, atLeast: any, message?: string): void; + /** + * Asserts that value < below + */ + isBelow(value: any, below: any, message?: string): void; + /** + * Asserts that value <= atMost + */ + isAtMost(value: any, atMost: any, message?: string): void; + /** + * Asserts that value is true + */ + isTrue(value: any, message?: string): void; + /** + * Asserts that value is not true + */ + isNotTrue(value: any, message?: string): void; + /** + * Asserts that value is false + */ + isFalse(value: any, message?: string): void; + /** + * Asserts that value is not false + */ + isNotFalse(value: any, message?: string): void; + /** + * Asserts that value is null + */ + isNull(value: any, message?: string): void; + /** + * Asserts that valus is not null + */ + isNotNull(value: any, message?: string): void; + /** + * Asserts that value is NaN + */ + isNaN(value: any, message?: string): void; + /** + * Asserts that value is not NaN + */ + isNotNaN(value: any, message?: string): void; + /** + * Asserts that value is neither null nor undefined + */ + exists(value: any, message?: string): void; + /** + * Asserts that value is either null or undefined + */ + notExists(value: any, message?: string): void; + /** + * Asserts that value is undefined + */ + isUndefined(value: any, message?: string): void; + /** + * Asserts that value is not undefined + */ + isDefined(value: any, message?: string): void; + /** + * Asserts that value is a function + */ + isFunction(value: any, message?: string): void; + /** + * Asserts that value is not a function + */ + isNotFunction(value: any, message?: string): void; + /** + * Asserts that value is an object of type Object + */ + isObject(value: any, message?: string): void; + /** + * Asserts that value is not an object of type Object + */ + isNotObject(value: any, message?: string): void; + /** + * Asserts that value is an array + */ + isArray(value: any, message?: string): void; + /** + * Asserts that value is not an array + */ + isNotArray(value: any, message?: string): void; + /** + * Asserts that value is a string + */ + isString(value: any, message?: string): void; + /** + * Asserts that value is not a string + */ + isNotString(value: any, message?: string): void; + /** + * Asserts that value is a number + */ + isNumber(value: any, message?: string): void; + /** + * Asserts that value is not a number + */ + isNotNumber(value: any, message?: string): void; + /** + * Asserts that value is a finite number + */ + isFinite(value: any, message?: string): void; + /** + * Asserts that value is a boolean + */ + isBoolean(value: any, message?: string): void; + /** + * Asserts that value is not a boolean + */ + isNotBoolean(value: any, message?: string): void; + /** + * Asserts that value's type is `type` + */ + typeOf(value: any, type: PossibleTypes, message?: string): void; + typeOf(value: any, type: string, message?: string): void; + /** + * Assert that value's type is not `type` + */ + notTypeOf(value: any, type: PossibleTypes, message?: string): void; + notTypeOf(value: any, type: string, message?: string): void; + /** + * Asserts that value is an instance of constructor + */ + instanceOf(value: any, constructor: object, message?: string): void; + /** + * Asserts that value is not an instance of constructor + */ + notInstanceOf(value: any, constructor: object, message?: string): void; + /** + * Asserts that expected includes inc + */ + include(expected: T[], inc: T, message?: string): void; + include(expected: string, inc: string, message?: string): void; + /** + * Asserts that expected does not include inc + */ + notInclude(expected: T[], inc: T, message?: string): void; + notInclude(expected: string, inc: string, message?: string): void; + /** + * Asserts that expected includes inc + */ + deepInclude(expected: T[], inc: T, message?: string): void; + deepInclude(expected: string, inc: string, message?: string): void; + /** + * Asserts that expected does not include inc + */ + notDeepInclude(expected: T[], inc: T, message?: string): void; + notDeepInclude(expected: string, inc: string, message?: string): void; + /** + * Asserts that expected includes inc + */ + nestedInclude(expected: object, inc: object, message?: string): void; + /** + * Asserts that expected does not include inc + */ + notNestedInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected includes inc + */ + deepNestedInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected includes inc + */ + notDeepNestedInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected includes inc + */ + ownInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected does not include inc + */ + notOwnInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected includes inc + */ + deepOwnInclude(expected: object, inc: object, message?: string): void; + /** + * Assert that expected does not include inc + */ + notDeepOwnInclude(expected: object, inc: object, message?: string): void; + /** + * Asserts that expected matches the regular expression regExp + */ + match(expected: any, regExp: RegExp, message?: string): void; + /** + * Asserts that expected does not match the regular expression regExp + */ + notMatch(expected: any, regExp: RegExp, message?: string): void; + /** + * Asserts that object has a property named `property` + */ + property(object: object, property: string, message?: string): void; + /** + * Asserts that object does not have a property named `property` + */ + notProperty(object: object, property: string, message?: string): void; + /** + * Asserts that object has a property named `property` with value `value` (===) + */ + propertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have a property named `property` with value `value` (===) + */ + notPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object has a property named `property` with a value `value` + */ + deepPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have a property named `property` with value `value` + */ + notDeepPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object has an owned property named `property` + */ + ownProperty(object: object, property: string, message?: string): void; + /** + * Asserts that object does not have an owned property named `property` + */ + notOwnProperty(object: object, property: string, message?: string): void; + /** + * Asserts that object has an owned property named `property` with value `value`(===) + */ + ownPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have an owned property named `property` with value `value`(===) + */ + notOwnPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object has an owned property named `property` with value `value` + */ + deepOwnPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have an owned property named `property` with value `value`(===) + */ + notDeepOwnPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object has a property named `property` + */ + nestedProperty(object: object, property: string, message?: string): void; + /** + * Asserts that object does not have a property named `property` + */ + notNestedProperty(object: object, property: string, message?: string): void; + /** + * Asserts that object has a property named `property` with value `value`(===) + */ + nestedPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have a property named `property` with value `value`(===) + */ + notNestedPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object has a property named `property` with value `value` + */ + deepNestedPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that object does not have a property named `property` with value `value` + */ + notDeepNestedPropertyVal(object: object, property: string, value: any, message?: string): void; + /** + * Asserts that expected has a length property with value `length` + */ + lengthOf(expected: any, length: number, message?: string): void; + /** + * Asserts that object has at least one key from `keys` + */ + hasAnyKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object has all and only all of the keys provided + */ + hasAllKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object has all the keys provided but maybe more + */ + containsAllKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object does not have any provided key + */ + doesNotHaveAnyKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object does not have all the keys provided + */ + doesNotHaveAllKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object has at least one of the keys provided + */ + hasAnyDeepKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object has all and only all of the keys provided + */ + hasAllDeepKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object has all the keys provided but maybe more + */ + containsAllDeepKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object does not have any provided key + */ + doesNotHaveAnyDeepKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that object does not have all the keys provided + */ + doesNotHaveAllDeepKeys(object: object, keys: string | string[] | object, message?: string): void; + /** + * Asserts that a function or an async functions throws an error + */ + throws(fn: () => void, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): any; + throws(fn: () => Promise, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): Promise; + /** + * Asserts that a function or an async functions throws an error + */ + throw(fn: () => void, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): any; + throw(fn: () => Promise, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): Promise; + /** + * Asserts that a function or an async function does not throw an error + */ + doesNotThrow(fn: () => Promise, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): Promise; + doesNotThrow(fn: () => void, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): any; + /** + * Compares two values using operator + */ + operator(value: any, operator: string, val2: any, message?: string): void; + /** + * Asserts that actual is expected +/- delta + */ + closeTo(actual: number, expected: number, delta: number, message?: string): void; + /** + * Asserts that actual is expect +/- delta + */ + approximately(actual: number, expected: number, delta: number, message?: string): void; + /** + * Asserts that arrays have the same members in any order (===) + */ + sameMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays do not have the same members in any order (===) + */ + notSameMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays have the same members in any order + */ + sameDeepMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays do not have the same members in any order + */ + notSameDeepMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays have the same members in the same order (===) + */ + sameOrderedMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays do not have the same members in the same order (===) + */ + notSameOrderedMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays have the same members in the same order + */ + sameDeepOrderedMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that arrays do not have the same members in the same order + */ + notSameDeepOrderedMembers(set1: any[], set2: any[], message?: string): void; + /** + * Asserts that subset is included in superset in any order (===) + */ + includeMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is not included in superset in any order (===) + */ + notIncludeMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is included in superset in any order + */ + includeDeepMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is not included in superset in any order + */ + notIncludeDeepMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is included in superset in the same order (===) + */ + includeOrderedMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is not included in superset in the same order (===) + */ + notIncludeOrderedMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is included in superset in the same order + */ + includeDeepOrderedMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that subset is not included in superset in the same order + */ + notIncludeDeepOrderedMembers(superset: any[], subset: any[], message?: string): void; + /** + * Asserts that list includes inList + */ + oneOf(inList: any, list: any[], message?: string): void; + /** + * Asserts that a function changes the value of a property + */ + changes(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function changes the value of a property by delta + */ + changesBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function does not changes the value of a property + */ + doesNotChange(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function does not change the value of a property or of a function’s return value by delta + */ + changesButNotBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function increases a numeric object property + */ + increases(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function increases a numeric object property or a function’s return value by delta + */ + increasesBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function does not increase a numeric object property + */ + doesNotIncrease(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function does not increase a numeric object property or function’s return value by delta + */ + increasesButNotBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function decreases the value of a property + */ + decreases(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function decreases the value of a property by delta + */ + decreasesBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function does not decrease the value of a property + */ + doesNotDecrease(fn: () => void, object: object, property: string, message?: string): void; + /** + * Asserts that a function does not decrease the value of a property or a function's return value by delta + */ + doesNotDecreaseBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Asserts that a function does not decreases a numeric object property or a function’s return value by delta + */ + decreasesButNotBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; + /** + * Throws an error if value is truthy + */ + ifError(value: any): void; + /** + * Asserts that object is extensible + */ + isExtensible(object: object, message?: string): void; + /** + * Asserts that object is extensible + */ + extensible(object: object, message?: string): void; + /** + * Asserts that object is not extensible + */ + isNotExtensible(object: object, message?: string): void; + /** + * Asserts that object is not extensible + */ + notExtensible(object: object, message?: string): void; + /** + * Asserts that object is sealed + */ + isSealed(object: object, message?: string): void; + /** + * Asserts that object is sealed + */ + sealed(object: object, message?: string): void; + /** + * Asserts that object is not sealed + */ + isNotSealed(object: object, message?: string): void; + /** + * Asserts that object is not sealed + */ + notSealed(object: object, message?: string): void; + /** + * Asserts that object is frozen + */ + isFrozen(object: object, message?: string): void; + /** + * Asserts that object is frozen + */ + frozen(object: object, message?: string): void; + /** + * Asserts that object is not frozen + */ + isNotFrozen(object: object, message?: string): void; + /** + * Asserts that object is not frozen + */ + notFrozen(object: object, message?: string): void; + /** + * Asserts that value is empty + */ + isEmpty(value: any, message?: string): void; + /** + * Asserts that value is empty + */ + empty(value: any, message?: string): void; + /** + * Asserts that value is not empty + */ + isNotEmpty(value: any, message?: string): void; + /** + * Asserts that value is not empty + */ + notEmpty(value: any, message?: string): void; + } + + interface ExpectFunction { + (value: shani.util.I.Spy, message?: string): MockAssertions; + (value: any, message?: string): Assertion; + fail(actual: any, expected: any, message?: string, operator?: any): void; + } + + interface LanguageChains { + to: this; + be: this; + been: this; + is: this; + that: this; + which: this; + and: this; + has: this; + have: this; + with: this; + at: this; + of: this; + same: this; + but: this; + does: this; + } + + interface Assertion extends LanguageChains { + /** + * Negates all following assertion in the chain + */ + not: this; + /** + * Causes following assertions to use deep equality + */ + deep: this; + /** + * Enables dot- and bracket-notation in following property and include assertions + */ + nested: this; + /** + * Causes following property and incude assertions to ignore inherited properties + */ + own: this; + /** + * Causes following members assertions to require that members be in the same order + */ + ordered: this; + /** + * Causes following keys assertions to only require that the target have at least one of the given keys + */ + any: this; + /** + * Causes following keys assertions to require that the target have all of the given keys + */ + all: this; + /** + * Asserts that the target's type is `type` + */ + a(type: PossibleTypes, message?: string): this; + a(type: string, message?: string): this; + /** + * Asserts that the target's type is `type` + */ + an(type: PossibleTypes, message?: string): this; + an(type: string, message?: string): this; + /** + * Asserts that the target includes the given value + */ + include(value: any, message?: string): this; + /** + * Asserts that the target includes the given value + */ + includes(value: any, message?: string): this; + /** + * Asserts that the target contains the given value + */ + contain(value: any, message?: string): this; + /** + * Asserts that the target contains the given value + */ + contains(value: any, message?: string): this; + /** + * Asserts that the target is non-strictly equal to true + */ + ok: this; + /** + * Asserts that the target is true + */ + true: this; + /** + * Asserts that the target is false + */ + false: this; + /** + * Asserts that the target is null + */ + null: this; + /** + * Asserts that the target is undefined + */ + undefined: this; + /** + * Asserts that the target is NaN + */ + NaN: this; + /** + * Asserts that the target is neither null nor undefined + */ + exist: this; + /** + * Asserts that the target is empty + */ + empty: this; + /** + * Asserts that the target is an arguments object + */ + arguments: this; + /** + * Asserts that the target is an arguments object + */ + Arguments: this; + /** + * Asserts that the target is strictly equal to value(===) + */ + equal(value: any, message?: string): this; + /** + * Asserts that the target is strictly equal to value(===) + */ + equals(value: any, message?: string): this; + /** + * Asserts that the target is strictly equal to value(===) + */ + eq(value: any, message?: string): this; + /** + * Asserts that the target is deeply equal to object + */ + eql(object: any, message?: string): this; + /** + * Asserts that the target is deeply equal to object + */ + eqls(object: any, message?: string): this; + /** + * Asserts that the target has the same length length and elements as array in the same order + */ + eqlArray(array: any[], message?: string): this; + /** + * Asserts that target > n + */ + above(n: number, message?: string): this; + /** + * Asserts that target > n + */ + gt(n: number, message?: string): this; + /** + * Asserts that target > n + */ + greaterThan(n: number, message?: string): this; + /** + * Asserts that target >= n + */ + least(n: number, message?: string): this; + /** + * Asserts that target >= n + */ + gte(n: number, message?: string): this; + /** + * Asserts that target < n + */ + below(n: number, message?: string): this; + /** + * Asserts that target < n + */ + lt(n: number, message?: string): this; + /** + * Asserts that target < n + */ + lessThan(n: number, message?: string): this; + /** + * Asserts that target <= n + */ + most(n: number, message?: string): this; + /** + * Asserts that target <= n + */ + lte(n: number, message?: string): this; + /** + * Asserts that start <= target <= end + */ + within(start: number, end: number, message?: string): this; + /** + * Asserts that the target is an instance of constructor + */ + instanceof(constructor: object, message?: string): this; + /** + * Asserts that the target is an instance of constructor + */ + instanceOf(constructor: object, message?: string): this; + /** + * Asserts that the target has a property name `name` with value `value` + */ + property(name: string, value?: any, message?: string): this; + /** + * Asserts that the target has its own property name `name` with value `value` + */ + ownProperty(name: string, value?: any, message?: string): this; + /** + * Asserts that the target has its own property name `name` with value `value` + */ + haveOwnProperty(name: string, value?: any, message?: string): this; + /** + * Asserts that the target has its own property descriptor with name `name` and value `value` + */ + ownPropertyDescriptor(name: string, descriptor?: object, message?: string): this; + /** + * Asserts that the target has its own property descriptor with name `name` and value `value` + */ + haveOwnPropertyDescriptor(name: string, descriptor?: object, message?: string): this; + /** + * Asserts that the target's property length equal to n + */ + length(n: number, message?: string): this; + /** + * Asserts that the target's property length equal to n + */ + lengthOf(n: number, message?: string): this; + /** + * Asserts that the target matches the regular expression regExp + */ + match(regExp: RegExp, message?: string): this; + /** + * Asserts that the target matches the regular expression regExp + */ + matches(regExp: RegExp, message?: string): this; + /** + * Asserts that the target contains str as a substring + */ + string(str: string, message?: string): this; + /** + * Assert that the target has the given keys + */ + key(key: string | string[] | object): this; + key(...keys: string[]): this; + /** + * Assert that the target has the given keys + */ + keys(key: string | string[] | object): this; + keys(...keys: string[]): this; + /** + * Assert that the target throws an error + */ + throw(errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): this; + /** + * Assert that the target throws an error + */ + throws(errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): this; + /** + * Assert that the target throws an error + */ + Throw(errorLike?: Error, errMsgMatcher?: string | RegExp): this; + /** + * Assert that the target has a method with name `method`. For functions checks the prototype + */ + respondTo(method: string, message?: string): this; + /** + * Assert that the target has a method with name `method`. For functions checks the prototype + */ + respondsTo(method: string, message?: string): this; + /** + * Makes respondsTo behave like the target is not a function + */ + itself: this; + /** + * Asserts that matches returns a truthy value with the target as the first argument + */ + satisfy(matcher: () => boolean, message?: string): this; + /** + * Asserts that matches returns a truthy value with the target as the first argument + */ + satisfies(matcher: () => boolean, message?: string): this; + /** + * Asserts that the target is expected +/- delta + */ + closeTo(expected: number, delta: number, message?: string): this; + /** + * Asserts that the target is expected +/- delta + */ + approximately(expected: number, delta: number, message?: string): this; + /** + * Asserts that the target array has the same members as the given + */ + members(set: any[], message?: string): this; + /** + * Asserts that the target is the member of list + */ + oneOf(list: any[], message?: string): this; + /** + * Asserts that fn returns a different value after the target's invokation than before + */ + change(fn: () => any, message?: string): this; + /** + * Asserts that the target's invokation changes subject's property + */ + change(subject: object, property: string, message?: string): this; + /** + * Asserts that fn returns a different value after the target's invokation than before + */ + changes(fn: () => any, message?: string): this; + /** + * Asserts that the target's invokation changes subject's property + */ + changes(subject: object, property: string, message?: string): this; + /** + * Asserts that fn returns a greater number after the target's invokation than before + */ + increase(fn: () => number, message?: string): this; + /** + * Asserts that the target's invokation increases subject's property + */ + increase(subject: object, property?: string, message?: string): this; + /** + * Asserts that fn returns a greater number after the target's invokation than before + */ + increases(fn: () => number, message?: string): this; + /** + * Asserts that the target's invokation increases subject's property + */ + increases(subject: object, property?: string, message?: string): this; + /** + * Asserts that fn returns a lesser number after the target's invokation than before + */ + decrease(fn: () => number, message?: string): this; + /** + * Asserts that the target's invokation decreases subject's property + */ + decrease(subject: object, property?: string, message?: string): this; + /** + * Asserts that fn returns a lesser number after the target's invokation than before + */ + decreases(fn: () => number, message?: string): this; + /** + * Asserts that the target's invokation decreases subject's property + */ + decreases(subject: object, property?: string, message?: string): this; + /** + * Asserts that the value was decreased/increased by delta + */ + by(delta: number, message?: string): this; + /** + * Asserts that the target is extensible + */ + extensible: this; + /** + * Asserts that the target is sealed + */ + sealed: this; + /** + * Asserts that the target is frozen + */ + frozen: this; + /** + * Asserts that the target is a finite number + */ + finite: this; + } + + interface MockAssertions extends Assertion { + /** + * Asserts that the spy has been called + */ + called: this; + /** + * Asserts that the spy has been called n times + */ + callCount(n: number): this; + /** + * Asserts that the spy has been called once + */ + calledOnce: this; + /** + * Asserts that the spy has been called twice + */ + calledTwice: this; + /** + * Asserts that the spy has been been called with `new` + */ + calledThrice: this; + /** + * Asserts that the spy has been called before anotherSpy + */ + calledBefore(anotherSpy: shani.util.I.Spy): this; + /** + * Asserts that the spy has been called after anotherSpy + */ + calledAfter(anotherSpy: shani.util.I.Spy): this; + /** + * Asserts that the spy has been called immediately before anotherSpy + */ + calledImmediatelyBefore(anotherSpy: shani.util.I.Spy): this; + /** + * Asserts that the spy has been called immediately after anotherSpy + */ + calledImmediatelyAfter(anotherSpy: shani.util.I.Spy): this; + /** + * Asserts that the spy has been called with context as this value + */ + calledOn(context: object): this; + /** + * Asserts that the spy has been called with the given arguments + */ + calledWith(...args: any[]): this; + /** + * Asserts that the spy has been called exactly with the given arguments + */ + calledWithExactly(...args: any[]): this; + /** + * Asserts that the spy has been called with matching arguments + */ + calledWithMatch(...args: any[]): this; + /** + * Asserts that the spy returned value + */ + returned(value: any): this; + /** + * Asserts that the spy threw error + */ + thrown(error: any): this; + /** + * Asserts that the spy threw error + */ + threw(error: any): this; + } } - interface Config { - /** - * Include stack in Assertion error message - */ - includeStack: boolean; - /** - * Include `showDiff` flag in the thrown errors - */ - showDiff: boolean; - /** - * Length threshold for actual and expected values in assertion errors - */ - truncateThreshold: number; - /** - * use Proxy to throw an error when a non-existent property is read - */ - useProxy: boolean; - /** - * properties that should be ignored instead of throwing an error if they do not exist on the assertion - */ - proxyExcludedKeys: string[]; + class AssertionError extends x.Exception { + constructor(message?: string, props?: object, ssf?: object) } - type PossibleTypes = adone.util.I.PossibleTypes | "array"; - - type UseFunction = (fn: () => void) => assertion; - - type LoadInterfaceFunction = () => assertion; - - interface AssertFunction { - /** - * Asserts that value is truthy - */ - (value: any, message?: string): void; - /** - * Throws an AssertionError, like node.js - */ - fail(actual?: any, expected?: any, message?: string, operator?: any): void; - /** - * Asserts that value is truthy - */ - isOk(value: any, message?: string): void; - /** - * Asserts that value is truthy - */ - ok(value: any, message?: string): void; - /** - * Asserts that value is falsy - */ - isNotOk(value: any, message?: string): void; - /** - * Asserts that value is falsy - */ - notOk(value: any, message?: string): void; - /** - * Asserts non-strict equality - */ - equal(actual: any, expected: any, message?: string): void; - /** - * Asserts non-strict inequality - */ - notEqual(actual: any, expected: any, message?: string): void; - /** - * Asserts strict equality - */ - strictEqual(actual: any, expected: any, message?: string): void; - /** - * Asserts strict inequality - */ - notStrictEqual(actual: any, expected: any, message?: string): void; - /** - * Asserts that actual is deeply equal to expected - */ - deepEqual(actual: any, expected: any, message?: string): void; - /** - * Asserts that actual is deeply equal to expected - */ - deepStrictEqual(actual: any, expected: any, message?: string): void; - /** - * Asserts that actual and expected have the same length and the same members (===) - */ - equalArrays(actual: any[], expected: any[], message?: string): void; - /** - * Asserts that actual is not deeply equal to expected - */ - notDeepEqual(actual: any, expected: any, message?: string): void; - /** - * Asserts that value > above - */ - isAbove(value: any, above: any, message?: string): void; - /** - * Asserts that value >= atLeast - */ - isAtLeast(value: any, atLeast: any, message?: string): void; - /** - * Asserts that value < below - */ - isBelow(value: any, below: any, message?: string): void; - /** - * Asserts that value <= atMost - */ - isAtMost(value: any, atMost: any, message?: string): void; - /** - * Asserts that value is true - */ - isTrue(value: any, message?: string): void; - /** - * Asserts that value is not true - */ - isNotTrue(value: any, message?: string): void; - /** - * Asserts that value is false - */ - isFalse(value: any, message?: string): void; - /** - * Asserts that value is not false - */ - isNotFalse(value: any, message?: string): void; - /** - * Asserts that value is null - */ - isNull(value: any, message?: string): void; - /** - * Asserts that valus is not null - */ - isNotNull(value: any, message?: string): void; - /** - * Asserts that value is NaN - */ - isNaN(value: any, message?: string): void; - /** - * Asserts that value is not NaN - */ - isNotNaN(value: any, message?: string): void; - /** - * Asserts that value is neither null nor undefined - */ - exists(value: any, message?: string): void; - /** - * Asserts that value is either null or undefined - */ - notExists(value: any, message?: string): void; - /** - * Asserts that value is undefined - */ - isUndefined(value: any, message?: string): void; - /** - * Asserts that value is not undefined - */ - isDefined(value: any, message?: string): void; - /** - * Asserts that value is a function - */ - isFunction(value: any, message?: string): void; - /** - * Asserts that value is not a function - */ - isNotFunction(value: any, message?: string): void; - /** - * Asserts that value is an object of type Object - */ - isObject(value: any, message?: string): void; - /** - * Asserts that value is not an object of type Object - */ - isNotObject(value: any, message?: string): void; - /** - * Asserts that value is an array - */ - isArray(value: any, message?: string): void; - /** - * Asserts that value is not an array - */ - isNotArray(value: any, message?: string): void; - /** - * Asserts that value is a string - */ - isString(value: any, message?: string): void; - /** - * Asserts that value is not a string - */ - isNotString(value: any, message?: string): void; - /** - * Asserts that value is a number - */ - isNumber(value: any, message?: string): void; - /** - * Asserts that value is not a number - */ - isNotNumber(value: any, message?: string): void; - /** - * Asserts that value is a finite number - */ - isFinite(value: any, message?: string): void; - /** - * Asserts that value is a boolean - */ - isBoolean(value: any, message?: string): void; - /** - * Asserts that value is not a boolean - */ - isNotBoolean(value: any, message?: string): void; - /** - * Asserts that value's type is `type` - */ - typeOf(value: any, type: I.PossibleTypes, message?: string): void; - typeOf(value: any, type: string, message?: string): void; - /** - * Assert that value's type is not `type` - */ - notTypeOf(value: any, type: I.PossibleTypes, message?: string): void; - notTypeOf(value: any, type: string, message?: string): void; - /** - * Asserts that value is an instance of constructor - */ - instanceOf(value: any, constructor: object, message?: string): void; - /** - * Asserts that value is not an instance of constructor - */ - notInstanceOf(value: any, constructor: object, message?: string): void; - /** - * Asserts that expected includes inc - */ - include(expected: T[], inc: T, message?: string): void; - include(expected: string, inc: string, message?: string): void; - /** - * Asserts that expected does not include inc - */ - notInclude(expected: T[], inc: T, message?: string): void; - notInclude(expected: string, inc: string, message?: string): void; - /** - * Asserts that expected includes inc - */ - deepInclude(expected: T[], inc: T, message?: string): void; - deepInclude(expected: string, inc: string, message?: string): void; - /** - * Asserts that expected does not include inc - */ - notDeepInclude(expected: T[], inc: T, message?: string): void; - notDeepInclude(expected: string, inc: string, message?: string): void; - /** - * Asserts that expected includes inc - */ - nestedInclude(expected: object, inc: object, message?: string): void; - /** - * Asserts that expected does not include inc - */ - notNestedInclude(expected: object, inc: object, message?: string): void; - /** - * Assert that expected includes inc - */ - deepNestedInclude(expected: object, inc: object, message?: string): void; - /** - * Assert that expected includes inc - */ - notDeepNestedInclude(expected: object, inc: object, message?: string): void; - /** - * Assert that expected includes inc - */ - ownInclude(expected: object, inc: object, message?: string): void; - /** - * Assert that expected does not include inc - */ - notOwnInclude(expected: object, inc: object, message?: string): void; - /** - * Assert that expected includes inc - */ - deepOwnInclude(expected: object, inc: object, message?: string): void; - /** - * Assert that expected does not include inc - */ - notDeepOwnInclude(expected: object, inc: object, message?: string): void; - /** - * Asserts that expected matches the regular expression regExp - */ - match(expected: any, regExp: RegExp, message?: string): void; - /** - * Asserts that expected does not match the regular expression regExp - */ - notMatch(expected: any, regExp: RegExp, message?: string): void; - /** - * Asserts that object has a property named `property` - */ - property(object: object, property: string, message?: string): void; - /** - * Asserts that object does not have a property named `property` - */ - notProperty(object: object, property: string, message?: string): void; - /** - * Asserts that object has a property named `property` with value `value` (===) - */ - propertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that object does not have a property named `property` with value `value` (===) - */ - notPropertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that object has a property named `property` with a value `value` - */ - deepPropertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that object does not have a property named `property` with value `value` - */ - notDeepPropertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that object has an owned property named `property` - */ - ownProperty(object: object, property: string, message?: string): void; - /** - * Asserts that object does not have an owned property named `property` - */ - notOwnProperty(object: object, property: string, message?: string): void; - /** - * Asserts that object has an owned property named `property` with value `value`(===) - */ - ownPropertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that object does not have an owned property named `property` with value `value`(===) - */ - notOwnPropertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that object has an owned property named `property` with value `value` - */ - deepOwnPropertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that object does not have an owned property named `property` with value `value`(===) - */ - notDeepOwnPropertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that object has a property named `property` - */ - nestedProperty(object: object, property: string, message?: string): void; - /** - * Asserts that object does not have a property named `property` - */ - notNestedProperty(object: object, property: string, message?: string): void; - /** - * Asserts that object has a property named `property` with value `value`(===) - */ - nestedPropertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that object does not have a property named `property` with value `value`(===) - */ - notNestedPropertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that object has a property named `property` with value `value` - */ - deepNestedPropertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that object does not have a property named `property` with value `value` - */ - notDeepNestedPropertyVal(object: object, property: string, value: any, message?: string): void; - /** - * Asserts that expected has a length property with value `length` - */ - lengthOf(expected: any, length: number, message?: string): void; - /** - * Asserts that object has at least one key from `keys` - */ - hasAnyKeys(object: object, keys: string | string[] | object, message?: string): void; - /** - * Asserts that object has all and only all of the keys provided - */ - hasAllKeys(object: object, keys: string | string[] | object, message?: string): void; - /** - * Asserts that object has all the keys provided but maybe more - */ - containsAllKeys(object: object, keys: string | string[] | object, message?: string): void; - /** - * Asserts that object does not have any provided key - */ - doesNotHaveAnyKeys(object: object, keys: string | string[] | object, message?: string): void; - /** - * Asserts that object does not have all the keys provided - */ - doesNotHaveAllKeys(object: object, keys: string | string[] | object, message?: string): void; - /** - * Asserts that object has at least one of the keys provided - */ - hasAnyDeepKeys(object: object, keys: string | string[] | object, message?: string): void; - /** - * Asserts that object has all and only all of the keys provided - */ - hasAllDeepKeys(object: object, keys: string | string[] | object, message?: string): void; - /** - * Asserts that object has all the keys provided but maybe more - */ - containsAllDeepKeys(object: object, keys: string | string[] | object, message?: string): void; - /** - * Asserts that object does not have any provided key - */ - doesNotHaveAnyDeepKeys(object: object, keys: string | string[] | object, message?: string): void; - /** - * Asserts that object does not have all the keys provided - */ - doesNotHaveAllDeepKeys(object: object, keys: string | string[] | object, message?: string): void; - /** - * Asserts that a function or an async functions throws an error - */ - throws(fn: () => void, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): any; - throws(fn: () => Promise, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): Promise; - /** - * Asserts that a function or an async functions throws an error - */ - throw(fn: () => void, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): any; - throw(fn: () => Promise, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): Promise; - /** - * Asserts that a function or an async function does not throw an error - */ - doesNotThrow(fn: () => Promise, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): Promise; - doesNotThrow(fn: () => void, errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): any; - /** - * Compares two values using operator - */ - operator(value: any, operator: string, val2: any, message?: string): void; - /** - * Asserts that actual is expected +/- delta - */ - closeTo(actual: number, expected: number, delta: number, message?: string): void; - /** - * Asserts that actual is expect +/- delta - */ - approximately(actual: number, expected: number, delta: number, message?: string): void; - /** - * Asserts that arrays have the same members in any order (===) - */ - sameMembers(set1: any[], set2: any[], message?: string): void; - /** - * Asserts that arrays do not have the same members in any order (===) - */ - notSameMembers(set1: any[], set2: any[], message?: string): void; - /** - * Asserts that arrays have the same members in any order - */ - sameDeepMembers(set1: any[], set2: any[], message?: string): void; - /** - * Asserts that arrays do not have the same members in any order - */ - notSameDeepMembers(set1: any[], set2: any[], message?: string): void; - /** - * Asserts that arrays have the same members in the same order (===) - */ - sameOrderedMembers(set1: any[], set2: any[], message?: string): void; - /** - * Asserts that arrays do not have the same members in the same order (===) - */ - notSameOrderedMembers(set1: any[], set2: any[], message?: string): void; - /** - * Asserts that arrays have the same members in the same order - */ - sameDeepOrderedMembers(set1: any[], set2: any[], message?: string): void; - /** - * Asserts that arrays do not have the same members in the same order - */ - notSameDeepOrderedMembers(set1: any[], set2: any[], message?: string): void; - /** - * Asserts that subset is included in superset in any order (===) - */ - includeMembers(superset: any[], subset: any[], message?: string): void; - /** - * Asserts that subset is not included in superset in any order (===) - */ - notIncludeMembers(superset: any[], subset: any[], message?: string): void; - /** - * Asserts that subset is included in superset in any order - */ - includeDeepMembers(superset: any[], subset: any[], message?: string): void; - /** - * Asserts that subset is not included in superset in any order - */ - notIncludeDeepMembers(superset: any[], subset: any[], message?: string): void; - /** - * Asserts that subset is included in superset in the same order (===) - */ - includeOrderedMembers(superset: any[], subset: any[], message?: string): void; - /** - * Asserts that subset is not included in superset in the same order (===) - */ - notIncludeOrderedMembers(superset: any[], subset: any[], message?: string): void; - /** - * Asserts that subset is included in superset in the same order - */ - includeDeepOrderedMembers(superset: any[], subset: any[], message?: string): void; - /** - * Asserts that subset is not included in superset in the same order - */ - notIncludeDeepOrderedMembers(superset: any[], subset: any[], message?: string): void; - /** - * Asserts that list includes inList - */ - oneOf(inList: any, list: any[], message?: string): void; - /** - * Asserts that a function changes the value of a property - */ - changes(fn: () => void, object: object, property: string, message?: string): void; - /** - * Asserts that a function changes the value of a property by delta - */ - changesBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; - /** - * Asserts that a function does not changes the value of a property - */ - doesNotChange(fn: () => void, object: object, property: string, message?: string): void; - /** - * Asserts that a function does not change the value of a property or of a function’s return value by delta - */ - changesButNotBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; - /** - * Asserts that a function increases a numeric object property - */ - increases(fn: () => void, object: object, property: string, message?: string): void; - /** - * Asserts that a function increases a numeric object property or a function’s return value by delta - */ - increasesBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; - /** - * Asserts that a function does not increase a numeric object property - */ - doesNotIncrease(fn: () => void, object: object, property: string, message?: string): void; - /** - * Asserts that a function does not increase a numeric object property or function’s return value by delta - */ - increasesButNotBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; - /** - * Asserts that a function decreases the value of a property - */ - decreases(fn: () => void, object: object, property: string, message?: string): void; - /** - * Asserts that a function decreases the value of a property by delta - */ - decreasesBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; - /** - * Asserts that a function does not decrease the value of a property - */ - doesNotDecrease(fn: () => void, object: object, property: string, message?: string): void; - /** - * Asserts that a function does not decrease the value of a property or a function's return value by delta - */ - doesNotDecreaseBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; - /** - * Asserts that a function does not decreases a numeric object property or a function’s return value by delta - */ - decreasesButNotBy(fn: () => void, object: object, property: string, delta: number, message?: string): void; - /** - * Throws an error if value is truthy - */ - ifError(value: any): void; - /** - * Asserts that object is extensible - */ - isExtensible(object: object, message?: string): void; - /** - * Asserts that object is extensible - */ - extensible(object: object, message?: string): void; - /** - * Asserts that object is not extensible - */ - isNotExtensible(object: object, message?: string): void; - /** - * Asserts that object is not extensible - */ - notExtensible(object: object, message?: string): void; - /** - * Asserts that object is sealed - */ - isSealed(object: object, message?: string): void; - /** - * Asserts that object is sealed - */ - sealed(object: object, message?: string): void; - /** - * Asserts that object is not sealed - */ - isNotSealed(object: object, message?: string): void; - /** - * Asserts that object is not sealed - */ - notSealed(object: object, message?: string): void; - /** - * Asserts that object is frozen - */ - isFrozen(object: object, message?: string): void; - /** - * Asserts that object is frozen - */ - frozen(object: object, message?: string): void; - /** - * Asserts that object is not frozen - */ - isNotFrozen(object: object, message?: string): void; - /** - * Asserts that object is not frozen - */ - notFrozen(object: object, message?: string): void; - /** - * Asserts that value is empty - */ - isEmpty(value: any, message?: string): void; - /** - * Asserts that value is empty - */ - empty(value: any, message?: string): void; - /** - * Asserts that value is not empty - */ - isNotEmpty(value: any, message?: string): void; - /** - * Asserts that value is not empty - */ - notEmpty(value: any, message?: string): void; - } - - interface ExpectFunction { - (value: adone.shani.util.I.Spy, message?: string): MockAssertions; - (value: any, message?: string): Assertion; - fail(actual: any, expected: any, message?: string, operator?: any): void; - } - - interface LanguageChains { - to: this; - be: this; - been: this; - is: this; - that: this; - which: this; - and: this; - has: this; - have: this; - with: this; - at: this; - of: this; - same: this; - but: this; - does: this; - } - - interface Assertion extends LanguageChains { - /** - * Negates all following assertion in the chain - */ - not: this; - /** - * Causes following assertions to use deep equality - */ - deep: this; - /** - * Enables dot- and bracket-notation in following property and include assertions - */ - nested: this; - /** - * Causes following property and incude assertions to ignore inherited properties - */ - own: this; - /** - * Causes following members assertions to require that members be in the same order - */ - ordered: this; - /** - * Causes following keys assertions to only require that the target have at least one of the given keys - */ - any: this; - /** - * Causes following keys assertions to require that the target have all of the given keys - */ - all: this; - /** - * Asserts that the target's type is `type` - */ - a(type: I.PossibleTypes, message?: string): this; - a(type: string, message?: string): this; - /** - * Asserts that the target's type is `type` - */ - an(type: I.PossibleTypes, message?: string): this; - an(type: string, message?: string): this; - /** - * Asserts that the target includes the given value - */ - include(value: any, message?: string): this; - /** - * Asserts that the target includes the given value - */ - includes(value: any, message?: string): this; - /** - * Asserts that the target contains the given value - */ - contain(value: any, message?: string): this; - /** - * Asserts that the target contains the given value - */ - contains(value: any, message?: string): this; - /** - * Asserts that the target is non-strictly equal to true - */ - ok: this; - /** - * Asserts that the target is true - */ - true: this; - /** - * Asserts that the target is false - */ - false: this; - /** - * Asserts that the target is null - */ - null: this; - /** - * Asserts that the target is undefined - */ - undefined: this; - /** - * Asserts that the target is NaN - */ - NaN: this; - /** - * Asserts that the target is neither null nor undefined - */ - exist: this; - /** - * Asserts that the target is empty - */ - empty: this; - /** - * Asserts that the target is an arguments object - */ - arguments: this; - /** - * Asserts that the target is an arguments object - */ - Arguments: this; - /** - * Asserts that the target is strictly equal to value(===) - */ - equal(value: any, message?: string): this; - /** - * Asserts that the target is strictly equal to value(===) - */ - equals(value: any, message?: string): this; - /** - * Asserts that the target is strictly equal to value(===) - */ - eq(value: any, message?: string): this; - /** - * Asserts that the target is deeply equal to object - */ - eql(object: any, message?: string): this; - /** - * Asserts that the target is deeply equal to object - */ - eqls(object: any, message?: string): this; - /** - * Asserts that the target has the same length length and elements as array in the same order - */ - eqlArray(array: any[], message?: string): this; - /** - * Asserts that target > n - */ - above(n: number, message?: string): this; - /** - * Asserts that target > n - */ - gt(n: number, message?: string): this; - /** - * Asserts that target > n - */ - greaterThan(n: number, message?: string): this; - /** - * Asserts that target >= n - */ - least(n: number, message?: string): this; - /** - * Asserts that target >= n - */ - gte(n: number, message?: string): this; - /** - * Asserts that target < n - */ - below(n: number, message?: string): this; - /** - * Asserts that target < n - */ - lt(n: number, message?: string): this; - /** - * Asserts that target < n - */ - lessThan(n: number, message?: string): this; - /** - * Asserts that target <= n - */ - most(n: number, message?: string): this; - /** - * Asserts that target <= n - */ - lte(n: number, message?: string): this; - /** - * Asserts that start <= target <= end - */ - within(start: number, end: number, message?: string): this; - /** - * Asserts that the target is an instance of constructor - */ - instanceof(constructor: object, message?: string): this; - /** - * Asserts that the target is an instance of constructor - */ - instanceOf(constructor: object, message?: string): this; - /** - * Asserts that the target has a property name `name` with value `value` - */ - property(name: string, value?: any, message?: string): this; - /** - * Asserts that the target has its own property name `name` with value `value` - */ - ownProperty(name: string, value?: any, message?: string): this; - /** - * Asserts that the target has its own property name `name` with value `value` - */ - haveOwnProperty(name: string, value?: any, message?: string): this; - /** - * Asserts that the target has its own property descriptor with name `name` and value `value` - */ - ownPropertyDescriptor(name: string, descriptor?: object, message?: string): this; - /** - * Asserts that the target has its own property descriptor with name `name` and value `value` - */ - haveOwnPropertyDescriptor(name: string, descriptor?: object, message?: string): this; - /** - * Asserts that the target's property length equal to n - */ - length(n: number, message?: string): this; - /** - * Asserts that the target's property length equal to n - */ - lengthOf(n: number, message?: string): this; - /** - * Asserts that the target matches the regular expression regExp - */ - match(regExp: RegExp, message?: string): this; - /** - * Asserts that the target matches the regular expression regExp - */ - matches(regExp: RegExp, message?: string): this; - /** - * Asserts that the target contains str as a substring - */ - string(str: string, message?: string): this; - /** - * Assert that the target has the given keys - */ - key(key: string | string[] | object): this; - key(...keys: string[]): this; - /** - * Assert that the target has the given keys - */ - keys(key: string | string[] | object): this; - keys(...keys: string[]): this; - /** - * Assert that the target throws an error - */ - throw(errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): this; - /** - * Assert that the target throws an error - */ - throws(errorLike?: object, errMsgMatcher?: string | RegExp, message?: string): this; - /** - * Assert that the target throws an error - */ - Throw(errorLike?: Error, errMsgMatcher?: string | RegExp): this; - /** - * Assert that the target has a method with name `method`. For functions checks the prototype - */ - respondTo(method: string, message?: string): this; - /** - * Assert that the target has a method with name `method`. For functions checks the prototype - */ - respondsTo(method: string, message?: string): this; - /** - * Makes respondsTo behave like the target is not a function - */ - itself: this; - /** - * Asserts that matches returns a truthy value with the target as the first argument - */ - satisfy(matcher: () => boolean, message?: string): this; - /** - * Asserts that matches returns a truthy value with the target as the first argument - */ - satisfies(matcher: () => boolean, message?: string): this; - /** - * Asserts that the target is expected +/- delta - */ - closeTo(expected: number, delta: number, message?: string): this; - /** - * Asserts that the target is expected +/- delta - */ - approximately(expected: number, delta: number, message?: string): this; - /** - * Asserts that the target array has the same members as the given - */ - members(set: any[], message?: string): this; - /** - * Asserts that the target is the member of list - */ - oneOf(list: any[], message?: string): this; - /** - * Asserts that fn returns a different value after the target's invokation than before - */ - change(fn: () => any, message?: string): this; - /** - * Asserts that the target's invokation changes subject's property - */ - change(subject: object, property: string, message?: string): this; - /** - * Asserts that fn returns a different value after the target's invokation than before - */ - changes(fn: () => any, message?: string): this; - /** - * Asserts that the target's invokation changes subject's property - */ - changes(subject: object, property: string, message?: string): this; - /** - * Asserts that fn returns a greater number after the target's invokation than before - */ - increase(fn: () => number, message?: string): this; - /** - * Asserts that the target's invokation increases subject's property - */ - increase(subject: object, property?: string, message?: string): this; - /** - * Asserts that fn returns a greater number after the target's invokation than before - */ - increases(fn: () => number, message?: string): this; - /** - * Asserts that the target's invokation increases subject's property - */ - increases(subject: object, property?: string, message?: string): this; - /** - * Asserts that fn returns a lesser number after the target's invokation than before - */ - decrease(fn: () => number, message?: string): this; - /** - * Asserts that the target's invokation decreases subject's property - */ - decrease(subject: object, property?: string, message?: string): this; - /** - * Asserts that fn returns a lesser number after the target's invokation than before - */ - decreases(fn: () => number, message?: string): this; - /** - * Asserts that the target's invokation decreases subject's property - */ - decreases(subject: object, property?: string, message?: string): this; - /** - * Asserts that the value was decreased/increased by delta - */ - by(delta: number, message?: string): this; - /** - * Asserts that the target is extensible - */ - extensible: this; - /** - * Asserts that the target is sealed - */ - sealed: this; - /** - * Asserts that the target is frozen - */ - frozen: this; - /** - * Asserts that the target is a finite number - */ - finite: this; - } - - interface MockAssertions extends Assertion { - /** - * Asserts that the spy has been called - */ - called: this; - /** - * Asserts that the spy has been called n times - */ - callCount(n: number): this; - /** - * Asserts that the spy has been called once - */ - calledOnce: this; - /** - * Asserts that the spy has been called twice - */ - calledTwice: this; - /** - * Asserts that the spy has been been called with `new` - */ - calledThrice: this; - /** - * Asserts that the spy has been called before anotherSpy - */ - calledBefore(anotherSpy: adone.shani.util.I.Spy): this; - /** - * Asserts that the spy has been called after anotherSpy - */ - calledAfter(anotherSpy: adone.shani.util.I.Spy): this; - /** - * Asserts that the spy has been called immediately before anotherSpy - */ - calledImmediatelyBefore(anotherSpy: adone.shani.util.I.Spy): this; - /** - * Asserts that the spy has been called immediately after anotherSpy - */ - calledImmediatelyAfter(anotherSpy: adone.shani.util.I.Spy): this; - /** - * Asserts that the spy has been called with context as this value - */ - calledOn(context: object): this; - /** - * Asserts that the spy has been called with the given arguments - */ - calledWith(...args: any[]): this; - /** - * Asserts that the spy has been called exactly with the given arguments - */ - calledWithExactly(...args: any[]): this; - /** - * Asserts that the spy has been called with matching arguments - */ - calledWithMatch(...args: any[]): this; - /** - * Asserts that the spy returned value - */ - returned(value: any): this; - /** - * Asserts that the spy threw error - */ - thrown(error: any): this; - /** - * Asserts that the spy threw error - */ - threw(error: any): this; - } + const config: I.Config; + const use: I.UseFunction; + const loadMockInterface: I.LoadInterfaceFunction; + const loadExpectInterface: I.LoadInterfaceFunction; + const loadAssertInterface: I.LoadInterfaceFunction; + const assert: I.AssertFunction; + const expect: I.ExpectFunction; } - - class AssertionError extends adone.x.Exception { - constructor(message?: string, props?: object, ssf?: object) - } - - const config: I.Config; - const use: I.UseFunction; - const loadMockInterface: I.LoadInterfaceFunction; - const loadExpectInterface: I.LoadInterfaceFunction; - const loadAssertInterface: I.LoadInterfaceFunction; - const assert: I.AssertFunction; - const expect: I.ExpectFunction; } diff --git a/types/adone/glosses/collections.d.ts b/types/adone/glosses/collections.d.ts new file mode 100644 index 0000000000..c21c13abb9 --- /dev/null +++ b/types/adone/glosses/collections.d.ts @@ -0,0 +1,1966 @@ +declare namespace adone { + namespace collection { + namespace I.LinkedList { + /** + * Represents the node of a linked list + */ + interface Node { + /** + * The next node + */ + next?: Node; + + /** + * The previous node + */ + prev?: Node; + + /** + * The value this node contains + */ + value: T; + } + } + + /** + * Represents a linked list + */ + class LinkedList { + /** + * The maximum length of the list + */ + readonly maxLength: number; + + /** + * Current length of the list + */ + readonly length: number; + + /** + * Whether the list is autoresizable + */ + readonly autoresize: boolean; + + /** + * @param maxLength Maximum length of the linked list + */ + constructor(maxLength?: number); + + /** + * Whether the list is full + */ + readonly full: boolean; + + /** + * Whether the list is empty + */ + readonly empty: boolean; + + /** + * Resizes the list + */ + resize(newLength: number): this; + + /** + * Adds a new node to the end + * + * @returns Added node + */ + push(value: T): I.LinkedList.Node; + + /** + * Removes the last node, returns undefined if the list is empty + */ + pop(): T | undefined; + + /** + * Removes the first node, returns undefined if the list is empty + */ + shift(): T | undefined; + + /** + * Inserts a new node at the beginning of the list + * + * @returns Added node + */ + unshift(value: T): I.LinkedList.Node; + + /** + * Moves the given node to the end of the list + */ + pushNode(node: I.LinkedList.Node): void; + + /** + * Moved the given node to the beginning of the list + */ + unshiftNode(node: I.LinkedList.Node): void; + + /** + * Removes the given node from the list + */ + removeNode(node: I.LinkedList.Node): void; + + /** + * Clears the list + * + * @param strong Whether to reset all the node's values + */ + clear(strong?: boolean): void; + + /** + * Convers the list to an array + */ + toArray(): T[]; + + /** + * The first element of the list + */ + readonly front: T; + + /** + * The last element of the list + */ + readonly back: T; + + /** + * Returns an iterator over the list elements + */ + [Symbol.iterator](): IterableIterator; + + /** + * Returns the next node for the given node + */ + nextNode(node: I.LinkedList.Node): I.LinkedList.Node; + + /** + * Maps this linked list to a new one using the given function + */ + map(fn: (value: T, index: number) => R): LinkedList; + + /** + * Invokes the given callback for each value from the beginning to the end (much faster than for-of). + * If the given function returns false it stops iterating. + */ + forEach(callback: (value: T, index: number) => void | boolean): void; + + /** + * Default length of a new created linked list + */ + static DEFAULT_LENGTH: number; + } + + namespace I { + type Long = math.Long; + + type Longable = math.I.Longable; + + namespace ByteArray { + interface Varint32 { + value: number; + length: number; + } + + interface Varint64 { + value: Long; + length: number; + } + + interface String { + string: string; + length: number; + } + + type Wrappable = string | ByteArray | Buffer | Uint8Array | ArrayBuffer; + + type Metrics = "b" | "c"; + } + } + + /** + * Represents an array of bytes, enhanced Node.js Buffer + */ + class ByteArray { + /** + * Constructs a new ByteArray + * + * @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64) + * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) + */ + constructor(capacity?: number, noAssert?: boolean); + + /** + * Reads a BitSet as an array of booleans. + * + * @param offset Offset to read from. Will use and increase offset by length if omitted. + */ + readBitSet(offset?: number): boolean[]; + + /** + * Reads the specified number of bytes. + * + * @param length Number of bytes to read + * @param offset Offset to read from. Will use and increase offset by length if omitted. + */ + read(length: number, offset?: number): ByteArray; + + /** + * Reads an 8bit signed integer + * + * @param offset Offset to read from + */ + readInt8(offset?: number): number; + + /** + * Reads an 8bit unsigned integer + * + * @param offset Offset to read from + */ + readUInt8(offset?: number): number; + + /** + * Reads a 16bit signed le integer + * + * @param offset Offset to read from + */ + readInt16LE(offset?: number): number; + + /** + * Reads a 16bit unsigned le integer + * + * @param offset Offset to read from + */ + readUInt16LE(offset?: number): number; + + /** + * Reads a 16bit signed be integer + * + * @param offset Offset to read from + */ + readInt16BE(offset?: number): number; + + /** + * Reads a 16bit unsigned be integer + * + * @param offset Offset to read from + */ + readUInt16BE(offset?: number): number; + + /** + * Reads a 32bit signed le integer + * + * @param offset Offset to read from + */ + readInt32LE(offset?: number): number; + + /** + * Reads a 32bit unsigned le integer + * + * @param offset Offset to read from + */ + readUInt32LE(offset?: number): number; + + /** + * Reads a 32bit signed be integer + * + * @param offset Offset to read from + */ + readInt32BE(offset?: number): number; + + /** + * Reads a 32bit unsigned be integer + * + * @param offset Offset to read from + */ + readUInt32BE(offset?: number): number; + + /** + * Reads a 64bit signed le integer as math.Long + * + * @param offset Offset to read from + */ + readInt64LE(offset?: number): math.Long; + + /** + * Reads a 64bit unsigned le integer as math.Long + * + * @param offset Offset to read from + */ + readUInt64LE(offset?: number): math.Long; + + /** + * Reads a 64bit signed be integer as math.Long + * + * @param offset Offset to read from + */ + readInt64BE(offset?: number): math.Long; + + /** + * Reads a 64bit unsigned be integer as math.Long + * + * @param offset Offset to read from + */ + readUInt64BE(offset?: number): math.Long; + + /** + * Reads a 32bit le float + * + * @param offset Offset to read from + */ + readFloatLE(offset?: number): number; + + /** + * Reads a 32bit be float + * + * @param offset Offset to read from + */ + readFloatBE(offset?: number): number; + + /** + * Reads a 64bit le float + * + * @param offset Offset to read from + */ + readDoubleLE(offset?: number): number; + + /** + * Reads a 64bit be float + * + * @param offset Offset to read from + */ + readDoubleBE(offset?: number): number; + + /** + * Appends some data to this ByteArray. + * This will overwrite any contents behind the specified offset up to the appended data's length. + * + * @param source The source write from + * @param offset Offset to write to + * @param length length to read from the source + * @param encoding encoding to use for wrapping the source in bytearray + */ + write(source: I.ByteArray.Wrappable, offset?: number, length?: number, encoding?: string): this; + + /** + * Writes the array as a bitset. + * @param value Array of booleans to write + */ + writeBitSet(value: number[]): this; + + /** + * Writes the array as a bitset. + * @param value Array of booleans to write + * @param offset Offset to write to + */ + writeBitSet(value: number[], offset: number): number; + + /** + * Writes an 8bit signed integer + * + * @param offset Offset to write to + */ + writeInt8(value: number, offset?: number): this; + + /** + * Writes an 8bit unsigned integer + * + * @param offset Offset to write to + */ + writeUInt8(value: number, offset?: number): this; + + /** + * Writes a 16bit signed le integer + * + * @param offset Offset to write to + */ + writeInt16LE(value: number, offset?: number): this; + + /** + * Writes a 16bit signed be integer + * + * @param offset Offset to write to + */ + writeInt16BE(value: number, offset?: number): this; + + /** + * Writes a 16bit unsigned le integer + * + * @param offset Offset to write to + */ + writeUInt16LE(value: number, offset?: number): this; + + /** + * Writes a 16bit unsigned be integer + * + * @param offset Offset to write to + */ + writeUInt16BE(value: number, offset?: number): this; + + /** + * Writes a 32bit signed le integer + * + * @param offset Offset to write to + */ + writeInt32LE(value: number, offset?: number): this; + + /** + * Writes a 32bit signed be integer + * + * @param offset Offset to write to + */ + writeInt32BE(value: number, offset?: number): this; + + /** + * Writes a 32bit unsigned le integer + * + * @param offset Offset to write to + */ + writeUInt32LE(value: number, offset?: number): this; + + /** + * Writes a 32bit unsigned be integer + * + * @param offset Offset to write to + */ + writeUInt32BE(value: number, offset?: number): this; + + /** + * Writes a 64bit signed le long integer + * + * @param offset Offset to write to + */ + writeInt64LE(value: math.Long | string | number, offset?: number): this; + + /** + * Writes a 64bit signed be long integer + * + * @param offset Offset to write to + */ + writeInt64BE(value: math.Long | string | number, offset?: number): this; + + /** + * Writes a 64bit unsigned le long integer + * + * @param offset Offset to write to + */ + writeUInt64LE(value: math.Long | string | number, offset?: number): this; + + /** + * Writes a 64bit unsigned be long integer + * + * @param offset Offset to write to + */ + writeUInt64BE(value: math.Long | string | number, offset?: number): this; + + /** + * Writes a 32bit le float + * + * @param offset Offset to write to + * @returns {this} + */ + writeFloatLE(value: number, offset?: number): this; + + /** + * Writes a 32bit be float + * + * @param offset Offset to write to + */ + writeFloatBE(value: number, offset?: number): this; + + /** + * Writes a 64bit le float + * + * @param offset Offset to write to + */ + writeDoubleLE(value: number, offset?: number): this; + + /** + * Writes a 64bit be float + * + * @param offset Offset to write to + */ + writeDoubleBE(value: number, offset?: number): this; + + /** + * Writes a 32bit base 128 variable-length integer + */ + writeVarint32(value: number): this; + + /** + * Writes a 32bit base 128 variable-length integer + * + * @param offset Offset to write to + */ + writeVarint32(value: number, offset: number): number; + + /** + * Writes a zig-zag encoded 32bit base 128 variable-length integer + */ + writeVarint32ZigZag(value: number): this; + + /** + * Writes a zig-zag encoded 32bit base 128 variable-length integer + * + * @param offset Offset to write to + */ + writeVarint32ZigZag(value: number, offset: number): number; + + /** + * Reads a 32bit base 128 variable-length integer + */ + readVarint32(): number; + + /** + * Reads a 32bit base 128 variable-length integer + * + * @param offset Offset to read from + */ + readVarint32(offset: number): I.ByteArray.Varint32; + + /** + * Reads a zig-zag encoded 32bit base 128 variable-length integer + */ + readVarint32ZigZag(): number; + + /** + * Reads a zig-zag encoded 32bit base 128 variable-length integer + * + * @param offset Offset to read from + */ + readVarint32ZigZag(offset: number): I.ByteArray.Varint32; + + /** + * Writes a 64bit base 128 variable-length integer + */ + writeVarint64(value: math.Long | string | number): this; + + /** + * Writes a 64bit base 128 variable-length integer + * + * @param offset Offset to write to + */ + writeVarint64(value: math.Long | string | number, offset: number): number; + + /** + * Writes a zig-zag encoded 64bit base 128 variable-length integer + */ + writeVarint64ZigZag(value: math.Long | string | number): this; + + /** + * Writes a zig-zag encoded 64bit base 128 variable-length integer + * + * @param offset Offset to write to + */ + writeVarint64ZigZag(value: math.Long | string | number, offset: number): number; + + /** + * Reads a 64bit base 128 variable-length integer + */ + readVarint64(): I.Long; + + /** + * Reads a 64bit base 128 variable-length integer + * + * @param offset Offset to read from + */ + readVarint64(offset: number): I.ByteArray.Varint64; + + /** + * Reads a zig-zag encoded 64bit base 128 variable-length integer + */ + readVarint64ZigZag(): math.Long; + + /** + * Reads a zig-zag encoded 64bit base 128 variable-length integer + * + * @param offset Offset to read from + */ + readVarint64ZigZag(offset: number): I.ByteArray.Varint64; + + /** + * Writes a NULL-terminated UTF8 encoded string. + * For this to work the specified string must not contain any NULL characters itself + */ + writeCString(str: string): this; + + /** + * Writes a NULL-terminated UTF8 encoded string. + * For this to work the specified string must not contain any NULL characters itself + * + * @param offset Offset to write to + */ + writeCString(str: string, offset: number): number; + + /** + * Reads a NULL-terminated UTF8 encoded string. + * For this to work the string read must not contain any NULL characters itself + */ + readCString(): string; + + /** + * Reads a NULL-terminated UTF8 encoded string. + * For this to work the string read must not contain any NULL characters itself + * + * @param offset Offset to read from + */ + readCString(offset: number): I.ByteArray.String; + + /** + * Writes an UTF8 encoded string + */ + writeString(str: string): this; + + /** + * Writes an UTF8 encoded string + * + * @param offset Offset to write to + */ + writeString(str: string, offset: number): number; + + /** + * Reads an UTF8 encoded string + * + * @param length Number of characters or bytes to read + * @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c") + */ + readString(length: number, metrics?: I.ByteArray.Metrics): string; + + /** + * Reads an UTF8 encoded string + * + * @param length Number of characters or bytes to read + * @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c") + * @param offset Offset to read from + */ + readString(length: number, metrics: I.ByteArray.Metrics, offset: number): I.ByteArray.String; + + /** + * Reads an UTF8 encoded string + * + * @param length Number of characters or bytes to read + * @param offset Offset to read from + */ + readString(length: number, offset: number): I.ByteArray.String; + + /** + * Writes a length as varint32 prefixed UTF8 encoded string + */ + writeVString(str: string): this; + + /** + * Writes a length as varint32 prefixed UTF8 encoded string + * + * @param offset Offset to read from + */ + writeVString(str: string, offset: number): number; + + /** + * Reads a length as varint32 prefixed UTF8 encoded string + */ + readVString(): string; + + /** + * Reads a length as varint32 prefixed UTF8 encoded string + * + * @param offset Offset to read from + */ + readVString(offset: number): I.ByteArray.String; + + /** + * Appends this ByteArray's contents to another ByteArray. + * This will overwrite any contents behind the specified offset up to the length of this ByteArray's data + * + * @param offset Offset to append to + */ + appendTo(target: ByteArray, offset?: number): this; + + /** + * Enables or disables assertions of argument types and offsets. + * Assertions are enabled by default but you can opt to disable them if your code already makes sure that everything is valid + */ + assert(assert?: boolean): this; + + /** + * Gets the capacity of this ByteArray's backing buffer + */ + capacity(): number; + + /** + * Clears this ByteArray's offsets by setting offset to 0 and limit to the backing buffer's capacity + */ + clear(): this; + + /** + * Creates a cloned instance of this ByteArray, + * preset with this ByteArray's values for offset, markedOffset and limit + * + * @param copy Whether to copy the backing buffer or to return another view on the same, false by default + */ + clone(copy?: boolean): ByteArray; + + /** + * Compacts this ByteArray to be backed by a buffer of its contents' length. + * Will set offset = 0 and limit = capacity and adapt markedOffset to the same relative position if set + * + * @param begin Offset to start at, buffer offset by default + * @param end Offset to end at, buffer limit by default + */ + compact(begin?: number, end?: number): this; + + /** + * Creates a copy of this ByteArray's contents. + * + * @param begin Begin offset, buffer offset by default + * @param end End offset, buffer limit by default + */ + copy(begin?: number, end?: number): ByteArray; + + /** + * Copies this ByteArray's contents to another ByteArray. + * + * @param targetOffset Offset to copy to. Will use and increase the target's offset by the number of bytes copied if omitted + * @param sourceOffset Offset to start copying from. Will use and increase offset by the number of bytes copied if omitted + * @param sourceLimit Offset to end copying from, defaults to the buffer limit + */ + copyTo(target: ByteArray, targetOffset?: number, souceOffset?: number, sourceLimit?: number): this | ByteArray; + + /** + * Makes sure that this ByteArray is backed by a ByteArray#buffer of at least the specified capacity. + * If the current capacity is exceeded, it will be doubled. + * If double the current capacity is less than the required capacity, the required capacity will be used instead + */ + ensureCapacity(capacity: number): this; + + /** + * Overwrites this ByteArray's contents with the specified value. + * + * @param value Byte value to fill with. If given as a string, the first character is used + * @param begin Begin offset. Will use and increase offset by the number of bytes written if omitted. defaults to offset + * @param end End offset, defaults to limit. + */ + fill(value: string | number, begin?: number, end?: number): this; + + /** + * Makes this ByteArray ready for a new sequence of write or relative read operations. + * Sets limit = offset and offset = 0. + * Make sure always to flip a ByteArray when all relative read or write operations are complete + */ + flip(): this; + + /** + * Marks an offset on this ByteArray to be used later + * + * @param offset Offset to mark. Defaults to offset. + */ + mark(offset?: number): this; + + /** + * Prepends some data to this ByteArray. + * This will overwrite any contents before the specified offset up to the prepended data's length. + * If there is not enough space available before the specified offset, + * the backing buffer will be resized and its contents moved accordingly + * + * @param source Data to prepend + * @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted. + */ + prepend(source: I.ByteArray.Wrappable, offset: number): this; + + /** + * Prepends some data to this ByteArray. + * This will overwrite any contents before the specified offset up to the prepended data's length. + * If there is not enough space available before the specified offset, + * the backing buffer will be resized and its contents moved accordingly + * + * @param source Data to prepend + * @param encoding Encoding if data is a string + * @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted. + */ + prepend(source: I.ByteArray.Wrappable, encoding?: string, offset?: number): this; + + /** + * Prepends this ByteArray to another ByteArray. + * This will overwrite any contents before the specified offset up to the prepended data's length. + * If there is not enough space available before the specified offset, + * the backing buffer will be resized and its contents moved accordingly + * + * @param offset Offset to prepend at + */ + prependTo(target: ByteArray, offset?: number): this; + + /** + * Gets the number of remaining readable bytes + */ + remaining(): number; + + /** + * Resets this ByteArray's offset. + * If an offset has been marked through mark before, offset will be set to markedOffset, which will then be discarded. + * If no offset has been marked, sets offset = 0 + */ + reset(): this; + + /** + * Resizes this ByteArray to be backed by a buffer of at least the given capacity. + * Will do nothing if already that large or larger. + * + * @param {number} capacity Capacity required + * @returns {this} + */ + resize(capacity: number): this; + + /** + * Reverses this ByteArray's contents. + * + * @param begin Offset to start at, defaults to offset + * @param end Offset to end at, defaults to limit + */ + reverse(begin?: number, end?: number): this; + + /** + * Skips the next length bytes. This will just advance + */ + skip(length: number): this; + + /** + * Slices this ByteArray by creating a cloned instance with offset = begin and limit = end + * + * @param begin Begin offset, defaults to offset + * @param end End offset, defaults to limit + */ + slice(begin?: number, end?: number): ByteArray; + + /** + * Returns a copy of the backing buffer that contains this ByteArray's contents. + * + * @param forceCopy If true returns a copy, otherwise returns a view referencing the same memory if possible, false by default + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toBuffer(forceCopy?: boolean, begin?: number, end?: number): Buffer; + + /** + * Returns a raw buffer compacted to contain this ByteArray's contents + */ + toArrayBuffer(): ArrayBuffer; + + /** + * Converts the ByteArray's contents to a string + * + * @param encoding Output encoding + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toString(encoding?: string, begin?: number, end?: number): string; + + /** + * Encodes this ByteArray's contents to a base64 encoded string + * + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toBase64(begin?: number, end?: number): string; + + /** + * Encodes this ByteArray to a binary encoded string, that is using only characters 0x00-0xFF as bytes + * + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toBinary(begin?: number, end?: number): string; + + /** + * Encodes this ByteArray to a hex encoded string with marked offsets + * + * @param columns If true returns two columns hex + ascii, defaults to false + */ + toDebug(columns?: boolean): string; + + /** + * Encodes this ByteArray's contents to a hex encoded string + * + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toHex(begin?: number, end?: number): string; + + /** + * Encodes this ByteArray's contents to an UTF8 encoded string + * + * @param begin Begin offset, offset by default + * @param end End offset, limit by default + */ + toUTF8(begin?: number, end?: number): string; + + static accessor(): typeof Buffer; + + /** + * Allocates a new ByteArray backed by a buffer of the specified capacity. + * + * @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64) + * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) + */ + static allocate(capacity?: number, noAssert?: boolean): ByteArray; + + /** + * Concatenates multiple ByteArrays into one + * + * @param encoding Encoding for strings + * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) + */ + static concat(buffers: I.ByteArray.Wrappable[], encoding?: string, noAssert?: boolean): ByteArray; + + static type(): typeof Buffer; + + /** + * Wraps a buffer or a string. + * Sets the allocated ByteArray's offset to 0 and its limit to the length of the wrapped data + * + * @param encoding Encoding for strings + * @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false) + */ + static wrap(buffer: I.ByteArray.Wrappable, encoding?: string, noAssert?: boolean): ByteArray; + + /** + * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer + */ + static calculateVarint32(value: number): number; + + /** + * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding + */ + static zigZagEncode32(n: number): number; + + /** + * Decodes a zigzag encoded signed 32bit integer + */ + static zigZagDecode32(n: number): number; + + /** + * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer + */ + static calculateVarint64(value: number | string): number; + + /** + * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding + */ + static zigZagEncode64(value: number | string | I.Long): I.Long; + + /** + * Decodes a zigzag encoded signed 64bit integer. + */ + static zigZagDecode64(value: number | string | I.Long): I.Long; + + /** + * Calculates the number of UTF8 characters of a string. + * JavaScript itself uses UTF-16, + * so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF + */ + static calculateUTF8Chars(str: string): number; + + /** + * Calculates the number of UTF8 bytes of a string. + */ + static calculateString(str: string): number; + + /** + * Decodes a base64 encoded string to a ByteArray + */ + static fromBase64(str: string): ByteArray; + + /** + * Encodes a binary string to base64 like window.btoa does + */ + static btoa(str: string): string; + + /** + * Decodes a base64 encoded string to binary like window.atob does + */ + static atob(b64: string): string; + + /** + * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteArray + */ + static fromBinary(str: string): ByteArray; + + /** + * Decodes a hex encoded string with marked offsets to a ByteArray + */ + static fromDebug(str: string, noAssert?: boolean): ByteArray; + + /** + * Decodes a hex encoded string to a ByteArray + */ + static fromHex(str: string, noAssert?: boolean): ByteArray; + + /** + * Decodes an UTF8 encoded string to a ByteArray + */ + static fromUTF8(str: string, noAssert?: boolean): ByteArray; + + /** + * Default initial capacity + */ + static DEFAULT_CAPACITY: number; + + /** + * Default no assertions flag + */ + static DEFAULT_NOASSERT: boolean; + + /** + * Maximum number of bytes required to store a 32bit base 128 variable-length integer + */ + static MAX_VARINT32_BYTES: number; + + /** + * Maximum number of bytes required to store a 64bit base 128 variable-length integer + */ + static MAX_VARINT64_BYTES: number; + + /** + * Metrics representing number of UTF8 characters. Evaluates to `c`. + */ + static METRICS_CHARS: string; + + /** + * Metrics representing number of bytes. Evaluates to `b`. + */ + static METRICS_BYTES: string; + } + + /** + * Represents a queue + */ + class Queue { + /** + * Whether the queue is full + */ + readonly full: boolean; + + /** + * The length of the queue + */ + readonly length: number; + + /** + * Whether the queue is empty + */ + readonly empty: boolean; + + /** + * Inserts a new element at the end + */ + push(x: S): this; + + /** + * Removes and returns an element from the beginning + */ + pop(): T | undefined; + } + + /** + * Represents an asynchronous queue, each pop is a promise + * that is resolved with an existing element or an element that will be pushed in the future + */ + class AsyncQueue extends Queue> { + /** + * Returns a promise that will be resolved with an existing element or an element that will be pushed in the future + */ + pop(): Promise; + } + + namespace I.PriorityQueue { + interface ConstructorOptions { + /** + * Function that compares objects. + * + * Must return a positive value if a > b, a negative if a < b, and zero for equal objects + */ + compare?(a: T, b: T): number; + + /** + * Function that evaluates the priority value by the given objects, + * if the returned value > 0, then the first argument has higher priority, + * = 0 same priority, < 0 lower priority. + * By default the top element is an element that has the highest priority, + * the default priority function is equal to the compare function + */ + priority?(a: T, b: T): number; + } + } + + /** + * Represents a priority queue + */ + class PriorityQueue { + /** + * Whether the queue is empty + */ + readonly empty: boolean; + + /** + * The length of the queue + */ + readonly length: number; + + constructor(options?: I.PriorityQueue.ConstructorOptions); + + /** + * Clones the queue + */ + clone(): PriorityQueue; + + /** + * Inserts a new element + */ + push(x: T): this; + + /** + * Removes the top element (that has the highest priority) + */ + pop(): T | undefined; + + /** + * Deletes the given element from the queue + */ + delete(x: T): this; + + /** + * Replaces the top element (pop + push) + */ + replace(x: T): T; + + /** + * Faster push + pop + */ + pushpop(x: T): T; + + /** + * Converts the queue to an array, it works with a clone of the queue, so the original queue is untouched + */ + toArray(): T[]; + + /** + * Creates a queue object from the given iterable + */ + static from(iterable: Iterable, options?: I.PriorityQueue.ConstructorOptions): PriorityQueue; + } + + /** + * Represents a faster LRU cache but with less functionality + */ + class FastLRU { + /** + * @param size Cache size, unlimited by default + */ + constructor(size?: number, options?: { + /** + * Function that is called when a value is deleted + */ + dispose?(key: K, value: V): void + }); + + /** + * The actual size of the cache + */ + readonly size: number; + + /** + * Gets the value by the given key + */ + get(key: K): V | undefined; + + /** + * Sets a new value for the given key + */ + set(key: K, value: V): void; + + /** + * Deletes the given key from the cache + */ + delete(key: K): boolean; + + /** + * Checks whether the cache has an element with the given key + */ + has(key: K): boolean; + + /** + * Returns the keys iterator + */ + keys(): IterableIterator; + + /** + * Returns the values iterator + */ + values(): IterableIterator; + + /** + * Returns the entries iterator + */ + entries(): IterableIterator<[K, V]>; + + /** + * Clears the cache + */ + clear(): void; + } + + /** + * Represents a stack + */ + class Stack { + /** + * Whether the stack is empty + */ + readonly empty: boolean; + + /** + * The top element of the stack + */ + readonly top: T; + + /** + * Inserts a new element + */ + push(x: T): this; + + /** + * Removes the top element + */ + pop(): T | undefined; + + /** + * Returns an iterator over the values + */ + [Symbol.iterator](): IterableIterator; + + /** + * Creates a stack and pushed all the values from the given iterable object + */ + static from(iterable: Iterable): Stack; + } + + namespace I.BinarySearchTree { + interface ConstructorOptions { + /** + * The parent tree + */ + parent?: Tree; + + /** + * Value to keep in this node + */ + value?: V; + + /** + * WHether the values must be unique, false by default. + * If false you can store many values for same keys, otherwise only one + */ + unique?: boolean; + + /** + * Custom keys comparator, by default if a > b => -1, a < b -1, a === b => 0 + */ + compareKeys?(a: K, b: K): number; + + /** + * Function that defines whether 2 values are the same, by default a === b + */ + checkValueEquality?(a: V, b: V): boolean; + } + + interface Query { + $lt?: K; + $lte?: K; + $gt?: K; + $gte?: K; + } + } + + /** + * Represents a binary search tree + */ + class BinarySearchTree { + constructor(options?: I.BinarySearchTree.ConstructorOptions>); + + /** + * Returns the max descendant tree + */ + getMaxKeyDescendant(): BinarySearchTree; + + /** + * Returns the maximum key + */ + getMaxKey(): K; + + /** + * Returns the min descendant tree + */ + getMinKeyDescendant(): BinarySearchTree; + + /** + * Returns the minumum key + */ + getMinKey(): K; + + /** + * Traverses the tree and calls the given function for each node + */ + checkAllNodesFullfillCondition(test: (key: K, value: V) => void): void; + + /** + * Checks whether the tree is a binary search tree + */ + checkIsBST(): void; + + /** + * Returns the of keys in the tree + */ + getNumberOfKeys(): number; + + /** + * Inserts a new key/value + */ + insert(key: K, value: V): void; + + /** + * Searches the given key in the tree + */ + search(key: K): V[]; + + /** + * Returns all the values from the given key bounds + */ + betweenBounds(query: I.BinarySearchTree.Query): V[]; + + /** + * Deletes the given key/value from the tree + */ + delete(key: K, value?: V): void; + + /** + * Executed the given callback for each node from left to right + */ + executeOnEveryNode(fn: (tree: BinarySearchTree) => void): void; + + /** + * Prints the tree + */ + prettyPrint(printData?: boolean, spacing?: string): void; + } + + /** + * Represents an AVL tree, a self-balancing binary search tree + */ + class AVLTree { + constructor(options?: I.BinarySearchTree.ConstructorOptions>); + + /** + * Checks whether the tree is an avl tree + */ + checkIsAVLT(): void; + + /** + * Inserts a new key/value + */ + insert(key: K, value: V): void; + + /** + * Deletes the given key/value from the tree + */ + delete(key: K, value?: V): void; + + /** + * Returns the of keys in the tree + */ + getNumberOFKeys(): number; + + /** + * Searches the given key in the tree + */ + search(key: K): V[]; + + /** + * Returns all the values from the given key bounds + */ + betweenBounds(query: I.BinarySearchTree.Query): V[]; + + /** + * Executed the given callback for each node from left to right + */ + executeOnEveryNode(fn: (tree: AVLTree) => void): void; + + /** + * Prints the tree + */ + prettyPrint(printDate?: boolean, spacing?: string): void; + } + + namespace I.RedBlackTree { + interface Node { + /** + * The key associated to the node + */ + key: K; + + /** + * The value associated to the node + */ + value: V; + + /** + * The left subtree of the node + */ + left?: Node; + + /** + * The right subtree of the node + */ + right?: Node; + } + + interface Iterator { + /** + * Checks if the iterator is valid + */ + readonly valid: boolean; + + /** + * The value of the node at the iterator's current position, null if invalid + */ + readonly node: Node | null; + + /** + * The key of the item referenced by the iterator, undefined if invalid + */ + readonly key?: K; + + /** + * The value of the item referenced by the iterator, undefined if invalid + */ + readonly value?: V; + + /** + * Returns the position of this iterator in the sequence + */ + readonly index: number; + + /** + * If true, then the iterator is not at the end of the sequence + */ + readonly hasNext: boolean; + + /** + * If true, then the iterator is not at the beginning of the sequence + */ + readonly hasPrev: boolean; + + /** + * The tree associated to the iterator + */ + tree: RedBlackTree; + + /** + * Makes a copy of the iterator + */ + clone(): Iterator; + + /** + * Removes the item at the position of the iterator and returns a new rb-tree + */ + remove(): RedBlackTree; + + /** + * Advances the iterator to the next position + */ + next(): void; + + /** + * Updates the value of the node in the tree at this iterator and returns a new rb-tree + */ + update(value: V): RedBlackTree; + + /** + * Moves the iterator backward one element + */ + prev(): void; + } + } + + /** + * Represents a fully persistent red-black tree + */ + class RedBlackTree { + /** + * The root node of the tree + */ + root: I.RedBlackTree.Node; + + constructor(compare?: (a: K, b: K) => number, root?: RedBlackTree); + + /** + * A sorted array of all the keys in the tree + */ + readonly keys: K[]; + + /** + * An array of all the values in the tree + */ + readonly values: V[]; + + /** + * The number of items in the tree + */ + readonly length: number; + + /** + * An iterator pointing to the first element in the tree + */ + readonly begin: I.RedBlackTree.Iterator; + + /** + * An iterator pointing to the last element in the tree + */ + readonly end: I.RedBlackTree.Iterator; + + /** + * Creates a new tree with the new pair inserted + */ + insert(key: K, value: V): RedBlackTree; + + /** + * Walks a visitor function over the nodes of the tree in order + * + * @param visit A callback that gets executed on each node. + * If a truthy value is returned from the visitor, then iteration is stopped. + * @param lo An optional start of the range to visit (inclusive) + * @param hi An optional end of the range to visit (non-inclusive) + */ + forEach(visit: (key: K, value: V) => T, lo?: K, hi?: K): T; + + /** + * Finds an iterator starting at the given element + */ + at(idx: number): I.RedBlackTree.Iterator; + + /** + * Finds the first item in the tree whose key is >= key + */ + ge(key: K): I.RedBlackTree.Iterator; + + /** + * Finds the first item in the tree whose key is > key + */ + gt(key: K): I.RedBlackTree.Iterator; + + /** + * Finds the first item in the tree whose key is < key + */ + lt(key: K): I.RedBlackTree.Iterator; + + /** + * Finds the first item in the tree whose key is <= key + */ + le(key: K): I.RedBlackTree.Iterator; + + /** + * Returns an iterator pointing to the first item in the tree with key, otherwise null + */ + find(key: K): I.RedBlackTree.Iterator | null; + + /** + * Removes the first item with key in the tree + */ + remove(key: K): RedBlackTree; + + /** + * Retrieves the value associated to the given key + */ + get(key: K): V | undefined; + } + + /** + * Respresetns a data structure which is a combination of an array and a set. + * Adding a new member is O(1), testing for membership is O(1), + * and finding the index of an element is O(1). + */ + class ArraySet { + /** + * The number of unique items in this ArraySet. + * If duplicates have been added, than those do not count towards the size. + */ + readonly length: number; + + /** + * Adds the given value to this set. + * + * @param allowDuplicates Whether to allow duplicates in the set, false by default + */ + add(value: T, allowDuplicates?: boolean): this; + + /** + * Checks whether the given value is a member of the set + */ + has(value: T): boolean; + + /** + * Returns the index of the given element. + * If the value is not present it will return -1 + */ + indexOf(value: T): number; + + /** + * Converts the set to an array + */ + toArray(): T[]; + + /** + * Creates an ArraySet from the given iterable object + * + * @param allowDuplicates Whether to allow duplicates in the set, false by default + */ + static from(iterable: Iterable, allowDuplicates?: boolean): ArraySet; + } + + namespace I.BufferList { + type Appendable = Buffer | BufferList | string | number | Array; + } + + /** + * Represents a Node.js Buffer list collector, reader and streamer with callback/promise interface support + */ + class BufferList extends std.stream.Duplex implements PromiseLike { + /** + * Creates a new buffer list + */ + constructor(); + + /** + * Creates a new buffer list and initiates with the given value + */ + constructor(buffer: I.BufferList.Appendable); + + /** + * Creates a new buffer list and subscribes the given callback on the end/error event + */ + constructor(callback: (err: any, data: Buffer) => void); + + /** + * Adds an additional buffer or BufferList to the internal list + */ + append(buf: I.BufferList.Appendable): this; + + /** + * Ends the stream + */ + end(chunk?: Buffer): void; + + /** + * Returns the byte at the specified index + */ + get(idx: number): number; + + /** + * Returns a new Buffer object containing the bytes within the range specified. + */ + slice(start?: number, end?: number): Buffer; + + /** + * Copies the content of the list in the dest buffer + * starting from destStart and containing the bytes within the range specified with srcStart to srcEnd + * + * @param dstStart writes from this position + * @param srcStart reads bytes from this position + * @param srcEnd read bytes to this position + */ + copy(dst: T, dstStart?: number, srcStart?: number, srcEnd?: number): T; + + /** + * Returns a new BufferList object containing the bytes within the range specified. + * No copies will be performed. All buffers in the result share memory with the original list. + * + * @param {number} start slice from + * @param {number} end slice to + */ + shallowSlice(start?: number, end?: number): BufferList; + + /** + * Return a string representation of the buffer + */ + toString(encoding?: fs.I.Encoding, start?: number, end?: number): string; + + /** + * Shifts bytes off the start of the list + */ + consume(bytes: number): this; + + /** + * Performs a shallow-copy of the list. + */ + duplicate(): BufferList; + + /** + * Destroys the stream + */ + destroy(): void; + + then( + onfulfilled?: ((value: Buffer) => T1 | PromiseLike) | undefined | null, + onrejected?: ((reason: any) => T2 | PromiseLike) | undefined | null + ): PromiseLike; + + catch(onrejected?: ((reason: any) => T | PromiseLike) | undefined | null): PromiseLike; + } + + /** + * Represents a Map that has a default values factory object or function. + * Each get of non-existent key goes through the factory + */ + class DefaultMap extends Map { + constructor(factory?: ((key: K) => V) | { [key: string]: V }, iterable?: Iterable<[K, V]>); + } + + namespace I.LRU { + type LengthCalculator = (value: V, key: K) => number; + interface ConstructorOptions { + /** + * The maximum size of the cache, checked by applying the length function to all values in the cache. + * Default is Infinity + */ + max?: number; + + /** + * Maximum age in ms. Items are not pro-actively pruned out as they age, + * but if you try to get an item that is too old, + * it'll drop it and return undefined instead of giving it to you + */ + maxAge?: number; + + /** + * Function that is used to calculate the length of stored items + */ + length?: LengthCalculator; + + /** + * Function that is called on items when they are dropped from the cache + */ + dispose?(key: K, value: V): void; + + /** + * Whether to return the stale value before deleting it + */ + stale?: boolean; + + /** + * Dispose will only be called when a key falls out of the cache, not when it is overwritten + */ + noDisposeOnSet?: boolean; + } + + interface SerializedEntry { + /** + * key + */ + key: K; + + /** + * value + */ + value: V; + + /** + * when it becomes expired + */ + e: number; + } + + interface Entry { + /** + * key + */ + key: K; + + /** + * value + */ + value: V; + + /** + * entry length + */ + length: number; + + /** + * Timestamp when the entry was created + */ + now: number; + + /** + * Maximum live time + */ + maxAge: number; + } + } + + /** + * Represent an LRU cache + */ + class LRU { + /** + * Creates an LRU cache of the given size + */ + constructor(max: number); + + /** + * Creates an LRU cache with the given options + */ + constructor(options?: I.LRU.ConstructorOptions); + + /** + * The length of the cache, setter resizes the cache + */ + max: number; + + /** + * stale setting + */ + allowStale: boolean; + + /** + * maxAge setting + */ + maxAge: number; + + /** + * length setting + */ + lengthCalculator: I.LRU.LengthCalculator; + + /** + * Total length of objects in cache taking into account length options function + */ + readonly length: number; + + /** + * Total quantity of objects currently in cache. + * Note, that stale items are returned as part of this item count. + */ + readonly itemCount: number; + + /** + * Iterates over all the keys in the cache, in reverse recent-ness order. (ie, less recently used items are iterated over first.) + */ + rforEach(fn: (this: T, value: V, key: K, cache: LRU) => void, thisp?: T): void; + + /** + * Iterates over all the keys in the cache, in order of recent-ness + */ + forEach(fn: (this: T, value: V, key: K, cache: LRU) => void, thisp?: T): void; + + /** + * Returns an array of the keys in the cache + */ + keys(): K[]; + + /** + * Returns an array of the values in the cache + */ + values(): V[]; + + /** + * Clears the cache entirely, throwing away all values + */ + reset(): void; + + /** + * Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)` + */ + dump(): Array>; + + /** + * Returns an internal lru list of entries + */ + dumpLru(): LinkedList>; + + /** + * @param opts std.util.inspect options + */ + inspect(opts?: object): string; + + /** + * Sets a new value for the given key. Updates the "recently used"-ness of the key + * + * @param maxAge maxAge option specific for this key + * @returns Whether the key was set + */ + set(key: K, value: V, maxAge?: number): boolean; + + /** + * Check if a key is in the cache, without updating the recent-ness or deleting it for being stale + */ + has(key: K): boolean; + + /** + * Gets the value of the given key. Updates the "recently used"-ness of the key + */ + get(key: K): V | undefined; + + /** + * Returns the key value without updating the "recently used"-ness of the key + */ + peek(key: K): V | undefined; + + /** + * Deletes the less recently used element + */ + pop(): I.LRU.Entry; + + /** + * Deletes a key out of the cache + */ + del(key: K): void; + + /** + * Loads another cache entries array, obtained with sourceCache.dump(), into the cache. + * The destination cache is reset before loading new entries + */ + load(arr: Array>): void; + + /** + * Manually iterates over the entire cache proactively pruning old entries + */ + prune(): void; + } + + /** + * Represents a Map that keeps keys only for a specified interval of time + */ + class TimedoutMap extends Map { + /** + * @param timeout maximum age of the keys, 1000 by default + * @param callback callback that is called with each key when the timeout is passed + */ + constructor(timeout?: number, callback?: (key: K) => void); + + /** + * Gets the timeout + */ + getTimeout(): number; + + /** + * Sets the timeout + */ + setTimeout(ms: number): void; + + /** + * Iterates over the map and calls the callback for each element + */ + forEach(callback: (this: T, value: V, key: K, cache: this) => void, thisArg?: T): this; + + /** + * Deletes the given key + */ + delete(key: K): boolean; + } + } +} diff --git a/types/adone/glosses/common.d.ts b/types/adone/glosses/common.d.ts deleted file mode 100644 index 57025ea054..0000000000 --- a/types/adone/glosses/common.d.ts +++ /dev/null @@ -1,465 +0,0 @@ -/** - * predicates - */ -export namespace is { - function _null(obj: any): boolean; - export { _null as null }; - export function undefined(obj: any): boolean; - export function exist(obj: any): boolean; - export function nil(obj: any): boolean; - export function number(obj: any): boolean; - export function numeral(obj: any): boolean; - export function infinite(obj: any): boolean; - export function odd(obj: any): boolean; - export function even(obj: any): boolean; - export function float(obj: any): boolean; - export function negativeZero(obj: any): boolean; - export function string(obj: any): boolean; - export function emptyString(obj: any): boolean; - export function substring(substring: string, string: string, offset?: number): boolean; - export function prefix(prefix: string, string: string): boolean; - export function suffix(suffix: string, string: string): boolean; - export function boolean(obj: any): boolean; - export function json(obj: any): boolean; - export function object(obj: any): boolean; - export function plainObject(obj: any): boolean; - function _class(obj: any): boolean; - export { _class as class }; - export function emptyObject(obj: any): boolean; - export function propertyOwned(obj: any, field: string): boolean; - export function propertyDefined(obj: any, field: string): boolean; - export function conforms(obj: object, schema: object, strict?: boolean): boolean; - export function arrayLikeObject(obj: any): boolean; - export function inArray(value: T, array: any[], offset?: number, comparator?: (a: T, b: T) => boolean): boolean; - export function sameType(value: any, other: any): boolean; - export function primitive(obj: any): boolean; - export function equalArrays(left: any[], right: any[]): boolean; - export function deepEqual(left: any, right: any): boolean; - export function shallowEqual(left: any, right: any): boolean; - export function stream(obj: any): boolean; - export function writableStream(obj: any): boolean; - export function readableStream(obj: any): boolean; - export function duplexStream(obj: any): boolean; - export function transformStream(obj: any): boolean; - export function utf8(obj: Buffer): boolean; - export function win32PathAbsolute(path: string): boolean; - export function posixPathAbsolute(path: string): boolean; - export function pathAbsolute(path: string): boolean; - export function glob(str: string): boolean; - export function dotfile(str: string): boolean; - function _function(obj: any): boolean; - export { _function as function }; - export function asyncFunction(obj: any): boolean; - export function promise(obj: any): boolean; - export function validDate(str: string): boolean; - export function buffer(obj: any): boolean; - export function callback(obj: any): boolean; - export function generator(obj: any): boolean; - export function nan(obj: any): boolean; - export function finite(obj: any): boolean; - export function integer(obj: any): boolean; - export function safeInteger(obj: any): boolean; - export function array(obj: any): boolean; - export function uint8Array(obj: any): boolean; - export function configuration(obj: any): boolean; - export function long(obj: any): boolean; - export function bigNumber(obj: any): boolean; - export function exbuffer(obj: any): boolean; - export function exdate(obj: any): boolean; - export function transform(obj: any): boolean; - export function subsystem(obj: any): boolean; - export function application(obj: any): boolean; - export function logger(obj: any): boolean; - export function coreStream(obj: any): boolean; - export function fastStream(obj: any): boolean; - export function fastFSStream(obj: any): boolean; - export function fastFSMapStream(obj: any): boolean; - export function genesisNetron(obj: any): boolean; - export function genesisPeer(obj: any): boolean; - export function netronAdapter(obj: any): boolean; - export function netron(obj: any): boolean; - export function netronPeer(obj: any): boolean; - export function netronDefinition(obj: any): boolean; - export function netronDefinitions(obj: any): boolean; - export function netronReference(obj: any): boolean; - export function netronInterface(obj: any): boolean; - export function netronContext(obj: any): boolean; - export function netronIMethod(netronInterface: object, name: string): boolean; - export function netronIProperty(netronInterface: any, name: string): boolean; - export function netronStub(obj: any): boolean; - export function netronRemoteStub(obj: any): boolean; - export function netronStream(obj: any): boolean; - export function iterable(obj: any): boolean; - export const windows: boolean; - export const linux: boolean; - export const freebsd: boolean; - export const darwin: boolean; - export const sunos: boolean; - export function uppercase(str: string): boolean; - export function lowercase(str: string): boolean; - export function digits(str: string): boolean; - export function identifier(str: string): boolean; - export function binaryExtension(str: string): boolean; - export function binaryPath(str: string): boolean; - export function ip4(str: string): boolean; - export function ip6(str: string): boolean; - export function arrayBuffer(obj: any): boolean; - export function arrayBufferView(obj: any): boolean; - export function date(obj: any): boolean; - export function error(obj: any): boolean; - export function map(obj: any): boolean; - export function regexp(obj: any): boolean; - export function set(obj: any): boolean; - export function symbol(obj: any): boolean; - export function validUTF8(obj: any): boolean; -} - -export namespace x { - class Exception extends Error { - constructor(message?: string | Error, captureStackTrace?: boolean); - } - class Runtime extends Exception { } - class IncompleteBufferError extends Exception { } - class NotImplemented extends Exception { } - class IllegalState extends Exception { } - class NotValid extends Exception { } - class Unknown extends Exception { } - class NotExists extends Exception { } - class Exists extends Exception { } - class Empty extends Exception { } - class InvalidAccess extends Exception { } - class NotSupported extends Exception { } - class InvalidArgument extends Exception { } - class InvalidNumberOfArguments extends Exception { } - class NotFound extends Exception { } - class Timeout extends Exception { } - class Incorrect extends Exception { } - class NotAllowed extends Exception { } - class LimitExceeded extends Exception { } - class Encoding extends Exception { } - class Network extends Exception { } - class Bind extends Exception { } - class Connect extends Exception { } - class Database extends Exception { } - class DatabaseInitialization extends Exception { } - class DatabaseOpen extends Exception { } - class DatabaseRead extends Exception { } - class DatabaseWrite extends Exception { } - class NetronIllegalState extends Exception { } - class NetronPeerDisconnected extends Exception { } - class NetronTimeout extends Exception { } -} - -export class EventEmitter { - static listenerCount(emitter: EventEmitter, event: string | symbol): number; - static defaultMaxListeners: number; - - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Array<(...args: any[]) => any>; - emit(event: string | symbol, ...args: any[]): boolean; - eventNames(): Array; - listenerCount(type: string | symbol): number; -} - -export class AsyncEmitter extends EventEmitter { - constructor(concurrency?: number); - - setConcurrency(max?: number): this; - - emitParallel(event: string, ...args: any[]): Promise; - - emitSerial(event: string, ...args: any[]): Promise; - - emitReduce(event: string, ...args: any[]): Promise; - - emitReduceRight(event: string, ...args: any[]): Promise; - - subscribe(event: string, listener: (...args: any[]) => void, once?: boolean): () => void; -} - -declare namespace I { - type Long = adone.math.Long; - - type Longable = adone.math.I.Longable; - - namespace ExBuffer { - interface Varint32 { - value: number; - length: number; - } - - interface Varint64 { - value: Long; - length: number; - } - - interface String { - string: string; - length: number; - } - - type Wrappable = string | ExBuffer | Buffer | Uint8Array | ArrayBuffer; - - type METRICS = "b" | "c"; - } -} - -export class ExBuffer { - constructor(capacity?: number, noAssert?: boolean); - - readBitSet(offset?: number): number[]; - - read(length: number, offset?: number): ExBuffer; - - readInt8(offset?: number): number; - - readUInt8(offset?: number): number; - - readInt16LE(offset?: number): number; - - readUInt16LE(offset?: number): number; - - readInt16BE(offset?: number): number; - - readUInt16BE(offset?: number): number; - - readInt32LE(offset?: number): number; - - readUInt32LE(offset?: number): number; - - readInt32BE(offset?: number): number; - - readUInt32BE(offset?: number): number; - - readInt64LE(offset?: number): adone.math.Long; - - readUInt64LE(offset?: number): adone.math.Long; - - readInt64BE(offset?: number): adone.math.Long; - - readUInt64BE(offset?: number): adone.math.Long; - - readFloatLE(offset?: number): number; - - readFloatBE(offset?: number): number; - - readDoubleLE(offset?: number): number; - - readDoubleBE(offset?: number): number; - - write(source: I.ExBuffer.Wrappable, offset?: number, length?: number, encoding?: string): this; - - writeBitSet(value: number[]): this; - - writeBitSet(value: number[], offset: number): number; - - writeInt8(value: number, offset?: number): this; - - writeUInt8(value: number, offset?: number): this; - - writeInt16LE(value: number, offset?: number): this; - - writeInt16BE(value: number, offset?: number): this; - - writeUInt16LE(value: number, offset?: number): this; - - writeUInt16BE(value: number, offset?: number): this; - - writeInt32LE(value: number, offset?: number): this; - - writeInt32BE(value: number, offset?: number): this; - - writeUInt32LE(value: number, offset?: number): this; - - writeUInt32BE(value: number, offset?: number): this; - - writeInt64LE(value: I.Longable, offset?: number): this; - - writeInt64BE(value: I.Longable, offset?: number): this; - - writeUInt64LE(value: I.Longable, offset?: number): this; - - writeUInt64BE(value: I.Longable, offset?: number): this; - - writeFloatLE(value: number, offset?: number): this; - - writeFloatBE(value: number, offset?: number): this; - - writeDoubleLE(value: number, offset?: number): this; - - writeDoubleBE(value: number, offset?: number): this; - - writeVarint32(value: number): this; - - writeVarint32(value: number, offset: number): number; - - writeVarint32ZigZag(value: number): this; - - writeVarint32ZigZag(value: number, offset: number): number; - - readVarint32(): number; - - readVarint32(offset: number): I.ExBuffer.Varint32; - - readVarint32ZigZag(): number; - - readVarint32ZigZag(offset: number): I.ExBuffer.Varint32; - - writeVarint64(value: I.Longable): this; - - writeVarint64(value: I.Longable, offset: number): number; - - writeVarint64ZigZag(value: I.Longable): this; - - writeVarint64ZigZag(value: I.Longable, offset: number): number; - - readVarint64(): I.Long; - - readVarint64(offset: number): I.ExBuffer.Varint64; - - readVarint64ZigZag(): adone.math.Long; - - readVarint64ZigZag(offset: number): I.ExBuffer.Varint64; - - writeCString(str: string): this; - - writeCString(str: string, offset: number): number; - - readCString(): string; - - readCString(offset: number): I.ExBuffer.String; - - writeString(str: string): this; - - writeString(str: string, offset: number): number; - - readString(length: number, metrics?: I.ExBuffer.METRICS): string; - - readString(length: number, metrics: I.ExBuffer.METRICS, offset: number): I.ExBuffer.String; - - readString(length: number, offset: number): I.ExBuffer.String; - - writeVString(str: string): this; - - writeVString(str: string, offset: number): number; - - readVString(): string; - - readVString(offset: number): I.ExBuffer.String; - - appendTo(target: ExBuffer, offset?: number): this; - - assert(assert?: boolean): this; - - capacity(): number; - - clear(): this; - - compact(begin?: number, end?: number): this; - - copy(begin?: number, end?: number): ExBuffer; - - copyTo(target: ExBuffer, targetOffset?: number, souceOffset?: number, sourceLimit?: number): this | ExBuffer; - - ensureCapacity(capacity: number): this; - - fill(value: string | number, begin?: number, end?: number): this; - - flip(): this; - - mark(offset?: number): this; - - prepend(source: I.ExBuffer.Wrappable, encoding?: string, offset?: number): this; - - prepend(source: I.ExBuffer.Wrappable, offset: number): this; - - prependTo(target: ExBuffer, offset?: number): this; - - remaining(): number; - - reset(): this; - - resize(capacity: number): this; - - reverse(begin?: number, end?: number): this; - - skip(length: number): this; - - slice(begin?: number, end?: number): ExBuffer; - - toBuffer(forceCopy?: boolean, begin?: number, end?: number): Buffer; - - toArrayBuffer(): ArrayBuffer; - - toString(encoding?: string, begin?: number, end?: number): string; - - toBase64(begin?: number, end?: number): string; - - toBinary(begin?: number, end?: number): string; - - toDebug(columns?: boolean): string; - - toHex(begin?: number, end?: number): string; - - toUTF8(begin?: number, end?: number): string; - - static accessor(): typeof Buffer; - - static allocate(capacity?: number, noAssert?: boolean): ExBuffer; - - static concat(buffers: I.ExBuffer.Wrappable[], encoding?: string, noAssert?: boolean): ExBuffer; - - static type(): typeof Buffer; - - static wrap(buffer: I.ExBuffer.Wrappable, encoding?: string, noAssert?: boolean): ExBuffer; - - static calculateVarint32(value: number): number; - - static zigZagEncode32(n: number): number; - - static zigZagDecode32(n: number): number; - - static calculateVarint64(value: number | string): number; - - static zigZagEncode64(value: number | string | I.Long): I.Long; - - static zigZagDecode64(value: number | string | I.Long): I.Long; - - static calculateUTF8Chars(str: string): number; - - static calculateString(str: string): number; - - static fromBase64(str: string): ExBuffer; - - static btoa(str: string): string; - - static atob(b64: string): string; - - static fromBinary(str: string): ExBuffer; - - static fromDebug(str: string, noAssert?: boolean): ExBuffer; - - static fromHex(str: string, noAssert?: boolean): ExBuffer; - - static fromUTF8(str: string, noAssert?: boolean): ExBuffer; - - static DEFAULT_CAPACITY: number; - - static DEFAULT_NOASSERT: boolean; - - static MAX_VARINT32_BYTES: number; - - static MAX_VARINT64_BYTES: number; - - static METRICS_CHARS: string; - - static METRICS_BYTES: string; -} diff --git a/types/adone/glosses/compressors.d.ts b/types/adone/glosses/compressors.d.ts new file mode 100644 index 0000000000..963eddc99d --- /dev/null +++ b/types/adone/glosses/compressors.d.ts @@ -0,0 +1,1137 @@ +declare namespace adone { + /** + * Various compressors + */ + namespace compressor { + namespace I { + namespace zlib { + type TypedArray = Int8Array | Uint8Array + | Uint8ClampedArray + | Int16Array | Uint16Array + | Int32Array | Uint32Array + | Float32Array | Float64Array; + + interface CommonOptions { + flush?: number; + finishFlush?: number; + chunkSize?: number; + + /** + * The base two logarithm of the window size (the size of the history buffer). + * It should be in the range 8..15. + * Larger values of this parameter result in better compression at the expense of memory usage. + */ + windowBits?: number; + } + + interface CompressStreamOptions extends CommonOptions { + /** + * The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + * 1 gives best speed, + * 9 gives best compression, + * 0 gives no compression at all (the input data is simply copied a block at a time). + * Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6) + */ + level?: number; + + /** + * How much memory should be allocated for the internal compression state + * + * memLevel=1 uses minimum memory but is slow and reduces compression ratio + * + * memLevel=9 uses maximum memory for optimal speed + */ + memLevel?: number; + + /** + * Used to tune the compression algorithm. + * + * Use the value Z_DEFAULT_STRATEGY for normal data, + * Z_FILTERED for data produced by a filter (or predictor), + * Z_HUFFMAN_ONLY to force Huffman encoding only (no string match), + * or Z_RLE to limit match distances to one (run-length encoding). + */ + strategy?: number; + } + + type DecompressStreamOptions = CommonOptions; + + interface CompressOptions extends CompressStreamOptions { + /** + * If true, returns an object with buffer and engine + */ + info?: boolean; + } + + interface DecompressOptions extends DecompressStreamOptions { + /** + * If true, returns an object with buffer and engine + */ + info?: boolean; + } + + interface Info { + buffer: Buffer; + engine: T; + } + + type GzipInfo = Info; + + type GunzipInfo = Info; + + type DeflateInfo = Info; + + type DeflateRawInfo = Info; + + type InflateInfo = Info; + + type InflateRawInfo = Info; + } + } + /** + * GZIP compressor + */ + namespace gz { + /** + * Compresses the given string or buffer + */ + function compress(buf: string | Buffer, options: I.zlib.CompressOptions & { info: true }): Promise; + + /** + * Compresses the given string or buffer + */ + function compress(buf: string | Buffer, options?: I.zlib.CompressOptions): Promise; + + /** + * Synchronously compreses the given string or buffer + */ + function compressSync(buf: string | Buffer, options: I.zlib.CompressOptions & { info: true }): I.zlib.GzipInfo; + + /** + * Synchronously compreses the given string or buffer + */ + function compressSync(buf: string | Buffer, options?: I.zlib.CompressOptions): Buffer; + + /** + * Creates a compress stream + */ + function compressStream(options?: I.zlib.CompressStreamOptions): nodestd.zlib.Gzip; + + /** + * Decompresses the given string or buffer + */ + function decompress(buf: string | Buffer, options: I.zlib.DecompressOptions & { info: true }): Promise; + + /** + * Decompresses the given string or buffer + */ + function decompress(buf: string | Buffer, options?: I.zlib.DecompressOptions): Promise; + + /** + * Synchronously decompresses the given string or buffer + */ + function decompressSync(buf: string | Buffer, options: I.zlib.DecompressOptions & { info: true }): I.zlib.GunzipInfo; + + /** + * Synchronously decompresses the given string or buffer + */ + function decompressSync(buf: string | Buffer, options?: I.zlib.DecompressOptions): Buffer; + + /** + * Creates a decompress stream + */ + function decompressStream(options?: I.zlib.DecompressStreamOptions): nodestd.zlib.Gunzip; + + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + } + + /** + * Deflate compressor + */ + namespace deflate { + namespace I { + interface CompressStreamOptions extends compressor.I.zlib.CompressStreamOptions { + dictionary?: Buffer | DataView | compressor.I.zlib.TypedArray; + } + + interface DecompressStreamOptions extends compressor.I.zlib.DecompressStreamOptions { + dictionary?: Buffer | DataView | compressor.I.zlib.TypedArray; + } + + interface CompressOptions extends CompressStreamOptions { + /** + * If true, returns an object with buffer and engine + */ + info?: boolean; + } + + interface DecompressOptions extends DecompressStreamOptions { + /** + * If true, returns an object with buffer and engine + */ + info?: boolean; + } + + type DeflateInfo = compressor.I.zlib.DeflateInfo; + + type DeflateRawInfo = compressor.I.zlib.DeflateRawInfo; + + type InflateInfo = compressor.I.zlib.InflateInfo; + + type InflateRawInfo = compressor.I.zlib.InflateRawInfo; + } + + /** + * Compresses the given string or buffer + */ + function compress(buf: string | Buffer, options: I.CompressOptions & { info: true }): Promise; + + /** + * Compresses the given string or buffer + */ + function compress(buf: string | Buffer, options?: I.CompressOptions): Promise; + + /** + * Synchronously compresses the given string or buffer + */ + function compressSync(buf: string | Buffer, options: I.CompressOptions & { info: true }): I.DeflateInfo; + + /** + * Synchronously compresses the given string or buffer + */ + function compressSync(buf: string | Buffer, options?: I.CompressOptions): Buffer; + + /** + * Creates a compress stream + */ + function compressStream(options?: I.CompressStreamOptions): nodestd.zlib.Deflate; + + /** + * Compresses data using deflate, and does not append a zlib header + */ + function rawCompress(buf: string | Buffer, options: I.CompressOptions & { info: true }): Promise; + + /** + * Compresses data using deflate, and does not append a zlib header + */ + function rawCompress(buf: string | Buffer, options?: I.CompressOptions): Promise; + + /** + * Synchronously compresses data using deflate, and does not append a zlib header + */ + function rawCompressSync(buf: string | Buffer, options: I.CompressOptions & { info: true }): I.DeflateRawInfo; + + /** + * Synchronously compresses data using deflate, and does not append a zlib header + */ + function rawCompressSync(buf: string | Buffer, options?: I.CompressOptions): Buffer; + + /** + * Creates a raw compress stream + */ + function rawCompressStream(options?: I.CompressStreamOptions): nodestd.zlib.DeflateRaw; + + /** + * Decomrpesses the given string of buffer + */ + function decompress(buf: string | Buffer, options: I.DecompressOptions & { info: true }): Promise; + + /** + * Decomrpesses the given string of buffer + */ + function decompress(buf: string | Buffer, options?: I.DecompressOptions): Promise; + + /** + * Synchronously decomrpesses the given string of buffer + */ + function decompressSync(buf: string | Buffer, options: I.DecompressOptions & { info: true }): I.InflateInfo; + + /** + * Synchronously decomrpesses the given string of buffer + */ + function decompressSync(buf: string | Buffer, options?: I.DecompressOptions): Buffer; + + /** + * Creates a decompress stream + */ + function decompressStream(options?: I.DecompressStreamOptions): nodestd.zlib.Inflate; + + /** + * Decompresses raw compressed data + */ + function rawDecompress(buf: string | Buffer, options: I.DecompressOptions & { info: true }): Promise; + + /** + * Decompresses raw compressed data + */ + function rawDecompress(buf: string | Buffer, options?: I.DecompressOptions): Promise; + + /** + * Synchronously decompresses raw compressed data + */ + function rawDecompressSync(buf: string | Buffer, options: I.DecompressOptions & { info: true }): I.InflateRawInfo; + + /** + * Synchronously decompresses raw compressed data + */ + function rawDecompressSync(buf: string | Buffer, options?: I.DecompressOptions): Buffer; + + /** + * Creates a raw decompress stream + */ + function rawDecompressStream(options?: I.DecompressStreamOptions): nodestd.zlib.InflateRaw; + + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + } + + /** + * Brotli compressor (br) + */ + namespace brotli { + namespace I { + interface CompressOptions { + /** + * Tune encoder for specific input. + * + * 0 - Generic mode, compressor does not know anything in advance about the properties of the input. + * + * 1 - Text mode, compression mode for UTF-8 formatted text input. + * + * 2 - Font, compression mode used in WOFF 2.0. + * + * Default is 0. + */ + mode?: number; + + /** + * The main compression speed-density lever. + * The higher the quality, the slower the compression. + * From 0 to 11. + * + * Default is 11. + */ + quality?: number; + + /** + * Recommended sliding LZ77 window size. + * Encoder may reduce this value, e.g. if input is much smaller than window size. + * Window size is (1 << value) - 16. + * From 10 to 24. + * + * Default is 22. + */ + lgwin?: number; + + /** + * Recommended input block size. + * Encoder may reduce this value, e.g. if input is much smaller than input block size. + * Bigger input block size allows better compression, but consumes more memory. + * From 16 to 24. + */ + lgblock?: number; + + /** + * Estimated total input size for all BrotliEncoderCompressStream calls. + * + * Automatically set for `compress` and `compressSync` to the input buffer length + */ + size_hint?: number; + + /** + * Flag that affects usage of "literal context modeling" format feature. + * This flag is a "decoding-speed vs compression ratio" trade-off. + */ + disable_literal_context_modeling?: boolean; + + /** + * A custom dictionary + */ + dictionary?: Buffer; + } + + interface DecompressOptions { + /** + * A custom dictionary + */ + dictionary?: Buffer; + } + + interface EncodeStream extends nodestd.stream.Transform { + flush(force?: boolean): void; + } + + type DecodeStream = nodestd.stream.Transform; + } + + /** + * Compresses the given string or buffer + */ + function compress(buf: string | Buffer, options?: I.CompressOptions): Promise; + + /** + * Synchronously compresses the given string or buffer + */ + function compressSync(buf: string | Buffer, options?: I.CompressOptions): Buffer; + + /** + * Creates a compress stream + */ + function compressStream(options?: I.CompressOptions): I.EncodeStream; + + /** + * Decompresses the given buffer + */ + function decompress(buf: Buffer, options?: I.DecompressOptions): Promise; + + /** + * Synchronously decompresses the given buffer + */ + function decompressSync(buf: Buffer, options?: I.DecompressOptions): Buffer; + + /** + * Creates a decompress stream + */ + function decompressStream(options?: I.DecompressOptions): I.DecodeStream; + } + + /** + * Snappy compressor + */ + namespace snappy { + /** + * Compresses the given string or buffer + */ + function compress(buf: string | Buffer): Promise; + + /** + * Synchronously compresses the given string or buffer + */ + function compressSync(buf: string | Buffer): Buffer; + + /** + * Checks whether the given buffer is a valid compressed buffer + */ + function isValidCompressed(buf: Buffer): Promise; + + /** + * Synchronously checks whether the given buffer is a valid compressed buffer + */ + function isValidCompressedSync(buf: Buffer): boolean; + + /** + * Decompresses the given buffer + */ + function decompress(buf: Buffer): Promise; + + /** + * Synchronously decompresses the given buffer + */ + function decompressSync(buf: Buffer): Buffer; + } + + namespace I.lzma { + interface Filter { + id: "LZMA_FILTERS_MAX" + | "LZMA_FILTER_ARM" + | "LZMA_FILTER_ARMTHUMB" + | "LZMA_FILTER_IA64" + | "LZMA_FILTER_POWERPC" + | "LZMA_FILTER_SPARC" + | "LZMA_FILTER_X86" + | "LZMA_FILTER_LZMA1" + | "LZMA_FILTER_LZMA2"; + } + + interface DeltaFilter { + id: "LZMA_FILTER_DELTA"; + dist?: number; + } + + interface LZMAFilter { + id: "LZMA_FILTER_LZMA1" | "LZMA_FILTER_LZMA2"; + + /** + * Dictionary size indicates how many bytes of the recently processed + * uncompressed data is kept in memory. + */ + dict_size?: number; + + /** + * The number of literal position bits. + * From 0 to 4. + * Default is 0. + * In addition, the sum of lc and lp must not exceed 4. + */ + lp?: number; + + /** + * The number of literal context bits. + * From 0 to 4. + * Default is 3. + * In addition, the sum of lc and lp must not exceed 4. + */ + lc?: number; + + /** + * The number of position bits. + * From 0 to 4. + * Default is 2. + */ + pb?: number; + + /** + * Compression mode + * + * lzma.MODE_FAST - 1 + * + * lzma.MODE_NORMAL - 2 + */ + mode?: number; + + /** + * Specify what is considered to be a nice length for a match. + * Once a match of at least nice bytes is found, the algorithm stops looking for possibly better matches. + * From 2 to 273. + * Default is 64. + */ + nice_len?: number; + + /** + * Match finder has major effect on both speed and compression ratio. + * Usually hash chains are faster than binary trees. + * + * MF_HC3 - 3 + * + * MF_HC4 - 4 + * + * MF_BT2 - 18 + * + * MF_BT3 - 19 + * + * MF_BT4 - 201 + * + */ + mf?: number; + + /** + * Specify the maximum search depth in the match finder. + * The default is the special value of 0, which makes the + * compressor determine a reasonable depth from mf and nice. + * + * Reasonable depth for Hash Chains is 4-100 and 16-1000 for Binary Trees. + */ + depth?: number; + + /** + * A number from 0 to 9, 0 being the fastest and weakest compression, + * 9 the slowest and highest compression level + */ + preset?: number; + } + + type Filters = Array; + + type Coder = "easyEncoder" + | "autoDecoder" + | "aloneEncoder" + | "aloneDecoder" + | "rawEncoder" + | "rawDecoder" + | "streamEncoder" + | "streamDecoder"; + + interface AloneEncoderOptions { + /** + * Any of: + * + * CHECK_CRC32 (1) + * + * CHECK_CRC64 (4) + * + * CHECK_NONE (0) + * + * CHECK_SHA256 (10) + */ + check?: number; + + /** + * A memory limit for (de-)compression in bytes + */ + memlimit?: number; + + /** + * A number from 0 to 9, 0 being the fastest and weakest compression, 9 the slowest and highest compression level + */ + preset?: number; + + /** + * A bitwise OR of + * LZMA_TELL_NO_CHECK, + * LZMA_TELL_UNSUPPORTED_CHECK, + * LZMA_TELL_ANY_CHECK, + * LZMA_CONCATENATED + */ + flags?: number; + + /** + * If true, forces synchronous coding (i.e. no usage of threading) + */ + synchronous?: boolean; + + /** + * The default size for allocated buffers + */ + bufsize?: number; + + /** + * Set to an integer to use liblzma’s multi-threading support. 0 will choose the number of CPU cores. + */ + threads?: number; + + /** + * Maximum uncompressed size of a block in multi-threading mode + */ + blockSize?: number; + + /** + * Timeout for a single encoding operation in multi-threading mode + */ + timeout?: number; + + /** + * An array of additional filters + */ + filters?: Filters; + } + + interface Stream extends nodestd.stream.Transform { + bufsize: number; + + totalIn(): number; + + totalOut(): number; + + cleanup(): void; + } + + interface EasyEncoderOptions { + /** + * A number from 0 to 9, 0 being the fastest and weakest compression, 9 the slowest and highest compression level + */ + preset?: number; + + /** + * Any of: + * + * CHECK_CRC32 (1) + * + * CHECK_CRC64 (4) + * + * CHECK_NONE (0) + * + * CHECK_SHA256 (10) + */ + check?: number; + } + + interface AutoDecoderOptions { + /** + * A memory limit for (de-)compression in bytes + */ + memlimit?: number; + + /** + * A bitwise OR of + * LZMA_TELL_NO_CHECK, + * LZMA_TELL_UNSUPPORTED_CHECK, + * LZMA_TELL_ANY_CHECK, + * LZMA_CONCATENATED + */ + flags?: number; + } + + interface AloneDecoderOptions { + /** + * A memory limit for (de-)compression in bytes + */ + memlimit?: number; + } + + interface RawEncoderOptions { + /** + * An array of additional filters + */ + filters?: Filters; + } + + interface RawDecoderOptions { + /** + * An array of additional filters + */ + filters?: Filters; + } + + interface StreamEncoderOptions { + /** + * Any of: + * + * CHECK_CRC32 (1) + * + * CHECK_CRC64 (4) + * + * CHECK_NONE (0) + * + * CHECK_SHA256 (10) + */ + check?: number; + + /** + * An array of additional filters + */ + filters?: Filters; + } + + interface StreamDecoderOptions { + /** + * A memory limit for (de-)compression in bytes + */ + memlimit?: number; + + /** + * A bitwise OR of + * LZMA_TELL_NO_CHECK, + * LZMA_TELL_UNSUPPORTED_CHECK, + * LZMA_TELL_ANY_CHECK, + * LZMA_CONCATENATED + */ + flags?: number; + } + } + + /** + * lzma compressor + common lzma functionality + */ + namespace lzma { + const asyncCodeAvailable: boolean; + + /** + * Returns the version of the underlying C library + */ + function versionNumber(): number; + + /** + * Returns the version of the underlying C library + */ + function versionString(): string; + + /** + * Checks whether the given Check ID is supported by this liblzma build + */ + function checkIsSupported(check: number): boolean; + + /** + * Return the byte size of a check sums + * + * @param check Any supported check constant + */ + function checkSize(check: number): number; + + /** + * Checks whether the given encoder filter is supported + */ + function filterEncoderIsSupported(encoder: string): boolean; + + /** + * Checks whether the given encoder filter is supported + */ + function filterDecoderIsSupported(decoder: string): boolean; + + /** + * Checks whether the given match finder is supported by this liblzma build + */ + function mfIsSupported(mf: number): boolean; + + /** + * Checks whether the given compression mode is supported by this liblzma build + */ + function modeIsSupported(mode: number): boolean; + + /** + * Returns the approximate memory usage when encoding using rawEncoder for a given filter list + */ + function rawEncoderMemusage(filters: I.lzma.Filters): number; + + /** + * Returns the approximate memory usage when decoding using rawDecoder for a given filter list + */ + function rawDecoderMemusage(filters: I.lzma.Filters): number; + + /** + * Returns the approximate memory usage when encoding using easyEncoder for a given preset + */ + function easyEncoderMemusage(preset: number): number; + + /** + * Returns the approximate memory usage when decoding using easyDecoder for a given preset + */ + function easyDecoderMemusage(preset: number): number; + + /** + * Returns a standard LZMA2 (.xz) encoder + * + * @param options preset or options + */ + function createStream(coder: "easyEncoder", options?: number | I.lzma.EasyEncoderOptions): I.lzma.Stream; + + /** + * Returns a standard LZMA 1/2 (bith .xz and .lzma) decoder with auto detection of file format + * + * @param options preset or options + */ + function createStream(coder: "autoDecoder", options?: I.lzma.AutoDecoderOptions): I.lzma.Stream; + + /** + * Returns a standard LZMA encoder + * + * @param options preset or options + */ + function createStream(coder: "aloneEncoder", options?: number | I.lzma.AloneEncoderOptions): I.lzma.Stream; + + /** + * Returns a standard LZMA decoder + */ + function createStream(coder: "aloneDecoder", options?: I.lzma.AloneDecoderOptions): I.lzma.Stream; + + /** + * Returns a custom encoder corresponding to lzma_raw_encoder + */ + function createStream(coder: "rawEncoder", options?: I.lzma.RawEncoderOptions): I.lzma.Stream; + + /** + * Returns a custom decoder corresponding to lzma_raw_decoder + */ + function createStream(coder: "rawDecoder", options?: I.lzma.RawDecoderOptions): I.lzma.Stream; + + /** + * Returns a custom encoder corresponding to lzma_stream_encoder + */ + function createStream(coder: "streamEncoder", options?: I.lzma.StreamEncoderOptions): I.lzma.Stream; + + /** + * Returns a custom decoder corresponding to lzma_stream_decoder + */ + function createStream(coder: "streamDecoder", options?: I.lzma.StreamDecoderOptions): I.lzma.Stream; + + /** + * Encodes the given string or buffer using the given stream + */ + function singleStringCoding( + stream: I.lzma.Stream, + string: string | Buffer, + onFinish?: (err: any, data: Buffer) => void, + onProgress?: (progress: number) => void + ): Promise; + + const CHECK_CRC32: number; + const CHECK_CRC64: number; + const CHECK_NONE: number; + const CHECK_SHA256: number; + + const FILTERS_MAX: string; + const FILTER_ARM: string; + const FILTER_ARMTHUMB: string; + const FILTER_IA64: string; + const FILTER_POWERPC: string; + const FILTER_SPARC: string; + const FILTER_X86: string; + const FILTER_DELTA: string; + const FILTER_LZMA1: string; + const FILTER_LZMA2: string; + + const PRESET_EXTREME: number; + const PRESET_DEFAULT: number; + const PRESET_LEVEL_MASK: number; + + const MF_HC3: number; + const MF_HC4: number; + const MF_BT2: number; + const MF_BT3: number; + const MF_BT4: number; + + const LZMA_TELL_NO_CHECK: number; + const LZMA_TELL_UNSUPPORTED_CHECK: number; + const LZMA_TELL_ANY_CHECK: number; + const LZMA_CONCATENATED: number; + + const MODE_FAST: number; + const MODE_NORMAL: number; + + const STREAM_HEADER_SIZE: number; + + /** + * Compresses the given string or buffer + * + * @param options preset or options + */ + function compress(buf: string | Buffer, options?: number | I.lzma.AloneEncoderOptions): Promise; + + /** + * Creates a compress stream + * + * @param options preset or options + */ + function compressStream(options?: number | I.lzma.AloneEncoderOptions): I.lzma.Stream; + + /** + * Decompresses the given buffer + */ + function decompress(buf: Buffer, options?: I.lzma.AloneDecoderOptions): Promise; + + /** + * Creates a decompress stream + * + * @param options preset or options + */ + function decompressStream(options?: I.lzma.AloneDecoderOptions): I.lzma.Stream; + } + + /** + * xz compressor (lzma2) + common lzma functionality + */ + namespace xz { + const asyncCodeAvailable: boolean; + + /** + * Returns the version of the underlying C library + */ + function versionNumber(): number; + + /** + * Returns the version of the underlying C library + */ + function versionString(): string; + + /** + * Checks whether the given Check ID is supported by this liblzma build + */ + function checkIsSupported(check: number): boolean; + + /** + * Return the byte size of a check sums + * + * @param check Any supported check constant + */ + function checkSize(check: number): number; + + /** + * Checks whether the given encoder filter is supported + */ + function filterEncoderIsSupported(encoder: string): boolean; + + /** + * Checks whether the given encoder filter is supported + */ + function filterDecoderIsSupported(decoder: string): boolean; + + /** + * Checks whether the given match finder is supported by this liblzma build + */ + function mfIsSupported(mf: number): boolean; + + /** + * Checks whether the given compression mode is supported by this liblzma build + */ + function modeIsSupported(mode: number): boolean; + + /** + * Returns the approximate memory usage when encoding using rawEncoder for a given filter list + */ + function rawEncoderMemusage(filters: I.lzma.Filters): number; + + /** + * Returns the approximate memory usage when decoding using rawDecoder for a given filter list + */ + function rawDecoderMemusage(filters: I.lzma.Filters): number; + + /** + * Returns the approximate memory usage when encoding using easyEncoder for a given preset + */ + function easyEncoderMemusage(preset: number): number; + + /** + * Returns the approximate memory usage when decoding using easyDecoder for a given preset + */ + function easyDecoderMemusage(preset: number): number; + + /** + * Returns a standard LZMA2 (.xz) encoder + * + * @param options preset or options + */ + function createStream(coder: "easyEncoder", options?: number | I.lzma.EasyEncoderOptions): I.lzma.Stream; + + /** + * Returns a standard LZMA 1/2 (bith .xz and .lzma) decoder with auto detection of file format + */ + function createStream(coder: "autoDecoder", options?: I.lzma.AutoDecoderOptions): I.lzma.Stream; + + /** + * Returns a standard LZMA encoder + * + * @param options preset or options + */ + function createStream(coder: "aloneEncoder", options?: number | I.lzma.AloneEncoderOptions): I.lzma.Stream; + + /** + * Returns a standard LZMA decoder + */ + function createStream(coder: "aloneDecoder", options?: I.lzma.AloneDecoderOptions): I.lzma.Stream; + + /** + * Returns a custom encoder corresponding to lzma_raw_encoder + */ + function createStream(coder: "rawEncoder", options?: I.lzma.RawEncoderOptions): I.lzma.Stream; + + /** + * Returns a custom decoder corresponding to lzma_raw_decoder + */ + function createStream(coder: "rawDecoder", options?: I.lzma.RawDecoderOptions): I.lzma.Stream; + + /** + * Returns a custom encoder corresponding to lzma_stream_encoder + */ + function createStream(coder: "streamEncoder", options?: I.lzma.StreamEncoderOptions): I.lzma.Stream; + + /** + * Returns a custom decoder corresponding to lzma_stream_decoder + */ + function createStream(coder: "streamDecoder", options?: I.lzma.StreamDecoderOptions): I.lzma.Stream; + + /** + * Encodes the given string or buffer using the given stream + */ + function singleStringCoding( + stream: I.lzma.Stream, + string: string | Buffer, + onFinish?: (err: any, data: Buffer) => void, + onProgress?: (progress: number) => void + ): Promise; + + const CHECK_CRC32: number; + const CHECK_CRC64: number; + const CHECK_NONE: number; + const CHECK_SHA256: number; + + const FILTERS_MAX: string; + const FILTER_ARM: string; + const FILTER_ARMTHUMB: string; + const FILTER_IA64: string; + const FILTER_POWERPC: string; + const FILTER_SPARC: string; + const FILTER_X86: string; + const FILTER_DELTA: string; + const FILTER_LZMA1: string; + const FILTER_LZMA2: string; + + const PRESET_EXTREME: number; + const PRESET_DEFAULT: number; + const PRESET_LEVEL_MASK: number; + + const MF_HC3: number; + const MF_HC4: number; + const MF_BT2: number; + const MF_BT3: number; + const MF_BT4: number; + + const LZMA_TELL_NO_CHECK: number; + const LZMA_TELL_UNSUPPORTED_CHECK: number; + const LZMA_TELL_ANY_CHECK: number; + const LZMA_CONCATENATED: number; + + const MODE_FAST: number; + const MODE_NORMAL: number; + + const STREAM_HEADER_SIZE: number; + + /** + * Compresses the given string or buffer + * + * @param options preset or options + */ + function compress(buf: string | Buffer, options?: number | I.lzma.EasyEncoderOptions): Promise; + + /** + * Creates a compress stream + * + * @param options preset or options + */ + function compressStream(options?: number | I.lzma.EasyEncoderOptions): I.lzma.Stream; + + /** + * Decompresses the given buffer + */ + function decompress(buf: Buffer, options?: I.lzma.AutoDecoderOptions): Promise; + + /** + * Creates a decompress stream + * + * @param options preset or options + */ + function decompressStream(options?: I.lzma.AutoDecoderOptions): I.lzma.Stream; + } + } +} diff --git a/types/adone/glosses/data.d.ts b/types/adone/glosses/data.d.ts new file mode 100644 index 0000000000..f711836bdd --- /dev/null +++ b/types/adone/glosses/data.d.ts @@ -0,0 +1,1032 @@ +declare namespace adone { + /** + * Various data [de]serializers + */ + namespace data { + /** + * JSON encoder + */ + namespace json { + namespace I { + type Replacer = ((key: string, value: any) => any) | string[]; + interface CompareValue { + key: string; + value: any; + } + type CompareFunction = (a: CompareValue, b: CompareValue) => number; + } + + /** + * Actually, the same as JSON.stringify, but returns a buffer + */ + function encode(obj: any, options?: { + /** + * A String or Number object that's used to insert white space into the output JSON string for readability purposes + */ + space?: string, + + /** + * A function that alters the behavior of the stringification process, + * or an array of String and Number objects that serve as a whitelist + * for selecting/filtering the properties of the value object to be included in the JSON string + */ + replacer?: I.Replacer + }): Buffer; + + /** + * Decodes JSON string or buffer + */ + function decode(buf: string | Buffer): any; + + /** + * Deterministic version of JSON.stringify() so you can get a consistent hash from stringified results + */ + function encodeStable(obj: any, options?: { + /** + * Indent spaces for pretty-printing + */ + space?: string, + + /** + * Whether to allow circular JSON structure + */ + cycles?: boolean, + + /** + * A function that alters the behavior of the stringification process, + * or an array of String and Number objects that serve as a whitelist + * for selecting/filtering the properties of the value object to be included in the JSON string + */ + replacer?: I.Replacer, + + /** + * Custom comparison function for object keys + */ + cmp?: I.CompareFunction + }): string; + + function encodeSafe(obj: any): string; + + function decodeSafe(str: string): any; + } + + /** + * MessagePack encoder + */ + namespace mpak { + /** + * Encodes the given object + */ + function encode(obj: any): Buffer; + + /** + * Decoder the given buffer + */ + function decode(buf: collection.I.ByteArray.Wrappable): any; + + namespace I { + type Type = string | number; // ? + type DecodeFunction = (buf: collection.ByteArray) => any; + type EncodeFunction = (x: any) => collection.ByteArray; + type EncodeCheckFunction = (x: any) => boolean; + + interface DecodingType { + /** + * Value type + */ + type: Type; + + /** + * Decode function + */ + decode: DecodeFunction; + } + + interface EncodingType { + /** + * Value type + */ + type: Type; + + /** + * Encode function + */ + encode: EncodeFunction; + + /** + * Check function + */ + check: EncodeCheckFunction; + } + } + + /** + * Represents a MessagePack encoder + */ + class Encoder { + constructor(encodingTypes: I.EncodingType[]); + + /** + * Encodes the given value + */ + encode(x: any, buf?: T): T; + } + + /** + * Represents a MessagePack decoder + */ + class Decoder { + constructor(decodingTypes: I.DecodingType[]); + + /** + * Decodes the given buffer + */ + decode(buf: collection.I.ByteArray.Wrappable): any; + + /** + * Decodes the given ByteArray buffer, but does not throw IncompleteBufferError if the size is invalid + */ + tryDecode(buf: collection.ByteArray): any; + } + + /** + * Represents a MessagePack serializer + */ + class Serializer { + /** + * Encoder instance + */ + readonly encoder: Encoder; + + /** + * Decoder instance + */ + readonly decoder: Decoder; + + /** + * Registers an encoder for the given type + * + * @param type type identifier + * @param check type predicate + * @param encode type encoder + */ + registerEncoder(type: I.Type, check: I.EncodeCheckFunction, encode: I.EncodeFunction): this; + + /** + * Registers a decoder for the given type + * + * @param type type identifier + * @param decode type decoder + */ + registerDecoder(type: I.Type, decode: I.DecodeFunction): this; + + /** + * Registers encoder/decoder functions for the given type and constructor + * + * @param type type identifier + * @param constructor type constructor, used in the predicate function (instanceof) + * @param encode type encoder + * @param decode type decoder + */ + register( + type: I.Type, + constructor: { new (...args: any[]): T }, + encode: (x: T, buf: collection.ByteArray) => void, + decode: (buf: collection.ByteArray) => T + ): this; + + /** + * Encodes the given value + */ + encode(x: any, buf?: T): T; + + /** + * Decodes the given buffer + */ + decode(buf: collection.I.ByteArray.Wrappable, needFlip?: boolean): any; + } + + /** + * An instance of default adone serializer with registered encoders/decoders for standard js/adone types like + * x.Exception, Error, Date, Map, Set, math.Long + */ + const serializer: Serializer; + } + + /** + * JSON5 encoder + */ + namespace json5 { + /** + * Encodes the given value + */ + function encode(obj: any, options?: { + /** + * Indent spaces for pretty-printing + */ + space?: string, + + /** + * A function that alters the behavior of the stringification process, + * or an array of String and Number objects that serve as a whitelist + * for selecting/filtering the properties of the value object to be included in the JSON string + */ + replacer?: ((key: string, value: any) => any) | string[] + }): Buffer; + + /** + * Decodes the given string/buffer + */ + function decode(buf: string | Buffer, reviver?: (holder: object, key: string, value: any) => any): any; + } + + /** + * Base64 encoder + */ + namespace base64 { + /** + * Encodes a string/Buffer to base64 + */ + function encode(str: string | Buffer, options: { buffer: false }): string; + function encode(str: string | Buffer, options?: { buffer?: true }): Buffer; + + /** + * Decodes base64 string/buffer into a buffer + */ + function decode(str: string | Buffer, options: { buffer: true }): Buffer; + + /** + * Decodes base64 string/buffer into a string + */ + function decode(str: string | Buffer, options?: { buffer?: false }): string; + + function encodeVLQ(value: number): string; + + function decodeVLQ(value: string, index: number | undefined, rest: true): { value: number, index: number }; + function decodeVLQ(value: string, index?: number, rest?: boolean): number; + + /** + * Maps a character to a base64 number + */ + function decodeCharCode(c: string): number; + + /** + * Maps a number to a base64 character + */ + function decodeNumber(n: number): string; + } + + /** + * YAML encoder + */ + namespace yaml { + /** + * YAML loaders + */ + namespace loader { + namespace I { + interface Options { + /** + * String to be used as a file path in error/warning messages. Default: null + */ + filename?: string; + + /** + * Specifies a schema to use + */ + schema?: schema.Schema; + + /** + * Function to call on warning messages. + * Loader will throw on warnings if this function is not provided + */ + onWarning?(warning: any): void; + + /** + * Compatibility with JSON.parse behaviour. + * If true, then duplicate keys in a mapping will override values rather than throwing an error + */ + json?: boolean; + } + } + + /** + * Same as safeLoadAll() but uses DEFAULT_FULL by default + */ + function loadAll(input: string | Buffer, iterator: (doc: any) => void, options?: I.Options): void; + function loadAll(input: string | Buffer, iterator?: undefined, options?: I.Options): any[]; + + /** + * The same as safeLoad() but uses DEFAULT_FULL_SCHEMA by default - adds some JavaScript-specific types: !!js/function, !!js/regexp and !!js/undefined. + * For untrusted sources, you must additionally validate object structure to avoid injections + */ + function load(input: string | Buffer, options?: I.Options): any; + + /** + * Parses string as single YAML document. Returns a JavaScript object or throws YAMLException on error. + * By default, does not support regexps, functions and undefined. + * This method is safe for untrusted data + */ + function safeLoadAll(input: string | Buffer, iterator: (doc: any) => void, options?: I.Options): void; + function safeLoadAll(input: string | Buffer, iterator?: undefined, options?: I.Options): any[]; + + /** + * Same as safeLoad(), but understands multi-document sources. + * Applies iterator to each document if specified, or returns array of documents + */ + function safeLoad(input: string | Buffer, options?: I.Options): any; + } + + /** + * YAML dumpers + */ + namespace dumper { + namespace I { + interface Options { + /** + * indentation width to use (in spaces). Default: 2 + */ + indent?: number; + + /** + * Do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. + * Default: false + */ + skipInvalid?: boolean; + + /** + * Specifies level of nesting, when to switch from block to flow style for collections. + * -1 means block style everwhere. Default: -1 + */ + flowLevel?: number; + + /** + * "tag" => "style" map. Each tag may have own set of styles + */ + styles?: object; + + /** + * Specifies a schema to use + */ + schema?: schema.Schema; + + /** + * If true, sort keys when dumping YAML. If a function, use the function to sort the keys. Default: false + */ + sortKeys?: boolean; + + /** + * Set max line width. Default: 80 + */ + lineWidth?: number; + + /** + * If true, don't convert duplicate objects into references. Default: false + */ + noRefs?: boolean; + + /** + * If true don't try to be compatible with older yaml versions. + * Currently: don't quote "yes", "no" and so on, as required for YAML 1.1. + * Default: false + */ + noCompatMode?: boolean; + + /** + * If true flow sequences will be condensed, omitting the space between a, b. Eg. '[a,b]' + */ + condenseFlow?: boolean; + } + } + + /** + * Same as safeDump() but without limits (uses DEFAULT_FULL by default) + */ + function dump(input: any, options?: I.Options): string; + + /** + * Serializes object as a YAML document. + * Uses DEFAULT_SAFE, so it will throw an exception if you try to dump regexps or functions + */ + function safeDump(input: any, options?: I.Options): string; + } + + /** + * YAML types for custom schemas + */ + namespace type { + namespace I { + type Kind = "scalar" | "sequence" | "mapping"; + + interface TypeOptions { + kind: Kind; + resolve?(data: string): boolean; + construct?(data: string): T; + instanceOf?: object; + predicate?(obj: any): boolean; + represent?: ((obj: any, style: string) => string) | { [key: string]: (obj: any, style: string) => string }; + defaultStyle?: string; + styleAliases?: object; + } + } + + class Type { + tag: string; + resolve(data: string): boolean; + construct(data: string): T; + instanceOf?: object; + predicate?(obj: any): boolean; + represent?: (obj: any, style: string) => string | { [key: string]: (obj: any, style: string) => string }; + defaultStyle?: string; + styleAliases?: object; + + constructor(tag: string, options: I.TypeOptions); + } + + namespace I { + interface Scalar extends Type { + kind: "scalar"; + } + + interface Mapping extends Type { + kind: "mapping"; + } + + interface Sequence extends Type { + kind: "sequence"; + } + } + + const Binary: I.Scalar; + + const Bool: I.Scalar; + + const Float: I.Scalar; + + const Int: I.Scalar; + + const Map: I.Mapping; + + const Merge: I.Scalar; + + const Null: I.Scalar; + + const Omap: I.Sequence; + + const Pairs: I.Sequence<[string, any]>; + + const Seq: I.Sequence; + + const Set: I.Mapping; + + const Str: I.Scalar; + + const Timestamp: I.Scalar; + + namespace js { + const Function: I.Scalar<(...args: any[]) => void>; + + const RegExp: I.Scalar; + + const Undefined: I.Scalar; + } + } + + /** + * YAML schemas + */ + namespace schema { + class Schema { + include: Schema[]; + implicit: type.Type[]; + explicit: type.Type[]; + compiledImplicit: type.Type[]; + compiledExplicit: type.Type[]; + compiledTypeMap: { + scalar: { [key: string]: type.Type }, + sequence: { [key: string]: type.Type }, + mapping: { [key: string]: type.Type }, + fallback: { [key: string]: type.Type } + }; + + constructor(_?: { include?: Schema[], implicit?: type.Type[], explicit?: type.Type[] }); + } + + function create(schemas: Schema | Schema[], types: type.Type | type.Type[]): Schema; + + /** + * same as JSON + */ + const CORE: Schema; + + /** + * all supported YAML types + */ + const DEFAULT_FULL: Schema; + + /** + * all supported YAML types, without unsafe ones: !!js/undefined, !!js/regexp and !!js/function + */ + const DEFAULT_SAFE: Schema; + + /** + * only strings, arrays and plain objects + */ + const FAILSAFE: Schema; + + /** + * all JSON-supported types + */ + const JSON: Schema; + } + + /** + * Represetns a mark that is used in exceptions to define the error's location + */ + class Mark { + name: string; + buffer: string; + position: number; + line: number; + column: number; + + constructor(name: string, buffer: string, position: number, line: number, column: number); + + getSnippet(indent?: number, maxLength?: number): string; + + toString(compact?: boolean): string; + } + + /** + * Represents a YAML exception + */ + class Exception extends adone.x.Exception { + reason: string; + mark: Mark; + + constructor(reason: string, mark: Mark); + } + + /** + * Encodes the given object using DEFAULT_SAFE scheme by default + */ + function encode(obj: any, options?: dumper.I.Options): Buffer; + + /** + * Decodes the given string/buffer using DEFAULT_SAFE scheme by default + */ + function decode(buf: string | Buffer, options?: loader.I.Options): any; + + /** + * The same as safeLoad() but uses DEFAULT_FULL_SCHEMA by default - adds some JavaScript-specific types: !!js/function, !!js/regexp and !!js/undefined. + * For untrusted sources, you must additionally validate object structure to avoid injections + */ + const load: typeof loader.load; + + /** + * Same as safeLoadAll() but uses DEFAULT_FULL by default + */ + const loadAll: typeof loader.loadAll; + + /** + * Parses string as single YAML document. Returns a JavaScript object or throws YAMLException on error. + * By default, does not support regexps, functions and undefined. + * This method is safe for untrusted data + */ + const safeLoad: typeof loader.safeLoad; + + /** + * Same as safeLoad(), but understands multi-document sources. + * Applies iterator to each document if specified, or returns array of documents + */ + const safeLoadAll: typeof loader.safeLoadAll; + + /** + * Same as safeDump() but without limits (uses DEFAULT_FULL by default) + */ + const dump: typeof dumper.dump; + + /** + * Serializes object as a YAML document. + * Uses DEFAULT_SAFE, so it will throw an exception if you try to dump regexps or functions + */ + const safeDump: typeof dumper.safeDump; + } + + /** + * BSON encoder + */ + namespace bson { + namespace I { + interface Type { + _bsontype: string; + } + } + + /** + * Represents a BSON Binary type + */ + class Binary implements I.Type { + _bsontype: "binary"; + + constructor(buffer: number | Buffer, subType?: number); + + /** + * Updates this binary with `byte` + */ + put(byte: number): void; + + /** + * Writes a buffer or string to the binary + */ + write(string: string | Buffer, offset?: number): void; + + /** + * Reads length bytes starting at position + */ + read(position: number, length?: number): void; + + /** + * Returns the value of this binary as a string or buffer + */ + value(asRaw: true): Buffer; + value(): string; + + /** + * Returns the length of the binary + */ + length(): number; + + toJSON(): string; + + toString(): string; + + static BUFFER_SIZE: number; + static SUBTYPE_DEFAULT: number; + static SUBTYPE_FUNCTION: number; + static SUBTYPE_BYTE_ARRAY: number; + static SUBTYPE_UUID_OLD: number; + static SUBTYPE_UUID: number; + static SUBTYPE_MD5: number; + static SUBTYPE_USER_DEFINED: number; + } + + /** + * Represents BSON Code type + */ + class Code implements I.Type { + _bsontype: "Code"; + + /** + * @param code a string or function + * @param scope an optional scope for the function + */ + constructor(code: string | ((...args: any[]) => void), scope?: object); + + toJSON(): { scope: object, code: string }; + } + + /** + * Represents BSON DBRef type + */ + class DBRef implements I.Type { + _bsontype: "DBRef"; + + /** + * @param namespace the collection name + * @param oid the reference ObjectID + * @param db optional db name, if omitted the reference is local to the current db + */ + constructor(namespace: string, oid: ObjectId, db?: string); + + toJSON(): { $ref: string, $id: ObjectId, $db: string }; + } + + /** + * Represents BSON Decimal128 type + */ + class Decimal128 implements I.Type { + _bsontype: "Decimal128"; + + /** + * @param bytes a buffer containing the raw Decimal128 bytes + */ + constructor(bytes: Buffer); + + toString(): string; + + toJSON(): { $numberDecimal: string }; + + /** + * Create a Decimal128 instance from a string representation + * + * @param string a numeric string representation + */ + static fromString(string: string): Decimal128; + } + + /** + * Represents BSON Double type + */ + class Double implements I.Type { + _bsontype: "Double"; + + constructor(value: number); + + valueOf(): number; + + toJSON(): number; + } + + /** + * /** + * Represents BSON Int32 type + */ + class Int32 implements I.Type { + _bsontype: "Int32"; + + constructor(value: number); + + valueOf(): number; + + toJSON(): number; + } + + /** + * Represents BSON Long type + */ + class Long extends math.Long implements I.Type { + _bsontype: "Long"; + + static MIN_VALUE: Long; + static MAX_VALUE: Long; + static MAX_UNSIGNED_VALUE: Long; + static ZERO: Long; + static UZERO: Long; + static ONCE: Long; + static ONE: Long; + static UONE: Long; + static NEG_ONE: Long; + } + + /** + * Represents BSON MaxKey type + */ + class MaxKey implements I.Type { + _bsontype: "MaxKey"; + } + + /** + * Represents BSON MinKey type + */ + class MinKey implements I.Type { + _bsontype: "MinKey"; + } + + /** + * Represents BSON ObjectId type + */ + class ObjectId implements I.Type { + _bsontype: "ObjectId"; + + generationTime: number; + + constructor(id?: string | Buffer | ObjectId | { toHexString(): string, id: string | Buffer | ObjectId }); + + /** + * Return the ObjectId id as a 24 byte hex string representation + */ + toHexString(): string; + + /** + * Returns the next ObjectId index + */ + getInc(): number; + + /** + * Generate a 12 byte id buffer used in ObjectId's + */ + generate(time?: number): Buffer; + + toString(format?: string): string; + + toJSON(): string; + + /** + * Compares the equality of this ObjectID with otherID + */ + equals(other: string | Buffer | ObjectId | { toHexString(): string }): boolean; + + /** + * Returns the generation date (accurate up to the second) that this ID was generated + */ + getTimestamp(): Date; + + /** + * Creates an ObjectId + */ + static createPk(): ObjectId; + + /** + * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId + */ + static createFromTime(time: number): ObjectId; + + /** + * Creates an ObjectID from a hex string representation of an ObjectId + */ + static createFromHexString(string: string): ObjectId; + + /** + * Checks if a value is a valid bson ObjectId + */ + static isValid(id: any): boolean; + + static index: number; + } + + /** + * Represents BSON RegExp type + */ + class BSONRegExp implements I.Type { + _bsontype: "BSONRegExp"; + + constructor(pattern: string, options?: string); + } + + /** + * Represents BSON Symbol type + */ + class Symbol implements I.Type { + _bsontype: "Symbol"; + + constructor(value: string); + + valueOf(): string; + + toString(): string; + + inspect(): string; + + toJSON(): string; + } + + /** + * This type is for INTERNAL use in MongoDB only and should not be used in applications + */ + class Timestamp extends math.Long implements I.Type { + _bsontype: "Timestamp"; + + static MIN_VALUE: Timestamp; + static MAX_VALUE: Timestamp; + static MAX_UNSIGNED_VALUE: Timestamp; + static ZERO: Timestamp; + static UZERO: Timestamp; + static ONCE: Timestamp; + static ONE: Timestamp; + static UONE: Timestamp; + static NEG_ONE: Timestamp; + } + + namespace I { + interface SerializeOptions { + /** + * Whether to check if keys are valid. Default: false + */ + checkKeys?: boolean; + + /** + * Whether to serialize javascript functions. Default: false + */ + serializeFunctions?: boolean; + + /** + * Whether to ignore undefined values. Default: true + */ + ignoreUndefined?: boolean; + } + + interface DeserializeOptions { + /** + * Evaluate functions in the BSON document scoped to the object deserialized. + * Default: false + */ + evalFunctions?: boolean; + + /** + * Cache evaluated functions for reuse. + * Default: false + */ + cacheFunctions?: boolean; + + /** + * Use a crc32 code for caching, otherwise use the string of the function. + * Default: false + */ + cacheFunctonsCrc32?: boolean; + + /** + * When deserializing a Long will fit it into a Number if it's smaller than 53 bits. + * Default: true + */ + promoteLongs?: boolean; + + /** + * When deserializing a Binary will return it as a node.js Buffer instance. + * Default: false + */ + promoteBuffers?: boolean; + + /** + * When deserializing will promote BSON values to their Node.js closest equivalent types. + * Default: false + */ + promoteValues?: boolean; + + /** + * Allow to specify if there what fields we wish to return as unserialized raw buffer. + */ + fieldsAsRaw?: string[]; + + /** + * Return BSON regular expressions as BSONRegExp instances. + * Default: false + */ + bsonRegExp?: boolean; + } + } + + /** + * Represents a BSON serializer + */ + class BSON { + constructor(types?: Array<{ new (...args: any[]): I.Type }>); + + /** + * Serializes a js object into a buffer + */ + serialize(object: object, options?: I.SerializeOptions): Buffer; + + /** + * Takes an object, a target buffer instance and an optional options object and returns the end serialization index + * in the final buffer + */ + serializeWithBufferAndIndex(object: object, buffer: Buffer, options?: I.SerializeOptions & { + /** + * The index in the buffer where we wish to start serializing into + */ + index?: number + }): number; + + /** + * Calculates the size BSON object for the given object + */ + calculateObjectSize(object: object, options?: { + /** + * Whether to serialize javascript functions. Default: false + */ + serializeFunctions?: boolean, + + /** + * Whether to ignore undefined values. Default: true + */ + ignoreUndefined?: boolean + }): number; + + /** + * Deserializes the given buffer into an object + */ + deserialize(buf: Buffer, options?: I.DeserializeOptions): any; + + /** + * Takes a node.js Buffer, startIndex and allow more control over deserialization of a Buffer containing concatenated BSON documents + */ + deserializeStream(buf: Buffer, startIndex: number, numberOfDocuments: number, documents: any[], docStartIndex: number, options?: I.DeserializeOptions): number; + } + + namespace c { + const BSON_INT32_MIN: number; + const BSON_INT32_MAX: number; + const BSON_INT64_MAX: number; + const BSON_INT64_MIN: number; + const JS_INT_MAX: number; + const JS_INT_MIN: number; + } + + /** + * BSON serializator instance + */ + const serializer: BSON; + + /** + * Encodes the given object + */ + function encode(obj: object, options?: I.SerializeOptions): Buffer; + + /** + * Decodes the given buffer with enabled buffers and values promoting + */ + function decode(buf: Buffer, options?: I.DeserializeOptions): any; + } + } +} diff --git a/types/adone/glosses/datetime.d.ts b/types/adone/glosses/datetime.d.ts new file mode 100644 index 0000000000..417f706d95 --- /dev/null +++ b/types/adone/glosses/datetime.d.ts @@ -0,0 +1,1394 @@ +// based on https://github.com/moment/moment/blob/develop/moment.d.ts + +declare namespace adone { + namespace I { + namespace datetime { + type RelativeTimeKey = "s" | "m" | "mm" | "h" | "hh" | "d" | "dd" | "M" | "MM" | "y" | "yy"; + type CalendarKey = "sameDay" | "nextDay" | "lastDay" | "nextWeek" | "lastWeek" | "sameElse"; + type LongDateFormatKey = "LTS" | "LT" | "L" | "LL" | "LLL" | "LLLL" | "lts" | "lt" | "l" | "ll" | "lll" | "llll"; + + interface Locale { + calendar(key?: CalendarKey, m?: Datetime, now?: Datetime): string; + + longDateFormat(key: LongDateFormatKey): string; + invalidDate(): string; + ordinal(n: number): string; + + preparse(inp: string): string; + postformat(inp: string): string; + relativeTime(n: number, withoutSuffix: boolean, key: RelativeTimeKey, isFuture: boolean): string; + pastFuture(diff: number, absRelTime: string): string; + set(config: object): void; + + months(): string[]; + months(m: Datetime, format?: string): string; + monthsShort(): string[]; + monthsShort(m: Datetime, format?: string): string; + monthsParse(monthName: string, format: string, strict: boolean): number; + monthsRegex(strict: boolean): RegExp; + monthsShortRegex(strict: boolean): RegExp; + + week(m: Datetime): number; + firstDayOfYear(): number; + firstDayOfWeek(): number; + + weekdays(): string[]; + weekdays(m: Datetime, format?: string): string; + weekdaysMin(): string[]; + weekdaysMin(m: Datetime): string; + weekdaysShort(): string[]; + weekdaysShort(m: Datetime): string; + weekdaysParse(weekdayName: string, format: string, strict: boolean): number; + weekdaysRegex(strict: boolean): RegExp; + weekdaysShortRegex(strict: boolean): RegExp; + weekdaysMinRegex(strict: boolean): RegExp; + + isPM(input: string): boolean; + meridiem(hour: number, minute: number, isLower: boolean): string; + } + + interface StandaloneFormatSpec { + format: string[]; + standalone: string[]; + isFormat?: RegExp; + } + + interface WeekSpec { + dow: number; + doy: number; + } + + type CalendarSpecVal = string | ((m?: DatetimeInput, now?: Datetime) => string); + interface CalendarSpec { + sameDay?: CalendarSpecVal; + nextDay?: CalendarSpecVal; + lastDay?: CalendarSpecVal; + nextWeek?: CalendarSpecVal; + lastWeek?: CalendarSpecVal; + sameElse?: CalendarSpecVal; + + // any additional properties might be used with datetime.calendarFormat + [x: string]: CalendarSpecVal | undefined; + } + + type RelativeTimeSpecVal = ( + string | + ((n: number, withoutSuffix: boolean, key: RelativeTimeKey, isFuture: boolean) => string) + ); + type RelativeTimeFuturePastVal = string | ((relTime: string) => string); + + interface RelativeTimeSpec { + future: RelativeTimeFuturePastVal; + past: RelativeTimeFuturePastVal; + s: RelativeTimeSpecVal; + m: RelativeTimeSpecVal; + mm: RelativeTimeSpecVal; + h: RelativeTimeSpecVal; + hh: RelativeTimeSpecVal; + d: RelativeTimeSpecVal; + dd: RelativeTimeSpecVal; + M: RelativeTimeSpecVal; + MM: RelativeTimeSpecVal; + y: RelativeTimeSpecVal; + yy: RelativeTimeSpecVal; + } + + interface LongDateFormatSpec { + LTS: string; + LT: string; + L: string; + LL: string; + LLL: string; + LLLL: string; + + // lets forget for a sec that any upper/lower permutation will also work + lts?: string; + lt?: string; + l?: string; + ll?: string; + lll?: string; + llll?: string; + } + + type MonthWeekdayFn = (datetimeToFormat: Datetime, format?: string) => string; + type WeekdaySimpleFn = (datetimeToFormat: Datetime) => string; + + interface LocaleSpecification { + months?: string[] | StandaloneFormatSpec | MonthWeekdayFn; + monthsShort?: string[] | StandaloneFormatSpec | MonthWeekdayFn; + + weekdays?: string[] | StandaloneFormatSpec | MonthWeekdayFn; + weekdaysShort?: string[] | StandaloneFormatSpec | WeekdaySimpleFn; + weekdaysMin?: string[] | StandaloneFormatSpec | WeekdaySimpleFn; + + meridiemParse?: RegExp; + meridiem?(hour: number, minute: number, isLower: boolean): string; + + isPM?(input: string): boolean; + + longDateFormat?: LongDateFormatSpec; + calendar?: CalendarSpec; + relativeTime?: RelativeTimeSpec; + invalidDate?: string; + ordinal?(n: number): string; + ordinalParse?: RegExp; + + week?: WeekSpec; + + // Allow anything: in general any property that is passed as locale spec is + // put in the locale object so it can be used by locale functions + [x: string]: any; + } + + interface DatetimeObjectOutput { + years: number; + /* One digit */ + months: number; + /* Day of the month */ + date: number; + hours: number; + minutes: number; + seconds: number; + milliseconds: number; + } + + interface Duration { + /** + * Returns a human readable representation + */ + humanize(withSuffix?: boolean): string; + + abs(): Duration; + + /** + * Returns the length of the duration in the given units + */ + as(units: unitOfTime.Base): number; + + /** + * Returns the value of the given unit + */ + get(units: unitOfTime.Base): number; + + /** + * Returns the number of milliseconds in the duration + */ + milliseconds(): number; + + /** + * Returns the length of the duration in milliseconds + */ + asMilliseconds(): number; + + /** + * Returns the number of seconds in the duration + */ + seconds(): number; + + /** + * Returns the length of the duration in seconds + */ + asSeconds(): number; + + /** + * Returns the number of minutes in the duration + */ + minutes(): number; + + /** + * Returns the length of the duration in minutes + */ + asMinutes(): number; + + /** + * Returns the number of hours in the duration + */ + hours(): number; + + /** + * Returns the length of the duration in hours + */ + asHours(): number; + + /** + * Returns the number of days in the duration + */ + days(): number; + + /** + * Returns the length of the duration in days + */ + asDays(): number; + + /** + * Returns the number of weeks in the duration + */ + weeks(): number; + + /** + * Returns the length of the duration in weeks + */ + asWeeks(): number; + + /** + * Returns the number of months in the duration + */ + months(): number; + + /** + * Returns the length of the duration in months + */ + asMonths(): number; + + /** + * Returns the number of years in the duration + */ + years(): number; + + /** + * Returns the length of the duration in years + */ + asYears(): number; + + /** + * Mutates the original duration by adding time + */ + add(inp?: DurationInputArg1, unit?: DurationInputArg2): Duration; + + /** + * Mutates the original duration by subtracting time. + */ + subtract(inp?: DurationInputArg1, unit?: DurationInputArg2): Duration; + + /** + * Returns the using locale + */ + locale(): string; + + /** + * Sets a new locale + */ + locale(locale: LocaleSpecifier): Duration; + + /** + * Returns the data of the using locale + */ + localeData(): Locale; + + /** + * Returns duration in string as specified by ISO 8601 standard. + */ + toISOString(): string; + + /** + * When serializing a duration object to JSON, it will be represented as an ISO8601 string. + */ + toJSON(): string; + } + + interface DatetimeParsingFlags { + empty: boolean; + unusedTokens: string[]; + unusedInput: string[]; + overflow: number; + charsLeftOver: number; + nullInput: boolean; + invalidMonth: string | null; + invalidFormat: boolean; + userInvalidated: boolean; + iso: boolean; + parsedDateParts: any[]; + meridiem: string | null; + } + + interface DatetimeParsingFlagsOpt { + empty?: boolean; + unusedTokens?: string[]; + unusedInput?: string[]; + overflow?: number; + charsLeftOver?: number; + nullInput?: boolean; + invalidMonth?: string; + invalidFormat?: boolean; + userInvalidated?: boolean; + iso?: boolean; + parsedDateParts?: any[]; + meridiem?: string; + } + + type DatetimeFormatSpecification = string | string[]; + + namespace unitOfTime { + type Base = ( + "year" | "years" | "y" | + "month" | "months" | "M" | + "week" | "weeks" | "w" | + "day" | "days" | "d" | + "hour" | "hours" | "h" | + "minute" | "minutes" | "m" | + "second" | "seconds" | "s" | + "millisecond" | "milliseconds" | "ms" + ); + + type _quarter = "quarter" | "quarters" | "Q"; + type _isoWeek = "isoWeek" | "isoWeeks" | "W"; + type _date = "date" | "dates" | "D"; + type DurationConstructor = Base | _quarter; + + type DurationAs = Base; + + type StartOf = Base | _quarter | _isoWeek | _date; + + type Diff = Base | _quarter; + + type DatetimeConstructor = Base | _date; + + type All = Base | _quarter | _isoWeek | _date | + "weekYear" | "weekYears" | "gg" | + "isoWeekYear" | "isoWeekYears" | "GG" | + "dayOfYear" | "dayOfYears" | "DDD" | + "weekday" | "weekdays" | "e" | + "isoWeekday" | "isoWeekdays" | "E"; + } + + interface DatetimeInputObject { + /** + * Year + */ + years?: number; + /** + * Year + */ + year?: number; + /** + * Year + */ + y?: number; + + /** + * Month, 0..11 + */ + months?: number; + /** + * Month, 0..11 + */ + month?: number; + /** + * Month, 0..11 + */ + M?: number; + + /** + * Day of week, 0..6 + */ + days?: number; + /** + * Day of week, 0..6 + */ + day?: number; + /** + * Day of week, 0..6 + */ + d?: number; + + /** + * Day of month, 1..31 + */ + dates?: number; + /** + * Day of month, 1..31 + */ + date?: number; + /** + * Day of month, 1..31 + */ + D?: number; + + /** + * Hour, 0..23 + */ + hours?: number; + /** + * Hour, 0..23 + */ + hour?: number; + /** + * Hour, 0..23 + */ + h?: number; + + /** + * Minute, 0..59 + */ + minutes?: number; + /** + * Minute, 0..59 + */ + minute?: number; + /** + * Minute, 0..59 + */ + m?: number; + + /** + * Second, 0..59 + */ + seconds?: number; + /** + * Second, 0..59 + */ + second?: number; + /** + * Second, 0..59 + */ + s?: number; + + /** + * Millisecond, 0..999 + */ + milliseconds?: number; + /** + * Millisecond, 0..999 + */ + millisecond?: number; + /** + * Millisecond, 0..999 + */ + ms?: number; + } + + interface DurationInputObject extends DatetimeInputObject { + /** + * Quarter, 1..4 + */ + quarters?: number; + /** + * Quarter, 1..4 + */ + quarter?: number; + /** + * Quarter, 1..4 + */ + Q?: number; + + /** + * Week of the year, 1..53 + */ + weeks?: number; + /** + * Week of the year, 1..53 + */ + week?: number; + /** + * Week of the year, 1..53 + */ + w?: number; + } + + interface DatetimeSetObject extends DatetimeInputObject { + /** + * Week-year according to the locale + */ + weekYears?: number; + + /** + * Week-year according to the locale + */ + weekYear?: number; + + /** + * Week-year according to the locale + */ + gg?: number; + + /** + * ISO week-year + */ + isoWeekYears?: number; + + /** + * ISO week-year + */ + isoWeekYear?: number; + + /** + * ISO week-year + */ + GG?: number; + + /** + * Quarter, 1..4 + */ + quarters?: number; + + /** + * Quarter, 1..4 + */ + quarter?: number; + + /** + * Quarter, 1..4 + */ + Q?: number; + + /** + * Week of the year, 1..53 + */ + weeks?: number; + + /** + * Week of the year, 1..53 + */ + week?: number; + + /** + * Week of the year, 1..53 + */ + w?: number; + + /** + * ISO week of the year, 1..53 + */ + isoWeeks?: number; + + /** + * ISO week of the year, 1..53 + */ + isoWeek?: number; + + /** + * ISO week of the year, 1..53 + */ + W?: number; + + /** + * Day of the year, 1..366 + */ + dayOfYears?: number; + + /** + * Day of the year, 1..366 + */ + dayOfYear?: number; + + /** + * Day of the year, 1..366 + */ + DDD?: number; + + /** + * Day of Week according to the locale + */ + weekdays?: number; + + /** + * Day of Week according to the locale + */ + weekday?: number; + + /** + * Day of Week according to the locale + */ + e?: number; + + /** + * ISO Day of Week + */ + isoWeekdays?: number; + + /** + * ISO Day of Week + */ + isoWeekday?: number; + + /** + * ISO Day of Week + */ + E?: number; + } + + interface FromTo { + from: DatetimeInput; + to: DatetimeInput; + } + + type DatetimeInput = string | number | Array | DatetimeInputObject | Datetime | Date | null | undefined; + type DurationInputArg1 = Duration | number | string | FromTo | DurationInputObject | null | undefined; + type DurationInputArg2 = unitOfTime.DurationConstructor; + type LocaleSpecifier = string | Datetime | Duration | string[] | boolean; + + interface DatetimeCreationData { + input: DatetimeInput; + format?: DatetimeFormatSpecification; + locale: Locale; + isUTC: boolean; + strict?: boolean; + } + + interface MSDOSFormat { + /** + * an unsigned 16-bit integer represents MS-DOS date + */ + date: number; + + /** + * an unsigned 16-bit integer represents MS-DOS time + */ + time: number; + } + + interface Datetime extends Object { + /** + * Formats the datetime using the given format. + * It takes a string of tokens and replaces them with their corresponding values + */ + format(format?: string): string; + + /** + * Mutates the original datetime by setting it to the start of a unit of time + */ + startOf(unitOfTime: unitOfTime.StartOf): Datetime; + + /** + * Mutates the original moment by setting it to the end of a unit of time + */ + endOf(unitOfTime: unitOfTime.StartOf): Datetime; + + /** + * Mutates the original moment by adding time, by default milliseconds + */ + add(amount?: DurationInputArg1, unit?: DurationInputArg2): Datetime; + + /** + * Mutates the original moment by subtracting time, by default milliseconds + */ + subtract(amount?: DurationInputArg1, unit?: DurationInputArg2): Datetime; + + /** + * Calendar time displays time relative to a given referenceTime (defaults to now) + */ + calendar(time?: DatetimeInput, formats?: CalendarSpec): string; + + /** + * Clones the datetime object + */ + clone(): Datetime; + + /** + * Returns unix timestamp in milliseconds + */ + valueOf(): number; + + /** + * Sets a flag on the original datetime to use local time to display a datetime instead of the original datetime's time + */ + local(keepLocalTime?: boolean): Datetime; + + /** + * Returns true if local flag is set + */ + isLocal(): boolean; + + /** + * Sets a flag on the original datetime to use UTC to display a datetime instead of the original datetime's time + */ + utc(keepLocalTime?: boolean): Datetime; + + /** + * Return true if utc flag is set + */ + isUTC(): boolean; + + /** + * Return true if utc flag is set + */ + isUtc(): boolean; + + parseZone(): Datetime; + + /** + * Return true if the datetime object is valid + */ + isValid(): boolean; + + /** + * Returns the index of the first overflowed unit + * + * 0 - years + * 1 - months + * 2 - days + * 3 - hours + * 4 - minutes + * 5 - seconds + * 6 - milliseconds + */ + invalidAt(): number; + + hasAlignedHourOffset(other?: DatetimeInput): boolean; + + /** + * Returns all the constructor inputs of this datatime object + */ + creationData(): DatetimeCreationData; + + /** + * + */ + parsingFlags(): DatetimeParsingFlags; + + /** + * Gets the year + */ + year(): number; + + /** + * Sets the year + */ + year(y: number): Datetime; + + /** + * Gets the year + * + * @deprecated use year(y) + */ + years(y: number): Datetime; + + /** + * Sets the year + * @deprecated use year() + */ + years(): number; + + /** + * Gets the quarter, 1..4 + */ + quarter(): number; + + /** + * Sets the quarter, 1..4 + */ + quarter(q: number): Datetime; + + /** + * Gets the quarter, 1..4 + */ + quarters(): number; + + /** + * Sets the quarter, 1..4 + */ + quarters(q: number): Datetime; + + /** + * Gets the month, 0..11 + */ + month(): number; + + /** + * Sets the month, 0..11. + * If the range is exceeded, it will bubble up to the year + */ + month(M: number | string): Datetime; + + /** + * Sets the month, 0..11. + * If the range is exceeded, it will bubble up to the year + * + * @deprecated use month(M) + */ + months(M: number | string): Datetime; + + /** + * Gets the month, 0..11 + * + * @deprecated use month() + */ + months(): number; + + /** + * Gets the day of week, 0(Sunday)..6(Saturday) + */ + day(): number; + + /** + * Sets the day of week, 0(Sunday)..6(Saturday). + * If the range is exceeded, it will bubble up to other weeks + */ + day(d: number | string): Datetime; + + /** + * Sets the day of week, 0(Sunday)..6(Saturday). + * If the range is exceeded, it will bubble up to other weeks + */ + days(d: number | string): Datetime; + + /** + * Gets the day of week, 0(Sunday)..6(Saturday) + */ + days(): number; + + /** + * Gets the day of the month, 1..31 + */ + date(): number; + + /** + * Sets the day of the month, 1..31. + * If the range is exceeded, it will bubble up to the months. + */ + date(d: number): Datetime; + + /** + * Gets the day of the month, 1..31 + * + * @deprecated use date(d) + */ + dates(d: number): Datetime; + + /** + * Sets the day of the month, 1..31. + * If the range is exceeded, it will bubble up to the months. + * + * @deprecated use date() + */ + dates(): number; + + /** + * Gets the hour, 0..23 + */ + hour(): number; + + /** + * Sets the hour, 0..23. + * If the range is exceeded, it will bubble up to the day. + */ + hour(h: number): Datetime; + + /** + * Gets the hour, 0..23 + */ + hours(): number; + + /** + * Sets the hour, 0..23. + * If the range is exceeded, it will bubble up to the day. + */ + hours(h: number): Datetime; + + /** + * Gets the minute, 0..59 + */ + minute(): number; + + /** + * Sets the minute, 0..59. + * If the range is exceeded, it will bubble up to the hour. + */ + minute(m: number): Datetime; + + /** + * Gets the minute, 0..59 + */ + minutes(): number; + + /** + * Sets the minute, 0..59. + * If the range is exceeded, it will bubble up to the hour. + */ + minutes(m: number): Datetime; + + /** + * Gets the second, 0..59 + */ + second(): number; + + /** + * Sets the second, 0..59. + * If the range is exceeded, it will bubble up to the minutes. + */ + second(s: number): Datetime; + + /** + * Gets the second, 0..59 + */ + seconds(): number; + + /** + * Sets the second, 0..59. + * If the range is exceeded, it will bubble up to the minutes. + */ + seconds(s: number): Datetime; + + /** + * Gets the millisecond, 0..999 + */ + millisecond(): number; + + /** + * Sets the millisecond, 0..999. + * If the range is exceeded, it will bubble up to the seconds. + */ + millisecond(ms: number): Datetime; + + /** + * Gets the millisecond, 0..999 + */ + milliseconds(): number; + + /** + * Sets the millisecond, 0..999. + * If the range is exceeded, it will bubble up to the seconds. + */ + milliseconds(ms: number): Datetime; + + /** + * Gets the day of the week according to the locale, 0..6. + * If the locale assigns Monday as the first day of the week, datetime().weekday() will be Monday (0). + */ + weekday(): number; + + /** + * Sets the day of the week according to the locale, 0..6. + * If the locale assigns Monday as the first day of the week, datetime().weekday(0) will be Monday. + * If Sunday is the first day of the week, moment().weekday(0) will be Sunday. + */ + weekday(d: number): Datetime; + + /** + * Gets the ISO day of the week, 1(Monday)..7(Sunday) + */ + isoWeekday(): number; + + /** + * Sets the ISO day of the week, 1(Monday)..7(Sunday) + * If the range is exceeded, it will bubble up to other weeks. + */ + isoWeekday(d: number | string): Datetime; + + /** + * Gets the week-year according to the locale + */ + weekYear(): number; + + /** + * Gets or sets the week-year according to the locale + * + */ + weekYear(d: number): Datetime; + + /** + * Gets the ISO week-year + */ + isoWeekYear(): number; + + /** + * Sets the ISO week-year + */ + isoWeekYear(d: number): Datetime; + + /** + * Gets the week of the year, 1..53 + */ + week(): number; + + /** + * Sets the week of the year, 1..53 + */ + week(d: number): Datetime; + + /** + * Gets the week of the year, 1..53 + */ + weeks(): number; + + /** + * Sets the week of the year, 1..53 + */ + weeks(d: number): Datetime; + + /** + * Gets the ISO week of the year, 1..53 + */ + isoWeek(): number; + + /** + * Sets the ISO week of the year, 1..53 + */ + isoWeek(d: number): Datetime; + + /** + * Gets the ISO week of the year, 1..53 + */ + isoWeeks(): number; + + /** + * Sets the ISO week of the year, 1..53 + */ + isoWeeks(d: number): Datetime; + + /** + * Gets the number of weeks according to locale in the current datetime's year + */ + weeksInYear(): number; + + /** + * Gets the number of weeks in the current datetime's year, according to ISO weeks + */ + isoWeeksInYear(): number; + + /** + * Gets the day of the year, 1..366 + */ + dayOfYear(): number; + + /** + * Sets the day of the year, 1..366. + * If the range is exceeded, it will bubble up to the years + */ + dayOfYear(d: number): Datetime; + + /** + * Displays a datetime in relation to a time other than now + */ + from(inp: DatetimeInput, suffix?: boolean): string; + + /** + * Displays the datetime in relation to a time other than now + */ + to(inp: DatetimeInput, suffix?: boolean): string; + + /** + * Displays the datatime in relation to now + */ + fromNow(withoutSuffix?: boolean): string; + + /** + * Displays the datatime in relation to now + */ + toNow(withoutPrefix?: boolean): string; + + /** + * Returns the difference in the given unit, default is milliseconds + */ + diff(b: DatetimeInput, unitOfTime?: unitOfTime.Diff, precise?: boolean): number; + + /** + * Returns an array that mirrors the parameters from new Date() + */ + toArray(): number[]; + + /** + * Conver the datetime to MS-DOS date/time format + */ + toDOS(): MSDOSFormat; + + /** + * Returns a copy of the native Date object that the datetime wraps + */ + toDate(): Date; + + /** + * Formats a string to the ISO8601 standard + */ + toISOString(): string; + + /** + * Returns a machine readable string, that can be evaluated to produce the same datetime + */ + inspect(): string; + + /** + * When serializing a duration object to JSON, it will be represented as an ISO8601 string + */ + toJSON(): string; + + /** + * Returns a Unix timestamp (the number of seconds since the Unix Epoch) + */ + unix(): number; + + /** + * Returns true if that year is a leap year, and false if it is not. + */ + isLeapYear(): boolean; + + /** + * Get the UTC offset in minutes. + */ + utcOffset(): number; + + /** + * Sets the UTC offset + */ + utcOffset(b: number | string, keepLocalTime?: boolean): Datetime; + + isUtcOffset(): boolean; + + /** + * Returns the number of days in the current month + */ + daysInMonth(): number; + + /** + * Checks if the current moment is in daylight saving time + */ + isDST(): boolean; + + /** + * Returns the zone abbreviation + */ + zoneAbbr(): string; + + /** + * Returns the zone name + */ + zoneName(): string; + + /** + * Check if the datetime is before another datetime. + */ + isBefore(inp?: DatetimeInput, granularity?: unitOfTime.StartOf): boolean; + + /** + * Check if the datetime is after another datetime. + */ + isAfter(inp?: DatetimeInput, granularity?: unitOfTime.StartOf): boolean; + + /** + * Check if the datetime is the same as another datetime. + */ + isSame(inp?: DatetimeInput, granularity?: unitOfTime.StartOf): boolean; + + /** + * Check if a datetime is after or the same as another datetime. + */ + isSameOrAfter(inp?: DatetimeInput, granularity?: unitOfTime.StartOf): boolean; + + /** + * Check if a datetime is before or the same as another datetime. + */ + isSameOrBefore(inp?: DatetimeInput, granularity?: unitOfTime.StartOf): boolean; + + /** + * Check if a datetime is between two other datetimes, optionally looking at unit scale (minutes, hours, days, etc). + * The match is exclusive. + */ + isBetween(a: DatetimeInput, b: DatetimeInput, granularity?: unitOfTime.StartOf, inclusivity?: "()" | "[)" | "(]" | "[]"): boolean; + + /** + * Returns the using locale + */ + locale(): string; + + /** + * Sets a new locale + */ + locale(locale: LocaleSpecifier): Datetime; + + /** + * Returns the data of the using locale + */ + localeData(): Locale; + + /** + * @deprecated no reliable implementation + */ + isDSTShifted(): boolean; + + /** + * Returns the value of the given unit + */ + get(unit: unitOfTime.All): number; + + /** + * Sets the value of the given unit + */ + set(unit: unitOfTime.All, value: number): Datetime; + + /** + * Sets the values of the given units represented as an object + */ + set(objectLiteral: DatetimeSetObject): Datetime; + + /** + * Returns an object containing year, month, day-of-month, hour, minute, seconds, milliseconds. + */ + toObject(): DatetimeObjectOutput; + } + + interface DatetimeFunction { + (inp?: DatetimeInput, format?: DatetimeFormatSpecification, strict?: boolean): Datetime; + (inp?: DatetimeInput, format?: DatetimeFormatSpecification, language?: string, strict?: boolean): Datetime; + + /** + * Creates a datetime in UTC + */ + utc(inp?: DatetimeInput, format?: DatetimeFormatSpecification, strict?: boolean): Datetime; + utc(inp?: DatetimeInput, format?: DatetimeFormatSpecification, language?: string, strict?: boolean): Datetime; + + /** + * Creates a datetime from the given UNIX timestamp + */ + unix(timestamp: number): Datetime; + + /** + * Creates a datetime from the given MS-DOS date and time + */ + dos(inp: MSDOSFormat): Datetime; + + /** + * Crates an invalid datetime object + */ + invalid(flags?: DatetimeParsingFlagsOpt): Datetime; + + /** + * Checks whether the given object is a Duration + */ + isDuration(d: any): d is Duration; + + /** + * Changes the using locale + */ + locale(language?: string): string; + + /** + * Changes the using locale, will use the first one it has localizations for. + */ + locale(language?: string[]): string; + + /** + * Changes the using locale with customization + */ + locale(language?: string, definition?: LocaleSpecification | null): string; + + /** + * Returns a locale by the given key or the current locale + */ + localeData(key?: string | string[]): Locale; + + /** + * Creates a new Duration object + */ + duration(inp?: DurationInputArg1, unit?: DurationInputArg2): Duration; + + parseZone(inp?: DatetimeInput, format?: DatetimeFormatSpecification, strict?: boolean): Datetime; + parseZone(inp?: DatetimeInput, format?: DatetimeFormatSpecification, language?: string, strict?: boolean): Datetime; + + /** + * Returns the months of the current locale + */ + months(): string[]; + + /** + * Returns a month of the current locale at the given index + */ + months(index: number): string; + + months(format: string): string[]; + months(format: string, index: number): string; + + /** + * Returns the short form of the months of the current locale + */ + monthsShort(): string[]; + + monthsShort(index: number): string; + monthsShort(format: string): string[]; + monthsShort(format: string, index: number): string; + + /** + * Returns the weekdays of the current locale + */ + weekdays(): string[]; + weekdays(index: number): string; + weekdays(format: string): string[]; + weekdays(format: string, index: number): string; + weekdays(localeSorted: boolean): string[]; + weekdays(localeSorted: boolean, index: number): string; + weekdays(localeSorted: boolean, format: string): string[]; + weekdays(localeSorted: boolean, format: string, index: number): string; + + /** + * Returns the short form of the weekdays of the current locale + */ + weekdaysShort(): string[]; + weekdaysShort(index: number): string; + weekdaysShort(format: string): string[]; + weekdaysShort(format: string, index: number): string; + weekdaysShort(localeSorted: boolean): string[]; + weekdaysShort(localeSorted: boolean, index: number): string; + weekdaysShort(localeSorted: boolean, format: string): string[]; + weekdaysShort(localeSorted: boolean, format: string, index: number): string; + + /** + * Returns the min form of the weekdays of the current locale + */ + weekdaysMin(): string[]; + weekdaysMin(index: number): string; + weekdaysMin(format: string): string[]; + weekdaysMin(format: string, index: number): string; + weekdaysMin(localeSorted: boolean): string[]; + weekdaysMin(localeSorted: boolean, index: number): string; + weekdaysMin(localeSorted: boolean, format: string): string[]; + weekdaysMin(localeSorted: boolean, format: string, index: number): string; + + /** + * Returns the minimum of the given datetimes + */ + min(...datetimes: DatetimeInput[]): Datetime; + + /** + * Returns the maximum of the given datetimes + */ + max(...datetimes: DatetimeInput[]): Datetime; + + /** + * Returns the number of milliseconds since the Unix epoch (January 1, 1970) + */ + now(): number; + + /** + * Defines a new locale + */ + defineLocale(language: string, localeSpec: LocaleSpecification | null): Locale; + + /** + * Updates an existing locale + */ + updateLocale(language: string, localeSpec: LocaleSpecification | null): Locale; + + /** + * Returns a list of the defined locales (lazy-loaded locales are not listed until they are loaded) + */ + locales(): string[]; + + /** + * Returns the original name of the given unit alias + */ + normalizeUnits(unit: unitOfTime.All): string; + + relativeTimeThreshold(threshold: string): number; + relativeTimeThreshold(threshold: string, limit: number): boolean; + relativeTimeRounding(fn: (num: number) => number): boolean; + relativeTimeRounding(): (num: number) => number; + + calendarFormat(m: Datetime, now: Datetime): string; + + /** + * Default format for datetime.format() + */ + defaultFormat: string; + + /** + * Default utc format for datetime.format() + */ + defaultFormatUtc: string; + } + } + } + + /** + * Creates a new datetime object + */ + const datetime: I.datetime.DatetimeFunction; +} diff --git a/types/adone/glosses/events.d.ts b/types/adone/glosses/events.d.ts new file mode 100644 index 0000000000..ecb323f925 --- /dev/null +++ b/types/adone/glosses/events.d.ts @@ -0,0 +1,38 @@ +declare namespace adone { + namespace event { + class EventEmitter { + static listenerCount(emitter: EventEmitter, event: string | symbol): number; + static defaultMaxListeners: number; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Array<(...args: any[]) => any>; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): Array; + listenerCount(type: string | symbol): number; + } + + class AsyncEmitter extends EventEmitter { + constructor(concurrency?: number); + + setConcurrency(max?: number): this; + + emitParallel(event: string, ...args: any[]): Promise; + + emitSerial(event: string, ...args: any[]): Promise; + + emitReduce(event: string, ...args: any[]): Promise; + + emitReduceRight(event: string, ...args: any[]): Promise; + + subscribe(event: string, listener: (...args: any[]) => void, once?: boolean): () => void; + } + } +} diff --git a/types/adone/glosses/exceptions.d.ts b/types/adone/glosses/exceptions.d.ts new file mode 100644 index 0000000000..347a3c632d --- /dev/null +++ b/types/adone/glosses/exceptions.d.ts @@ -0,0 +1,37 @@ +declare namespace adone { + namespace x { + class Exception extends Error { + constructor(message?: string | Error, captureStackTrace?: boolean); + } + class Runtime extends Exception { } + class IncompleteBufferError extends Exception { } + class NotImplemented extends Exception { } + class IllegalState extends Exception { } + class NotValid extends Exception { } + class Unknown extends Exception { } + class NotExists extends Exception { } + class Exists extends Exception { } + class Empty extends Exception { } + class InvalidAccess extends Exception { } + class NotSupported extends Exception { } + class InvalidArgument extends Exception { } + class InvalidNumberOfArguments extends Exception { } + class NotFound extends Exception { } + class Timeout extends Exception { } + class Incorrect extends Exception { } + class NotAllowed extends Exception { } + class LimitExceeded extends Exception { } + class Encoding extends Exception { } + class Network extends Exception { } + class Bind extends Exception { } + class Connect extends Exception { } + class Database extends Exception { } + class DatabaseInitialization extends Exception { } + class DatabaseOpen extends Exception { } + class DatabaseRead extends Exception { } + class DatabaseWrite extends Exception { } + class NetronIllegalState extends Exception { } + class NetronPeerDisconnected extends Exception { } + class NetronTimeout extends Exception { } + } +} diff --git a/types/adone/glosses/fast.d.ts b/types/adone/glosses/fast.d.ts new file mode 100644 index 0000000000..725e0e9db3 --- /dev/null +++ b/types/adone/glosses/fast.d.ts @@ -0,0 +1,745 @@ +declare namespace adone { + /** + * Filesystem Automation Streaming Templates/Transforms + */ + namespace fast { + // File is based on vinyl typings + // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/vinyl/index.d.ts + + namespace I { + interface FileConstructorOptions { + /** + * The current workring directory of the file. Default: process.cwd() + */ + cwd?: string; + + /** + * Full path to the file + */ + path?: string; + + /** + * Stores the path history + */ + history?: string[]; + + /** + * The result of a fs.Stat call + */ + stat?: fs.I.Stats; + + /** + * File contents + */ + contents?: null | Buffer | nodestd.stream.Readable; + + /** + * Used for relative pathing. Typically where a glob starts. Default: options.cwd + */ + base?: string; + + symlink?: string; + } + + interface FileCloneOptions { + contents?: boolean; + deep?: boolean; + } + + interface FileConstructor { + new(options: FileConstructorOptions & { contents: Buffer }): BufferFile; + new(options: FileConstructorOptions & { contents: nodestd.stream.Readable }): StreamFile; + new(options?: FileConstructorOptions): NullFile; + + prototype: File; + } + + interface File { + /** + * Gets and sets the contents of the file + */ + contents: null | Buffer | nodestd.stream.Readable; + + /** + * Gets and sets current working directory. Will always be normalized and have trailing separators removed. + */ + cwd: string; + + /** + * Gets and sets base directory. Used for relative pathing (typically where a glob starts). + */ + base: string; + + /** + * Gets and sets the absolute pathname string or `undefined`. Setting to a different value + * appends the new path to `file.history`. If set to the same value as the current path, it + * is ignored. All new values are normalized and have trailing separators removed. + */ + path: string; + + stat: fs.I.Stats; + + /** + * Gets the result of `path.relative(file.base, file.path)`. Or sets a new relative path for file.base + */ + relative: string; + + /** + * Gets and sets the dirname of `file.path`. Will always be normalized and have trailing + * separators removed. + */ + dirname: string; + + /** + * Gets and sets the basename of `file.path`. + */ + basename: string; + + /** + * Gets and sets extname of `file.path`. + */ + extname: string; + + /** + * Gets and sets stem (filename without suffix) of `file.path`. + */ + stem: string; + + /** + * Array of `file.path` values the file has had, from `file.history[0]` (original) + * through `file.history[file.history.length - 1]` (current). `file.history` and its elements + * should normally be treated as read-only and only altered indirectly by setting `file.path`. + */ + readonly history: ReadonlyArray; + + /** + * Gets and sets the path where the file points to if it's a symbolic link. Will always + * be normalized and have trailing separators removed. + */ + symlink: string; + + /** + * Returns a new File object with all attributes cloned. + */ + clone(options: FileCloneOptions & { contents: true }): this; + clone(options?: FileCloneOptions): File; + + isBuffer(): boolean; + + isStream(): boolean; + + isNull(): boolean; + + isDirectory(): boolean; + + isSymbolic(): boolean; + } + + interface NullFile extends File { + contents: null; + } + + interface BufferFile extends File { + contents: Buffer; + // + } + + interface StreamFile extends File { + contents: nodestd.stream.Readable; + } + + type DirectoryFile = File; + type SymbolicFile = File; + + /* tslint:disable-next-line:no-empty-interface */ + interface Stream extends stream.CoreStream { + // + } + } + + export const File: I.FileConstructor; + + namespace I { + type CoreStreamSource = stream.I.CoreStream.Source; + + interface LocalStreamConstructorOptions { + /** + * Whether to read files. Default: true + */ + read?: boolean; + + /** + * Read files as buffers. Default: true + */ + buffer?: boolean; + + /** + * Read files as streams + */ + stream?: boolean; + + /** + * Current working directory for files. Default: process.cwd() + */ + cwd?: string; + } + + interface LocalStreamConstructor { + new(source: CoreStreamSource | File[], options: LocalStreamConstructorOptions & { read: false }): LocalStream; + new(source: CoreStreamSource | File[], options: LocalStreamConstructorOptions & { stream: true }): LocalStream; + new(source: CoreStreamSource | File[], options?: LocalStreamConstructorOptions): LocalStream; + + prototype: LocalStream; + } + + interface LocalStreamDestOptions { + /** + * Mode that is used for writing + */ + mode?: number; + + /** + * Flag that is used for writing + */ + flag?: fs.I.Flag; + + /** + * Current working directory for files, dest is resolved using this cwd. Default: constuctor cwd or process.cwd() + */ + cwd?: string; + + /** + * Whether to push written files into the stream + */ + produceFiles?: boolean; + + /** + * Whether to inherit the source file's mode (access properties) + */ + originMode?: boolean; + + /** + * Whether to inherit the source file's time properties (atime, mtime) + */ + originTimes?: boolean; + + /** + * Whether to inherit the source file's uid and gid + */ + originOwner?: boolean; + } + + interface LocalStream extends Stream { + /** + * Writes all files into the given directory + * + * @param directory directory where to write files + */ + dest(directory: string, options?: LocalStreamDestOptions): this; + + /** + * Writes all files into the given directory using the given callback + * + * @param getDirectory callback that returns a directory for each file + */ + dest(getDirectory: (file: T) => string, options?: LocalStreamDestOptions): this; + } + } + + export const LocalStream: I.LocalStreamConstructor; + + namespace I { + interface SrcOptions extends LocalStreamConstructorOptions { + /** + * Used for relative pathing of files. Typically where a glob starts. + */ + base?: string; + + /** + * Whether to match dotted files (hidden). Default: true + */ + dot?: boolean; + + /** + * Whether to lstat instead of stat when stating. Default: false + */ + links?: boolean; + } + } + + /** + * @param globs Source file/files + */ + function src(globs: string | string[], options: I.SrcOptions & { read: false }): I.LocalStream; + function src(globs: string | string[], options: I.SrcOptions & { stream: true }): I.LocalStream; + function src(globs: string | string[], options?: I.SrcOptions): I.LocalStream; + + namespace I { + type WatcherConstructorOptions = fs.I.Watcher.ConstructorOptions; + + interface WatchOptions extends WatcherConstructorOptions, LocalStreamConstructorOptions { + /** + * Used for relative pathing of files. Typically where a glob starts. + */ + base?: string; + + /** + * Whether to match dotted files (hidden). Default: true + */ + dot?: boolean; + + /** + * Whether to resume the stream on the next tick. Default: true + */ + resume?: boolean; + } + } + + /** + * @param globs Source file/files + */ + function watch(globs: string | string[], options: I.WatchOptions & { read: false }): I.LocalStream; + function watch(globs: string | string[], options: I.WatchOptions & { stream: true }): I.LocalStream; + function watch(globs: string | string[], options?: I.WatchOptions): I.LocalStream; + + namespace I { + interface LocalMapStream extends Stream { + dest(options?: LocalStreamDestOptions): this; + } + + interface Mapping { + /** + * Source file/files + */ + from: string; + + /** + * Destination directory + */ + to: string; + } + + interface MapOptions extends LocalStreamConstructorOptions { + /** + * Used for relative pathing of files. Typically where a glob starts. + */ + base?: string; + + /** + * Whether to match dotted files (hidden). Default: true + */ + dot?: boolean; + } + + type WatchMapOptions = MapOptions & WatcherConstructorOptions; + + type MapSource = Mapping | Mapping[]; + } + + /** + * The same as fast.src, but source and dest paths are defined in one place + */ + function map(mappings: I.MapSource, options: I.MapOptions & { read: false }): I.LocalMapStream; + function map(mappings: I.MapSource, options: I.MapOptions & { stream: true }): I.LocalMapStream; + function map(mappings: I.MapSource, options?: I.MapOptions): I.LocalMapStream; + + function watchMap(mappings: I.MapSource, options: I.WatchMapOptions & { read: false }): I.LocalMapStream; + function watchMap(mappings: I.MapSource, options: I.WatchMapOptions & { stream: true }): I.LocalMapStream; + function watchMap(mappings: I.MapSource, options?: I.WatchMapOptions): I.LocalMapStream; + + // plugins + + namespace I { + namespace plugin.compressor { + type Compressor = "gz" | "deflate" | "brotli" | "lzma" | "xz" | "snappy"; // TODO keyof adone.compressor ? + } + + interface Stream { + /** + * Compresses all files using the given compressor + */ + compress(this: {}, type: plugin.compressor.Compressor, options?: { + /** + * Whether to rename files, adds corresponding extname + */ + rename?: boolean, + [key: string]: any + }): this; + + /** + * Decompresses all files using the given compressor + */ + decompress(type: plugin.compressor.Compressor, options?: object): this; + } + + namespace plugin.archive { + type Archiver = "tar" | "zip"; // TODO keyof adone.archive ? + } + + interface Stream { + /** + * Packs all files into one archive of the given type + */ + pack(type: plugin.archive.Archiver, options?: object): this; + + /** + * Unpacks the incoming files using the given archive type + */ + unpack(type: plugin.archive.Archiver, options?: object): this; + + /** + * transpiles files + */ + transpile(options: object): this; // TODO adone.js.transpiler options + + /** + * Deletes lines from files + */ + deleteLines(filters: RegExp | RegExp[]): this; + + /** + * sets new filename + */ + rename(filename: string): this; + rename(handle: { + dirname?: string, + prefix?: string, + basename?: string, + extname?: string + }): this; + rename(handler: (handle: { + dirname: string, + basename: string, + extname: string + }) => void): this; + + /** + * concats all files into one + */ + concat(file: string | { path: string }, options?: { + newLine?: string + }): this; + + // flatten(options?: { + // newPath?: string, + // includeParents?: number | [number, number], + // subPath?: number | [number, number], + // }): this; + } + + namespace plugin.sourcemaps { + interface WriteOptions { + /** + * By default the source maps include the source code. Pass false to use the original files + */ + includeContent?: boolean; + + /** + * By default a comment containing / referencing the source map is added. + * Set this to false to disable the comment (e.g. if you want to load the source maps by header) + */ + addComment?: boolean; + + /** + * Sets the charset for inline source maps + */ + charset?: fs.I.Encoding; + + /** + * Set the location where the source files are hosted (use this when includeContent is set to false) + */ + sourceRoot?: string | ((file: T) => string); + + /** + * Function that is called for every source and receives the default source path as a parameter and the original file + */ + mapSources?(path: string, file: T): string; + mapSourcesAbsolute?: boolean; + + /** + * This option allows to rename the map file. + * It takes a function that is called for every map and receives the default map path as a parameter + */ + mapFile?(file: T): string; + + /** + * Set the destination path + */ + destPath?: string; + + /** + * Clone options + */ + clone?: FileCloneOptions; + + /** + * Specify a prefix to be prepended onto the source map URL when writing external source maps. + */ + sourceMappingURLPrefix?: string | ((file: T) => string); + + /** + * The output of the function must be the full URL to the source map (in function of the output file) + */ + sourceMappingURL?(file: T): string; + } + } + + interface Stream { + sourcemapsInit(options?: { + /** + * Whether to load existing sourcemaps + */ + loadMaps?: boolean, + + /** + * Whether to generate initial sourcemaps instead of using empty sourcemap + */ + identityMap?: boolean, + + largeFile?: boolean + }): this; + + /** + * + * + * @param dest destination directory + */ + sourcemapsWrite(dest: string, options?: plugin.sourcemaps.WriteOptions): this; + sourcemapsWrite(options?: plugin.sourcemaps.WriteOptions): this; + } + + namespace plugin.wrap { + interface Options { + /** + * Set to explicit false value to disable automatic JSON, JSON5 and YAML parsing + */ + parse?: boolean; + escape?: RegExp; + evaluate?: RegExp; + imports?: object; + interpolate?: RegExp; + sourceURL?: string; + variable?: string; + } + + interface TemplateFunctionData extends Options { + file: T; + contents: object; + [custom: string]: any; + } + } + + interface Stream { + /** + * Wraps contents + */ + wrap( + template: { src: string } | string | ((data: plugin.wrap.TemplateFunctionData) => string), + data?: object | ((file: T) => object), + options?: plugin.wrap.Options | ((file: T) => plugin.wrap.Options) + ): this; + + /** + * Replaces contents + */ + replace(search: string, replacement: string | ((search: string) => string)): this; + replace(search: RegExp, replacement: string): this; + replace(search: Array, replacement: Array string)>): this; + + /** + * Static asset revisioning by appending content hash to filenames + */ + revisionHash(options?: { + manifest: { + path?: string, + merge?: boolean + transformer?: { + parse(str: string): any; + stringify(obj: any): string; + } + } + }): this; + + /** + * Rewrite occurrences of filenames which have been renamed by revisionHash + */ + revisionHashReplace(options?: { + /** + * Use canonical Uris when replacing filePaths, + * i.e. when working with filepaths with non forward slash (/) path separators + * we replace them with forward slash. + * Default: true + */ + canonicalUris?: boolean, + + /** + * Add the prefix string to each replacement + */ + prefix?: string, + + /** + * Only substitute in new filenames in files of these types + * Default: ['.js', '.css', '.html', '.hbs'] + */ + replaceExtensions?: string[], + + /** + * Read JSON manifests written out by revisionHash + */ + manifest?: File[] | stream.CoreStream, + + /** + * Modify the name of the unreved files before using them + */ + modifyUnreved?(path: string): string, + + /** + * Modify the name of the reved files before using them + */ + modifyReved?(path: string): string + }): this; + } + + namespace plugin.chmod { + interface Access { + /** + * Whether to have read access + */ + read?: boolean; + + /** + * Whether to have write access + */ + write?: boolean; + + /** + * Whether to ahve execute access + */ + execute?: boolean; + } + + interface Mode { + /** + * Owner properties + */ + owner?: Access; + + /** + * Group properties + */ + group?: Access; + + /** + * Others properties + */ + others?: Access; + } + } + + interface Stream { + /** + * Changes file mode + */ + chmod(mode?: number | plugin.chmod.Mode, dirMode?: number | plugin.chmod.Mode): this; + } + + namespace plugin.notify { + interface Options { + notifier?: object; // TODO adone.notifier + + host?: string; + appName?: string; + port?: number; + + /** + * Filter out files + */ + filter?(file: T): boolean; + + /** + * Whether to emit an error when the stream emits an error. Default: false + */ + emitError?: boolean; + + /** + * Whether to notify on the last file. Default: false + */ + onLast?: boolean; + + /** + * Whether to debounce notifications. Accepts a number as timeout or debounce options + * Default: undefined + */ + debounce?: number | util.I.DebounceOptions & { + /** + * debounce timeout + */ + timeout: number + }; + + /** + * Object passed to the lodash template, for additional properties passed to the template + */ + templateOptions?: object; + + /** + * Whether to use console notifications (print a message to console) + */ + console?: boolean; + + /** + * Whether to use GUI notifications (notify-send/toaster/etc) + */ + gui?: boolean; + + /** + * Notification title + */ + title?: string | ((file: T) => string); + + /** + * Notification subtitle + */ + subtitle?: string | ((file: T) => string); + + open?: string | ((file: T) => string); + + /** + * Notification message + */ + message?: string | ((file: T) => string); + } + + interface OnErrorOptions extends Options { + /** + * Whether to end the stream when an error occurs + */ + endStream?: boolean; + } + + type OptionsArg = string | O | (() => O); + } + + interface Stream { + /** + * Notify about passing through files + */ + notify(options?: plugin.notify.OptionsArg>): this; + + /** + * Notify about errors + */ + notifyError(options?: plugin.notify.OptionsArg>): this; + } + } + + namespace plugin { + namespace notify { + /** + * Creates a callback that can be used as a reporter for errors + */ + function onError(options?: I.plugin.notify.OptionsArg>): (error: T) => void; + } + } + } +} diff --git a/types/adone/glosses/fs.d.ts b/types/adone/glosses/fs.d.ts new file mode 100644 index 0000000000..7fa8f51593 --- /dev/null +++ b/types/adone/glosses/fs.d.ts @@ -0,0 +1,1728 @@ +declare namespace adone { + /** + * File system stuff + */ + namespace fs { + namespace I { + type URL = nodestd.url.URL; + type Stats = nodestd.fs.Stats; + type Flag = "r" | "r+" | "rs+" | "w" | "wx" | "w+" | "wx+" | "a" | "ax" | "a+" | "ax+"; + type Encoding = "ascii" | "utf8" | "utf16le" | "usc2" | "base64" | "latin1" | "binary" | "hex"; + type SymlinkType = "dir" | "file" | "junction"; + type ReadStream = nodestd.fs.ReadStream; + type WriteStream = nodestd.fs.WriteStream; + type FD = number; + } + + /** + * Reads the value of a symbolic link + */ + function readlink(path: string | Buffer | I.URL, encoding: null): Promise; + function readlink(path: string | Buffer | I.URL, encoding: I.Encoding): Promise; + function readlink(path: string | Buffer | I.URL, options: { encoding: null }): Promise; + function readlink(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): Promise; + + /** + * Deletes a name and possibly the file it refers to + */ + function unlink(path: string | Buffer | I.URL): Promise; + + /** + * Deletes a name and possibly the file it refers to + */ + function unlinkSync(path: string | Buffer | I.URL): void; + + /** + * Changes permissions of a file + */ + function chmod(path: string | Buffer | I.URL, mode: number): Promise; + + /** + * Changes ownership of a file + */ + function chown(path: string | Buffer | I.URL, uid: number, gid: number): Promise; + + /** + * Deletes a directory + */ + function rmdir(path: string | Buffer | I.URL): Promise; + + /** + * Reads a directory + */ + function readdir(path: string | Buffer | I.URL, encoding: null): Promise; + function readdir(path: string | Buffer | I.URL, encoding: I.Encoding): Promise; + function readdir(path: string | Buffer | I.URL, options: { encoding: null }): Promise; + function readdir(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): Promise; + + /** + * Reads a directory + */ + function readdirSync(path: string | Buffer | I.URL, encoding: null): Buffer[]; + function readdirSync(path: string | Buffer | I.URL, encoding: I.Encoding): string[]; + function readdirSync(path: string | Buffer | I.URL, options: { encoding: null }): Buffer[]; + function readdirSync(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): string[]; + + /** + * Gets file status, identical to stat, except that if pathname is a symbolic link, + * then it returns information about the link itself, not the file that it refers to + */ + function lstat(path: string | Buffer | I.URL): Promise; + + /** + * Gets file status, identical to stat, except that if pathname is a symbolic link, + * then it returns information about the link itself, not the file that it refers to + */ + function lstatSync(path: string | Buffer | I.URL): I.Stats; + + /** + * Gets file status + */ + function stat(path: string | Buffer | I.URL): Promise; + + /** + * Gets file status + */ + function statSync(path: string | Buffer | I.URL): I.Stats; + + /** + * Truncates file to the given length + */ + function truncate(path: string | Buffer, length?: number): Promise; + + /** + * Writes data to a file, replacing the file if it already exists + */ + function writeFile(file: string | Buffer | number, data: string | Buffer | Uint8Array, options?: { + encoding?: I.Encoding, + mode?: number, + flag?: I.Flag + }): Promise; + + /** + * Writes data to a file, replacing the file if it already exists + */ + function writeFileSync(file: string | Buffer | number, data: string | Buffer | Uint8Array, options?: { + encoding?: I.Encoding, + mode?: number, + flag?: I.Flag + }): void; + + /** + * Appends data to a file, creating the file if it does not yet exist + */ + function appendFile(file: string | Buffer | number, data: string | Buffer, options?: { + encoding?: I.Encoding, + mode?: number, + flag?: I.Flag + }): Promise; + + /** + * Tests a user's permissions for the file or directory specified by path + */ + function access(file: string | Buffer | I.URL, mode?: number): Promise; + + /** + * Tests a user's permissions for the file or directory specified by path + */ + function accessSync(file: string | Buffer | I.URL, mode?: number): void; + + /** + * Makes a new name for a file + */ + function symlink(target: string | Buffer | I.URL, path: string | Buffer | I.URL, type?: I.SymlinkType): Promise; + + /** + * Recursively deletes the given path, that can be a glob pattern + */ + function rm(path: string, options?: { + /** + * Whether to consider the given path as a glob pattern + */ + glob?: boolean, + /** + * Maximum busy tries, errors when cannot remove a file due to EBUSY, ENOTEMPTY, EPERM + */ + maxBusyTries?: number, + /** + * The delay to wait between busy tries + */ + emfileWait?: number + /** + * cwd to use + */ + cwd?: string + }): Promise; + + namespace I { + interface Access { + read: boolean; + write: boolean; + execute: boolean; + } + } + + /** + * Represents the permissions of a file + */ + class Mode { + stat: I.Stats; + owner: I.Access; + group: I.Access; + others: I.Access; + + constructor(stat: I.Stats); + + valueOf(): number; + } + + /** + * Represents a file + */ + class File { + constructor(...path: string[]); + + /** + * Sets the file encoding + */ + encoding(name: I.Encoding | "buffer"): this; + + /** + * Returns the file stats + */ + stat(): Promise; + + /** + * Returns the file stats synchronously + */ + statSync(): I.Stats; + + /** + * Returns the files stats, for links the link stats + */ + lstat(): Promise; + + /** + * Returns the files stats, for links the link stats, works synchronously + */ + lstatSync(): I.Stats; + + /** + * Returns the file mode + */ + mode(): Mode; + + /** + * Returns the file absoulte path + */ + path(): string; + + /** + * Returns normalized file path, with only / and removed redundant slashes + */ + normalizedPath(): string; + + /** + * Returns the file dirname + */ + dirname(): string; + + /** + * Returns the filename + */ + filename(): string; + + /** + * Returns the file extension + */ + extname(): string; + + /** + * Returns the filename with no extension + */ + stem(): string; + + /** + * Returns a relative path + */ + relativePath(path: string | Directory): string; + + /** + * Returns true if the file exists, visible by the process + */ + exists(): Promise; + + /** + * Creates the file, writes an empty string + */ + create(options?: { mode?: number }): Promise; + + /** + * Writes the given data to the file + */ + write(buffer: string | Buffer, options?: { encoding?: I.Encoding, mode?: number, flag?: I.Flag }): Promise; + + /** + * Appends the given data to the file + */ + append(buffer: string | Buffer, options?: { encoding?: I.Encoding, mode?: number, flag?: I.Flag }): Promise; + + /** + * Removes the file + */ + unlink(): Promise; + + /** + * Returns the contents as a buffer + */ + contents(encoding: "buffer"): Promise; + + /** + * Returns the contents as a string + */ + contents(encoding?: I.Encoding): Promise; + + /** + * Returns the contents as a buffer synchronously + */ + contentsSync(encoding: "buffer"): Buffer; + + /** + * Returns the contents as a string synchronously + */ + contentsSync(encoding?: I.Encoding): string; + + /** + * Returns a read stream for this file + */ + contentsStream(encoding?: "buffer" | I.Encoding): I.ReadStream; + + /** + * Changes the file premissions + */ + chmod(mode: number | Mode): Promise; + + /** + * Renames the file + */ + rename(name: string | File): Promise; + + /** + * Creates a symbolic link to this file + */ + symbolicLink(path: string | File): SymbolicLinkFile; + + /** + * Returns the file size in bytes + */ + size(): Promise; + } + + namespace I.Directory { + interface AddFileOptions { + contents?: string | Buffer; + encoding?: string; + mode?: number; + } + } + + /** + * Represents a directory + */ + class Directory { + constructor(...path: string[]); + + /** + * Returns dirname + */ + dirname(): string; + + /** + * Returns filename + */ + filename(): string; + + /** + * Returns absoulte path + */ + path(): string; + + /** + * Returns normalized file path, with only / and removed redundant slashes + */ + normalizedPath(): string; + + /** + * Returns relative path + */ + relativePath(path: string | Directory): string; + + /** + * Returns directory stats + */ + stat(): Promise; + + /** + * Returns the files stats, for links the link stats + */ + lstat(): Promise; + + /** + * Returns true if the directory exists + */ + exists(): Promise; + + /** + * Creates the directory if doesnt exist + */ + create(options?: { mode?: number }): Promise; + + /** + * Returns path relative to this directory + */ + resolve(...path: string[]): string; + + /** + * Returns directory relative to this directory + */ + getDirectory(...path: string[]): Directory; + + /** + * Returns file relative to this directory + */ + getFile(...path: string[]): File; + + /** + * Returns file that is a symbolic link + */ + getSymbolicLinkFile(...path: string[]): SymbolicLinkFile; + + /** + * Returns directory that is a symbolic link + */ + getSymbolicLinkDirectory(...path: string[]): SymbolicLinkDirectory; + + /** + * Adds a new file + */ + addFile(filename: string, options?: I.Directory.AddFileOptions): Promise; + addFile(a: string, filename: string, options?: I.Directory.AddFileOptions): Promise; + addFile(a: string, b: string, filename: string, options?: I.Directory.AddFileOptions): Promise; + addFile(a: string, b: string, c: string, filename: string, options?: I.Directory.AddFileOptions): Promise; + addFile(a: string, b: string, c: string, d: string, filename: string, options?: I.Directory.AddFileOptions): Promise; + addFile(a: string, ...filename: Array>): Promise; + + /** + * Adds a new directory + */ + addDirectory(...path: string[]): Promise; + + /** + * Returns files inside this directory + */ + files(): Promise>; + + /** + * Returns files inside this directory synchronously + */ + filesSync(): Array; + + /** + * Deletes all the file inside this directory, but not the directory + */ + clean(): Promise; + + /** + * Deletes the directory + */ + unlink(options?: { retries?: number, delay?: number }): Promise; + + /** + * Searches all nested files and directories + */ + find(options?: { files?: boolean, dirs?: boolean }): Promise>; + + /** + * Searches all nested files and directories synchronously + */ + findSync(options?: { files?: boolean, dirs?: boolean }): Array; + + /** + * Renames the directory + */ + rename(name: string | Directory): Promise; + + /** + * Create a symbolic link for this directory + */ + symbolicLink(path: string | Directory): Promise; + + /** + * Copies this from this directory to the given path + */ + copyTo(destPath: string, options?: I.CopyOptions): Promise; + + /** + * Copies files from the given path to this directory + */ + copyFrom(srcPath: string, options?: I.CopyOptions): Promise; + + /** + * Creates a new directory with the given path + */ + static create(...path: string[]): Promise; + + /** + * Creates a new temporary directory + */ + static createTmp(options?: I.TmpNameOptions): Promise; + } + + /** + * Represents a file that is a symbolic link to another file + */ + class SymbolicLinkFile extends File { + /** + * Returns the path of the file it refers to + */ + realpath(): Promise; + + /** + * Returns the contents of the original file as a buffer + */ + contents(encoding: "buffer"): Promise; + + /** + * Returns the contents of the original file as a string + */ + contents(encoding?: I.Encoding): Promise; + + /** + * Returns the contents of the original file as a buffer synchronously + */ + contentsSync(encoding: "buffer"): Buffer; + + /** + * Returns the contents of the original file as a string synchronously + */ + contentsSync(encoding?: I.Encoding): string; + + /** + * Returns a read stream for the original file + */ + contentsStream(encoding?: "buffer" | I.Encoding): I.ReadStream; + } + + /** + * Represents a directory that is a symbolic link to another directory + */ + class SymbolicLinkDirectory extends Directory { + /** + * Returns the path of the directory it refers to + */ + realpath(): Promise; + + /** + * Removes the link, not the directory it refers to + */ + unlink(): Promise; + } + + namespace I.RandomAccessFile { + interface ConstructorOptions { + /** + * Whether the file should be open as readable + */ + readable?: boolean; + /** + * Whether the file should be open as writable + */ + writable?: boolean; + /** + * Whether the file should be open as appendable + */ + appendable?: boolean; + /** + * Predefined mtime + */ + mtime?: number; + /** + * Predefined atime + */ + atime?: number; + /** + * Base direcotry for the file + */ + cwd?: string; + } + } + + /** + * Represents a file that supports random access + */ + class RandomAccessFile extends event.EventEmitter { + constructor(filename: string, options?: I.RandomAccessFile.ConstructorOptions); + + /** + * Reads a buffer at the given offset + */ + read(length: number, offset?: number): Promise; + + /** + * Writes the given buffer at the given offset + */ + write(buf: string | Buffer, offset?: number): Promise; + + /** + * Closes the file + */ + close(): Promise; + + /** + * Writes atime and mtime properties of the file + */ + end(options?: { atime?: number, mtime?: number }): Promise; + + /** + * Truncates the file to the given length + */ + truncate(size: number): Promise; + + /** + * Removes this file + */ + unlink(): Promise; + + /** + * Opens the given file with the given options + */ + static open(filename: string, options?: I.RandomAccessFile.ConstructorOptions): Promise; + } + + /** + * Represents an abstract random access reader + */ + class AbstractRandomAccessReader extends event.EventEmitter { + /** + * Increments the reference counter + */ + ref(): void; + + /** + * Decrements the reference counter + */ + unref(): void; + + /** + * Creates a readable stream for the given range + */ + createReadStream(options?: { + /** + * Start offset, inslusive + */ + start?: number, + + /** + * End offset, exclusive + */ + end?: number + }): nodestd.stream.Readable; + + /** + * Reads data and writes to the given buffer + * + * @param buffer buffer to write to + * @param offset buffer offset to write to + * @param length number of bytes to read + * @param position position to read from + */ + read(buffer: Buffer, offset: number, length: number, position: number): Promise; + + /** + * Must be implemented in derived classes and return a readable stream for the given range [start, end] + */ + _readStreamFromRange(start: number, end: number): nodestd.stream.Readable; + } + + /** + * Represents a random access reader for a file by its file descriptor + */ + class RandomAccessFdReader extends AbstractRandomAccessReader { + constructor(fd: number); + } + + /** + * Represents a random access reader for a buffer + */ + class RandomAccessBufferReader extends AbstractRandomAccessReader { + constructor(buffer: Buffer); + } + + namespace I.Glob { + interface Options { + /** + * The current working directory in which to search. Defaults to process.cwd() + */ + cwd?: string; + + /** + * The place where patterns starting with / will be mounted onto + */ + root?: string; + + /** + * Include .dot files in normal matches and globstar matches + */ + dot?: boolean; + + /** + * By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, + * so that a valid filesystem path is returned + */ + nomount?: boolean; + + /** + * Add a / character to directory matches. Note that this requires additional stat calls + */ + mark?: boolean; + + /** + * Don't sort the results + */ + nosort?: boolean; + + /** + * Set to true to stat all results + */ + stat?: boolean; + + /** + * When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. + * Set the option to true to suppress these warnings. + */ + silent?: boolean; + + /** + * When an unusual error is encountered when attempting to read a directory, + * the process will just continue on in search of other matches. + * Set the option to raise an error in these cases + */ + strict?: boolean; + + /** + * Pass in a previously generated cache object to save some fs calls + */ + cache?: Map; + + /** + * A cache of results of filesystem information, to prevent unnecessary stat calls + */ + statCache?: Map; + + /** + * A cache of results of filesystem information, to prevent unnecessary realpath calls + */ + realpathCache?: Map; + + /** + * A cache of known symbolic links + */ + symlinks?: object; + + /** + * In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. + * By default, this implementation prevents duplicates in the result set. + * Set this flag to disable that behavior + */ + nounique?: boolean; + + /** + * Set to never return an empty set, instead returning a set containing the pattern itself. + * This is the default in glob(3). + */ + nonull?: boolean; + + /** + * Do not expand {a,b} and {1..3} brace sets. + */ + nobrace?: boolean; + + /** + * Do not match ** against multiple filenames. (Ie, treat it as a normal * instead.) + */ + noglobstar?: boolean; + + /** + * Do not match +(a|b) "extglob" patterns. + */ + noext?: boolean; + + /** + * Perform a case-insensitive match. + * Note: on case-insensitive filesystems, non-magic patterns will match by default, since stat and readdir will not raise errors. + */ + nocase?: boolean; + + /** + * Perform a basename-only match if the pattern does not contain any slash characters. + * That is, *.js would be treated as equivalent to **\/*.js, matching all js files in all directories + */ + matchBase?: boolean; + + /** + * Do not match directories, only files + */ + nodir?: boolean; + + /** + * Add a pattern or an array of glob patterns to exclude matches + */ + ignore?: string | string[]; + + /** + * Follow symlinked directories when expanding ** patterns. + * Note that this can result in a lot of duplicate references in the presence of cyclic links + */ + follow?: boolean; + + /** + * Set to true to call fs.realpath on all of the results + */ + realpath?: boolean; + + /** + * Set to true to always receive absolute paths for matched files + */ + absolute?: boolean; + } + + interface StreamOptions extends Options { + /** + * Add the index of the matching pattern to the result + */ + patternIndex?: boolean; + } + + interface StreamConstructor { + new(patterns: string | string[], options: StreamOptions & { stat: true, patternIndex: true }): Stream<{ + path: string, + stat: Stats, + patternIndex: number + }>; + new(patterns: string | string[], options: StreamOptions & { stat: true }): Stream<{ + path: string, + stat: Stats + }>; + new(patterns: string | string[], options: StreamOptions & { patternIndex: true }): Stream<{ + path: string, + patternIndex: number + }>; + new(patterns: string | string[], options?: StreamOptions): Stream; + + prototype: Stream; + } + + type Stream = stream.CoreStream; + + interface EmitterConstructor { + new(pattern: string, optons: Options, callback?: (error: any, matches: string[]) => void): Emitter; + new(pattern: string, callback?: (error: any, matches: string[]) => void): Emitter; + + prototype: Emitter; + } + + interface Emitter extends event.EventEmitter { + isIgnored(path: string): boolean; + + /** + * Stops the search permanently + */ + abort(): void; + + /** + * Temporarely stops the search + */ + pause(): void; + + /** + * Resumes the search + */ + resume(): void; + + on(event: "match", callback: (match: string, stat?: Stats) => void): this; + on(event: "end", callback: (matches: string[]) => void): this; + } + + interface GlobFunction { + (patterns: string | string[], options: StreamOptions & { stat: true, patternIndex: true }): Stream<{ + /** + * File path + */ + path: string, + + /** + * File stats + */ + stat: Stats, + + /** + * Pattern index + */ + patternIndex: number + }>; + (patterns: string | string[], options: StreamOptions & { stat: true }): Stream<{ + /** + * File path + */ + path: string, + + /** + * File stats + */ + stat: Stats + }>; + (patterns: string | string[], options: StreamOptions & { patternIndex: true }): Stream<{ + /** + * File path + */ + path: string, + + /** + * Pattern index + */ + patternIndex: number + }>; + (patterns: string | string[], options?: StreamOptions): Stream; + + /** + * low level glob emitter + */ + Glob: EmitterConstructor; + + /** + * Glob stream class + */ + Core: StreamConstructor; + } + } + + /** + * Creates a glob stream + */ + const glob: I.Glob.GlobFunction; + + namespace I.Watcher { + interface ConstructorOptions { + /** + * Indicates whether the process should continue to run as long as files are being watched + */ + persistent?: boolean; + /** + * If set to false then add/addDir events are also emitted for matching paths + * while instantiating the watching as watcher discovers these file paths + */ + ignoreInitial?: boolean; + /** + * Indicates whether to watch files that don't have read permissions if possible + */ + ignorePermissionErrors?: boolean; + /** + * Interval of file system polling (used when usePolling = true) + */ + interval?: number; + /** + * Interval of file system polling for binary files (used when usePolling = true) + */ + binaryInterval?: number; + /** + * If set to true then the strings passed to .watch() and .add() are treated as literal path names, + * even if they look like globs + */ + disableGlobbing?: boolean; + /** + * Whether to use the fsevents watching interface if available (true on mac by default) + */ + useFsEvents?: boolean; + /** + * Whether to use fs.watchFile (backed by polling), or fs.watch. + */ + usePolling?: boolean; + /** + * Automatically filters out artifacts that occur when using editors that use "atomic writes" + * instead of writing directly to the source file. If a file is re-added within 100 ms of being deleted, + * wather emits a change event rather than unlink then add + */ + atomic?: boolean | number; + /** + * When false, only the symlinks themselves will be watched for changes + * instead of following the link references and bubbling events through the link's path + */ + followSymlinks?: boolean; + /** + * If truthy, defines settings to control how long a file must not change after add/change events and only then emit the event + */ + awaitWriteFinish?: boolean | { + /** + * Amount of time in milliseconds for a file size to remain constant before emitting its event + */ + stabilityThreshold?: number, + /** + * File size polling interval + */ + pollInterval?: number + }; + /** + * Defines files/paths to be ignored + */ + ignored?: string[]; + /** + * Always passes fs.Stat file with `add`, `addDir` events + */ + alwaysStat?: boolean; + /** + * If set, limits how many levels of subdirectories will be traversed + */ + depth?: number; + /** + * The base directory from which watch paths are to be derived + */ + cwd?: string; + } + + type Event = "add" | "addDir" | "change" | "unlink" | "unlinkDir" | "ready" | "raw" | "error"; + } + + /** + * Represents a file watcher + */ + class Watcher extends event.EventEmitter { + constructor(options?: I.Watcher.ConstructorOptions); + + /** + * Adds files, directories, or glob patterns for tracking + */ + add(path: string | string[]): this; + + /** + * Stops watching files, directories, or glob patterns. + */ + unwatch(path: string | string[]): this; + + /** + * Removes all listeners from watched files + */ + close(): this; + + /** + * Returns an object representing all the paths on the file system being watched by this watcher + */ + getWatched(): { [path: string]: string[] }; + + on(event: "all", callback: (event: I.Watcher.Event, path: string, stat?: I.Stats) => void): this; + on(event: "raw", callback: (event: string, path: string, details: object) => void): this; + on(event: I.Watcher.Event, callback: (path: string, stat?: I.Stats) => void): this; + } + + /** + * Creates a Watcher instance with the given options and starts watching the given paths + */ + function watch(paths: string | string[], options?: I.Watcher.ConstructorOptions): Watcher; + + namespace is { + /** + * Returns true if the given path refers to a file + */ + function file(path: string): Promise; + + /** + * Returns true if the given path refers to a file + */ + function fileSync(path: string): boolean; + + /** + * Returns true if the given path refers to a direcotry + */ + function directory(path: string): Promise; + + /** + * Returns true if the given path refers to a direcotry + */ + function directorySync(path: string): boolean; + + /** + * Returns true if the given path refers to an executable file + */ + function executable(path: string): Promise; + + /** + * Returns true if the given path refers to an executable file + */ + function executableSync(path: string): boolean; + } + + namespace I.Which { + interface Options { + colon?: string; + path?: string; + pathExt?: string; + nothrow?: boolean; + all?: boolean; + } + + interface OptionsAll extends Options { + all: true; + } + + interface OptionsNothrow extends Options { + nothrow: true; + } + + interface OptionsAllNothrow extends Options { + all: true; + nothrow: true; + } + } + + /** + * Finds instances of a specified executable in the PATH environment variable + */ + function which(cmd: string, options: I.Which.OptionsAllNothrow): Promise; + + /** + * Finds instances of a specified executable in the PATH environment variable + */ + function which(cmd: string, options: I.Which.OptionsAll): Promise; + + /** + * Finds the first instance of a specified executable in the PATH environment variable + */ + function which(cmd: string, options: I.Which.OptionsNothrow): Promise; + + /** + * Finds instances of a specified executable in the PATH environment variable + */ + function which(cmd: string, options?: I.Which.Options): Promise; + + /** + * Finds instances of a specified executable in the PATH environment variable + */ + function whichSync(cmd: string, options: I.Which.OptionsAllNothrow): string[] | null; + + /** + * Finds instances of a specified executable in the PATH environment variable + */ + function whichSync(cmd: string, options: I.Which.OptionsAll): string[]; + + /** + * Finds the first instance of a specified executable in the PATH environment variable + */ + function whichSync(cmd: string, options: I.Which.OptionsNothrow): string | null; + + /** + * Finds instances of a specified executable in the PATH environment variable + */ + function whichSync(cmd: string, options?: I.Which.Options): string; + + /** + * Functions to work with files using file descriptors + */ + namespace fd { + /** + * Opens and possibly create a file + */ + function open(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): Promise; + + /** + * Opens and possibly create a file + */ + function openSync(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): I.FD; + + /** + * Closes a file descriptor + */ + function close(fd: I.FD): Promise; + + /** + * Closes a file descriptor + */ + function closeSync(fd: I.FD): void; + + /** + * Changes the file timestamps of a file referenced by the supplied file descriptor + */ + function utimes(fd: I.FD, atime: number, mtime: number): Promise; + + /** + * Changes the file timestamps of a file referenced by the supplied file descriptor + */ + function utimesSync(fd: I.FD, atime: number, mtime: number): void; + + /** + * Gets file status + */ + function stat(fd: I.FD): Promise; + + /** + * Gets file status + */ + function statSync(fd: I.FD): I.Stats; + + /** + * Truncates a file to a specified length + */ + function truncate(fd: I.FD, length?: number): Promise; + + /** + * Truncates a file to a specified length + */ + function truncateSync(fd: I.FD, length?: number): void; + + /** + * Read data from the file specified by fd + */ + function read( + fd: I.FD, + /** + * The buffer that the data will be written to + */ + buffer: Buffer | Uint8Array, + /** + * The offset in the buffer to start writing at + */ + offset: number, + /** + * An integer specifying the number of bytes to read + */ + length: number, + /** + * An argument specifying where to begin reading from in the file + */ + position: number + ): Promise; + + function readSync( + fd: I.FD, + /** + * The buffer that the data will be written to + */ + buffer: Buffer | Uint8Array, + /** + * The offset in the buffer to start writing at + */ + offset: number, + /** + * An integer specifying the number of bytes to read + */ + length: number, + /** + * An argument specifying where to begin reading from in the file + */ + position: number + ): number; + + /** + * Writes buffer to the file specified by fd + */ + function write( + fd: I.FD, + buffer: Buffer | Uint8Array, + /** + * Determines the part of the buffer to be written + */ + offset?: number, + /** + * An integer specifying the number of bytes to write + */ + length?: number, + /** + * The offset from the beginning of the file where this data should be written + */ + position?: number + ): Promise; + + /** + * Writes string to the file specified by fd + */ + function write( + fd: I.FD, + string: string, + /** + * The offset from the beginning of the file where this data should be written + */ + position?: number, + /** + * The expected string encoding + */ + encoding?: I.Encoding + ): Promise; + + /** + * Writes buffer to the file specified by fd + */ + function writeSync( + fd: I.FD, + buffer: Buffer | Uint8Array, + /** + * Determines the part of the buffer to be written + */ + offset?: number, + /** + * An integer specifying the number of bytes to write + */ + length?: number, + /** + * The offset from the beginning of the file where this data should be written + */ + position?: number + ): number; + + /** + * Writes string to the file specified by fd + */ + function writeSync( + fd: I.FD, + string: string, + /** + * The offset from the beginning of the file where this data should be written + */ + position?: number, + /** + * The expected string encoding + */ + encoding?: I.Encoding + ): number; + + /** + * Synchronizes a file's in-core state with storage + */ + function sync(fd: I.FD): Promise; + + /** + * Synchronizes a file's in-core state with storage + */ + function syncSync(fd: I.FD): void; + + /** + * Changes ownership of a file + */ + function chown(fd: I.FD, uid: number, gid: number): Promise; + + /** + * Changes ownership of a file + */ + function chownSync(fd: I.FD, uid: number, gid: number): void; + + /** + * Changes permissions of a file + */ + function chmod(fd: I.FD, mode: number): Promise; + + /** + * Changes permissions of a file + */ + function chmodSync(fd: I.FD, mode: number): void; + + /** + * Repositions read/write file offset + */ + function seek(fd: I.FD, offset: number, whence: number): Promise; + + /** + * Applies or removes an advisory lock on an open file + */ + function lock(fd: I.FD, flags: "sh" | "ex" | "shnb" | "exnb" | "un" | number): Promise; + } + + namespace constants { + const F_OK: number; + const LOCK_EX: number; + const LOCK_NB: number; + const LOCK_SH: number; + const LOCK_UN: number; + const O_APPEND: number; + const O_CREAT: number; + const O_DIRECT: number; + const O_DIRECTORY: number; + const O_EXCL: number; + const O_NOATIME: number; + const O_NOCTTY: number; + const O_NOFOLLOW: number; + const O_NONBLOCK: number; + const O_RDONLY: number; + const O_RDWR: number; + const O_SYNC: number; + const O_TRUNC: number; + const O_WRONLY: number; + const R_OK: number; + const SEEK_CUR: number; + const SEEK_END: number; + const SEEK_SET: number; + const S_IFBLK: number; + const S_IFCHR: number; + const S_IFDIR: number; + const S_IFIFO: number; + const S_IFLNK: number; + const S_IFMT: number; + const S_IFREG: number; + const S_IFSOCK: number; + const S_IRGRP: number; + const S_IROTH: number; + const S_IRUSR: number; + const S_IRWXG: number; + const S_IRWXO: number; + const S_IRWXU: number; + const S_IWGRP: number; + const S_IWOTH: number; + const S_IWUSR: number; + const S_IXGRP: number; + const S_IXOTH: number; + const S_IXUSR: number; + const W_OK: number; + const X_OK: number; + } + + /** + * Returns the canonicalized absolute pathname + */ + function realpath(path: string | Buffer | I.URL, encoding: "buffer"): Promise; + function realpath(path: string | Buffer | I.URL, encoding: I.Encoding): Promise; + function realpath(path: string | Buffer | I.URL, options: { encoding: "buffer" }): Promise; + function realpath(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): Promise; + + /** + * Returns the canonicalized absolute pathname + */ + function realpathSync(path: string | Buffer | I.URL, encoding: "buffer"): Buffer; + function realpathSync(path: string | Buffer | I.URL, encoding: I.Encoding): string; + function realpathSync(path: string | Buffer | I.URL, options: { encoding: "buffer" }): Buffer; + function realpathSync(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): string; + + namespace I { + interface ReadFileOptions { + check?: boolean; + flags?: Flag; + encoding?: null | Encoding; + } + } + + /** + * Reads a file + */ + function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true, encoding: null }): Promise; + function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true, encoding: I.Encoding }): Promise; + function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true }): Promise; + function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { encoding: null }): Promise; + function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { encoding: I.Encoding }): Promise; + function readFile(filepath: string | Buffer | I.URL, options: I.ReadFileOptions): Promise; + function readFile(filepath: string | Buffer | I.URL, encoding: null): Promise; + function readFile(filepath: string | Buffer | I.URL, encoding: I.Encoding): Promise; + function readFile(filepath: string | Buffer | I.URL): Promise; + + /** + * Reads a file + */ + function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true, encoding: null }): Buffer | null; + function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true, encoding: I.Encoding }): string | null; + function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { check: true }): Buffer | null; + function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { encoding: null }): Buffer; + function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions & { encoding: I.Encoding }): string; + function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions): Buffer; + function readFileSync(filepath: string | Buffer | I.URL, options: I.ReadFileOptions): Buffer; + function readFileSync(filepath: string | Buffer | I.URL, encoding: null): Buffer; + function readFileSync(filepath: string | Buffer | I.URL, encoding: I.Encoding): string; + function readFileSync(filepath: string | Buffer | I.URL): Buffer; + + /** + * Reads lines from a file + */ + function readLines(filepath: string | Buffer | I.URL, options: { check: true, flags?: I.Flag, encoding?: null | I.Encoding }): Promise; + function readLines(filepath: string | Buffer | I.URL, options: { check?: false, flags?: I.Flag, encoding?: null | I.Encoding }): Promise; + function readLines(filepath: string | Buffer | I.URL, encoding?: null | I.Encoding): Promise; + + /** + * Reads lines from a file + */ + function readLinesSync(filepath: string | Buffer | I.URL, options: { check: true, flags?: I.Flag, encoding?: null | I.Encoding }): string[] | null; + function readLinesSync(filepath: string | Buffer | I.URL, options: { check?: false, flags?: I.Flag, encoding?: null | I.Encoding }): string[]; + function readLinesSync(filepath: string | Buffer | I.URL, encoding?: null | I.Encoding): string[]; + + /** + * Reads words from a file + */ + function readWords(filepath: string | Buffer | I.URL, options: { check: true, flags?: I.Flag, encoding?: null | I.Encoding }): Promise; + function readWords(filepath: string | Buffer | I.URL, options: { check?: false, flags?: I.Flag, encoding?: null | I.Encoding }): Promise; + function readWords(filepath: string | Buffer | I.URL, encoding?: null | I.Encoding): Promise; + + /** + * Reads words from a file + */ + function readWordsSync(filepath: string | Buffer | I.URL, options: { check: true, flags?: I.Flag, encoding?: null | I.Encoding }): string[] | null; + function readWordsSync(filepath: string | Buffer | I.URL, options: { check?: false, flags?: I.Flag, encoding?: null | I.Encoding }): string[]; + function readWordsSync(filepath: string | Buffer | I.URL, encoding?: null | I.Encoding): string[]; + + /** + * Checks whether a file exists + */ + function exists(path: string | Buffer | I.URL): Promise; + + /** + * Checks whether a file exists + */ + function existsSync(path: string | Buffer | I.URL): boolean; + + /** + * Creates a new directory and any necessary subdirectories + */ + function mkdir(path: string, mode?: number): Promise; + + namespace I { + interface CopyOptions { + /** + * Do not replace existing files + */ + ignoreExisting?: boolean; + + /** + * Base direcotry for paths + */ + cwd?: string; + } + } + + /** + * Copies all files from src to dst + */ + function copy(src: string, dst: string, options?: I.CopyOptions): Promise; + + /** + * Renames a file + */ + function rename(oldPath: string, newPath: string, options?: { + /** + * Will retry if fails with EPERM or EACCESS errors + */ + retries?: number, + /** + * Will retry after this delay + */ + delay?: number + }): Promise; + + /** + * Returns the last lines of a file + */ + function tail(path: string, n: number, options?: { separator?: string, chunkLength?: number }): Promise; + + namespace I { + interface StatVFS { + /** + * Maximum filename length + */ + f_namemax: number; + + /** + * File system block size + */ + f_bsize: number; + + /** + * Fragment size + */ + f_frsize: number; + + /** + * Size of fs in f_frsize units + */ + f_blocks: number; + + /** + * # free blocks for unprivileged users + */ + f_bavail: number; + + /** + * # free blocks + */ + f_bfree: number; + + /** + * # inodes + */ + f_files: number; + + /** + * # free inodes for unprivileged users + */ + f_favail: number; + + /** + * # free inodes + */ + f_ffree: number; + } + } + + /** + * Returns information about a mounted file system + */ + function statVFS(path: string): Promise; + + namespace I { + interface ReadStreamOptions { + flags?: Flag; + encoding?: Encoding | null; + /** + * File mode + */ + mode?: number; + /** + * Inclusive start of the reading range + */ + start?: number; + /** + * Inclusive end of the reading range + */ + end?: number; + } + + interface ReadStreamOptionsFD extends ReadStreamOptions { + /** + * Use the specified file descriptor for reading instead of `path` + */ + fd: number; + /** + * Whether to close the file descriptor + */ + autoClose?: boolean; + } + } + + /** + * Returns a read stream for the given file + */ + function createReadStream(path: null | undefined, options: I.ReadStreamOptionsFD): I.ReadStream; + function createReadStream(path: string | Buffer | I.URL, options?: I.ReadStreamOptions): I.ReadStream; + function createReadStream(path: string | Buffer | I.URL, encoding: I.Encoding | null): I.ReadStream; + + namespace I { + interface WriteStreamOptions { + flags?: Flag; + defaultEncoding?: Encoding | null; + /** + * File mode + */ + mode?: number; + /** + * Start position to write data at some position past the beginning of the file + */ + start?: number; + } + + interface WriteStreamOptionsFD extends WriteStreamOptions { + /** + * Use the specified file descriptor for writing instead of `path` + */ + fd: number; + /** + * Whether to close the file descriptor + */ + autoClose?: boolean; + } + } + + /** + * Returns a write stream to the given file + */ + function createWriteStream(path: null | undefined, options: I.WriteStreamOptionsFD): I.WriteStream; + function createWriteStream(path: string | Buffer | I.URL, options?: I.WriteStreamOptions): I.WriteStream; + function createWriteStream(path: string | Buffer | I.URL, encoding: I.Encoding | null): I.WriteStream; + + namespace I { + interface TmpNameOptions { + name?: string; + tries?: number; + template?: RegExp; + dir?: string; + prefix?: string; + ext?: string; + } + } + + /** + * Generates a temporary filepath + */ + function tmpName(options?: I.TmpNameOptions): Promise; + + /** + * Returns the current user homedir + */ + function homeDir(): string; + + /** + * TODO + */ + function lookup(path: string): Promise; + + /** + * Recursively changes ownership of files + */ + function chownr(path: string, uid: number, gid: number): Promise; + + namespace I.TailWatcher { + interface ConstructorOptions { + /** + * Uses this separator to split lines + */ + separator?: string | RegExp; + /** + * Options for fs.watch + */ + fsWatchOptions?: object; + /** + * Start from the beginning of the file + */ + fromBeginning?: boolean; + /** + * Follow the file when it renames + */ + follow?: boolean; + /** + * use fs.watchFile + */ + useWatchFile?: boolean; + /** + * Use the given encoding for reading + */ + encoding?: Encoding | null; + /** + * Start watching from the given position + */ + pos?: number; + } + } + + /** + * Represents an event emitter that watches for a file growing, + * emits "line" event for each new line in a file + */ + class TailWatcher extends event.EventEmitter { + constructor(filename: string, options?: I.TailWatcher.ConstructorOptions); + + /** + * Stop watching + */ + unwatch(): void; + + on(event: "line", callback: (line: string) => void): this; + } + + /** + * Creates a new TailWatcher instance with the given arguments + */ + function watchTail(filename: string, options?: I.TailWatcher.ConstructorOptions): TailWatcher; + } +} diff --git a/types/adone/glosses/is.d.ts b/types/adone/glosses/is.d.ts new file mode 100644 index 0000000000..335439a0bf --- /dev/null +++ b/types/adone/glosses/is.d.ts @@ -0,0 +1,553 @@ +declare namespace adone { + /** + * predicates + */ + namespace is { + /** + * Checks whether the given object is `null` + */ + function _null(obj: any): boolean; + export { _null as null }; + + /** + * Checks whether the given object is `undefined` + */ + export function undefined(obj: any): boolean; + + /** + * Checks whether the given object is nither `undefined` nor `null` + */ + export function exist(obj: any): boolean; + + /** + * Checks whether the given object is either `undefined` or `null` + */ + export function nil(obj: any): boolean; + + /** + * Checks whether the given object is a number + */ + export function number(obj: any): boolean; + + /** + * Checks whether the given object is a finite number or a string represents a finite number + */ + export function numeral(obj: any): boolean; + + /** + * Checks whether the given object is either +Infinity or -Inginity + */ + export function infinite(obj: any): boolean; + + /** + * Checks whether the given object is an odd number + */ + export function odd(obj: any): boolean; + + /** + * Checks whether the given object is an even number + */ + export function even(obj: any): boolean; + + /** + * Checks whether the given object is a float + */ + export function float(obj: any): boolean; + + /** + * Checks whether the given object is -0 + */ + export function negativeZero(obj: any): boolean; + + /** + * Checks whether the given object is a string + */ + export function string(obj: any): boolean; + + /** + * Checks whether the given object is an empty string + */ + export function emptyString(obj: any): boolean; + + /** + * Checks whether the first string is a substring of the second string from the given offset + */ + export function substring(substring: string, string: string, offset?: number): boolean; + + /** + * Checks whether `string` starts from `prefix` + */ + export function prefix(prefix: string, string: string): boolean; + + /** + * Checks whether `strin` ends with `prefix` + */ + export function suffix(suffix: string, string: string): boolean; + + /** + * Checks whether the given object is a boolean + */ + export function boolean(obj: any): boolean; + + /** + * Checks whether the given object is a string with ".json" extension or an object + */ + export function json(obj: any): boolean; + + /** + * Checks whether the given object is not a primitive, i.e. neither `undefined` nor `null` nor number nor string nor boolean nor symbol) + */ + export function object(obj: any): boolean; + + /** + * Checks whether the given object is a plain object, i.e. created by Object + */ + export function plainObject(obj: any): boolean; + + /** + * Checks whether the given object is an adone namespace + */ + export function namespace(obj: any): boolean; + + /** + * Checks whether the given object is a class + */ + function _class(obj: any): boolean; + export { _class as class }; + + /** + * Checks whether the given object is empty, i.e. it is an object(not a primitive), and Object.keys returns an empty array + */ + export function emptyObject(obj: any): boolean; + + /** + * Checks whether the given object has the given owned property + */ + export function propertyOwned(obj: any, field: string): boolean; + + /** + * Checks whether the given object has the given property + */ + export function propertyDefined(obj: any, field: string): boolean; + + /** + * Checks whether the given object conforms to `schema`. + */ + export function conforms(obj: object, schema: object, strict?: boolean): boolean; + + /** + * Checks whether the given object is like an array, i.e. it is not a primitive, not a function and has length + */ + export function arrayLikeObject(obj: any): boolean; + + /** + * Checks whether the given array has the given value + */ + export function inArray(value: T, array: any[], offset?: number, comparator?: (a: T, b: T) => boolean): boolean; + + /** + * Checks whether the given objects has same type + */ + export function sameType(value: any, other: any): boolean; + + /** + * Checks whether the given object is a primitive, i.e. it is either `undefined` or `null` or number or boolean or string or symbol + */ + export function primitive(obj: any): boolean; + + /** + * Checks whether the given arrays are equal + */ + export function equalArrays(left: any[], right: any[]): boolean; + + /** + * Checks whether the given objects are deep equal + */ + export function deepEqual(left: any, right: any): boolean; + + export function shallowEqual(left: any, right: any): boolean; + + /** + * Checks whether the given object is a stream, i.e. an object and has a pipe method + */ + export function stream(obj: any): boolean; + + /** + * Checks whether the given object is a writable stream, i.e. a stream that has _writableState + */ + export function writableStream(obj: any): boolean; + + /** + * Checks whether the given object is a readable stream, i.e. a stream that has _readableState + */ + export function readableStream(obj: any): boolean; + + /** + * Checks whether the given object is a duplex stream, i.e. a readable and writable stream + */ + export function duplexStream(obj: any): boolean; + + /** + * Checks whether the given object is a transform stream, i.e. a stream that has _transformState + */ + export function transformStream(obj: any): boolean; + + /** + * Checks whether the given buffer is in utf8 + */ + export function utf8(obj: Buffer): boolean; + + /** + * Checks whether the given path is an absolute win32 path + */ + export function win32PathAbsolute(path: string): boolean; + + /** + * Checks whether the given path is an absolute posix path + */ + export function posixPathAbsolute(path: string): boolean; + + /** + * Checks whether the given path is an absolute path + */ + export function pathAbsolute(path: string): boolean; + + /** + * Checks whether the given string is a glob + */ + export function glob(str: string): boolean; + + /** + * Checks whether the given path is not a dot-file path (.secret) + */ + export function dotfile(str: string): boolean; + + /** + * Checks whether the given object is a function + */ + function _function(obj: any): boolean; + export { _function as function }; + + /** + * Checks whether the given object is an async function + */ + export function asyncFunction(obj: any): boolean; + + /** + * Checks whether the given object is a promise + */ + export function promise(obj: any): boolean; + + /** + * Checks whether the given string is a valid date-string + */ + export function validDate(str: string): boolean; + + /** + * Checks whether the given object is a buffer + */ + export function buffer(obj: any): boolean; + + /** + * Checks whether the given object is a callback function, i.e. it has a common function name + */ + export function callback(obj: any): boolean; + + /** + * Checks whether the given object is a generator function + */ + export function generator(obj: any): boolean; + + /** + * Checks whether the given object is NaN + */ + export function nan(obj: any): boolean; + + /** + * Checks whether the given object is a finite number + */ + export function finite(obj: any): boolean; + + /** + * Checks whether the given object is an integer + */ + export function integer(obj: any): boolean; + + /** + * Checks whether the given object is a safe integer + */ + export function safeInteger(obj: any): boolean; + + /** + * Checks whether the given object is an array + */ + export function array(obj: any): boolean; + + /** + * Checks whether the given object is a Uint8 array + */ + export function uint8Array(obj: any): boolean; + + /** + * Checks whether the given object is an adone configuration + */ + export function configuration(obj: any): boolean; + + /** + * Checks whether the given object is an instance of adone.math.Long + */ + export function long(obj: any): boolean; + + /** + * Checks whether the given object is an instance of adone.math.BigNumber + */ + export function bigNumber(obj: any): boolean; + + /** + * Checks whether the given object is an instance of adone.collection.ByteArray + */ + export function byteArray(obj: any): boolean; + + /** + * Checks whether the given object is an instance of adone.datetime + */ + export function datetime(obj: any): boolean; + + export function transform(obj: any): boolean; + + /** + * Checks whether the given object is an adone subsystem + */ + export function subsystem(obj: any): boolean; + + /** + * Checks whether the given object is an adone application + */ + export function application(obj: any): boolean; + + /** + * Checks whether the given object is an adone logger + */ + export function logger(obj: any): boolean; + + /** + * Checks whether the given object is a core stream + */ + export function coreStream(obj: any): boolean; + + /** + * Checks whether the given object is a fast local map stream + */ + export function fastLocalMapStream(obj: any): boolean; + + /** + * Checks whether the given object is a fast local stream + */ + export function fastLocalStream(obj: any): boolean; + + /** + * Checks whether the given object is a fast stream + */ + export function fastStream(obj: any): boolean; + + /** + * Checks whether the given object is a genesis netron + */ + export function genesisNetron(obj: any): boolean; + + /** + * Checks whether the given object is a genesis peer + */ + export function genesisPeer(obj: any): boolean; + + /** + * Checks whether the given object is a netron adapter + */ + export function netronAdapter(obj: any): boolean; + + /** + * Checks whether the given object is a netron instance + */ + export function netron(obj: any): boolean; + + /** + * Checks whether the given object is a netron peer instance + */ + export function netronPeer(obj: any): boolean; + + /** + * Checks whether the given object is a netron definition + */ + export function netronDefinition(obj: any): boolean; + + /** + * Checks whether the given object represents netron definitions + */ + export function netronDefinitions(obj: any): boolean; + + /** + * Checks whether the given object is a netron reference + */ + export function netronReference(obj: any): boolean; + + /** + * Checks whether the given object is a netron interface + */ + export function netronInterface(obj: any): boolean; + + /** + * Checks whether the given object is a netron context + */ + export function netronContext(obj: any): boolean; + + /** + * Checks whether the given netron interface has `name` method + */ + export function netronIMethod(netronInterface: object, name: string): boolean; + + /** + * Checks whether the given netron interface has `name` property + */ + export function netronIProperty(netronInterface: any, name: string): boolean; + + /** + * Checks whether the given object is a netron stub + */ + export function netronStub(obj: any): boolean; + + /** + * Checks whether the given object is a netron remote stub + */ + export function netronRemoteStub(obj: any): boolean; + + /** + * Checks whether the given object is a netron stream + */ + export function netronStream(obj: any): boolean; + + /** + * Checks whether the given object is iterable, has defined Symbol.iterator property + */ + export function iterable(obj: any): boolean; + + /** + * true if the OS is Windows + */ + export const windows: boolean; + + /** + * true if the OS is Linux + */ + export const linux: boolean; + + /** + * true is the OS is FreeBSD + */ + export const freebsd: boolean; + + /** + * true is the os is macOS + */ + export const darwin: boolean; + + /** + * true is the os is SunOS + */ + export const sunos: boolean; + + /** + * Checks whether the given string is uppercased + */ + export function uppercase(str: string): boolean; + + /** + * Checks whether the given string is lowercased + */ + export function lowercase(str: string): boolean; + + /** + * Checks whether the given string includes only digits + */ + export function digits(str: string): boolean; + + /** + * Checks whether the given string is a valid js identifier + */ + export function identifier(str: string): boolean; + + /** + * Checks whether the given string is a binary extension (7z, zip, mp3, etc) + */ + export function binaryExtension(str: string): boolean; + + /** + * Checks whether the given string is a path to a binary file + */ + export function binaryPath(str: string): boolean; + + /** + * Checks whether the given string is an IPv4 address + */ + export function ip4(str: string): boolean; + + /** + * Checks whether the given string is an IPv6 address + */ + export function ip6(str: string): boolean; + + /** + * Checks whether the given object is an array buffer + */ + export function arrayBuffer(obj: any): boolean; + + /** + * Checks whether the given object is an array buffer view + */ + export function arrayBufferView(obj: any): boolean; + + /** + * Checks whether the given object is a date + */ + export function date(obj: any): boolean; + + /** + * Checks whether the given object is an error, instance of Error + */ + export function error(obj: any): boolean; + + /** + * Checks whether the given object is a map + */ + export function map(obj: any): boolean; + + /** + * Checks whether the given object is a regexp + */ + export function regexp(obj: any): boolean; + + /** + * Checks whether the given object is a set + */ + export function set(obj: any): boolean; + + /** + * Checks whether the given object is a symbol + */ + export function symbol(obj: any): boolean; + + /** + * Checks whether the given buffer a valid UTF-8 encoded text + */ + export function validUTF8(obj: Buffer): boolean; + + /** + * Checks whether the given object is a vault valuable + */ + export function vaultValuable(obj: any): boolean; + + /** + * Checks whether the given object is an adone task + */ + export function task(obj: any): boolean; + } +} diff --git a/types/adone/glosses/math.d.ts b/types/adone/glosses/math.d.ts deleted file mode 100644 index 076bdd105f..0000000000 --- a/types/adone/glosses/math.d.ts +++ /dev/null @@ -1,118 +0,0 @@ -/** - * math related things - */ -export namespace math { - namespace I { - interface LowHighBits { - low: number; - high: number; - } - type Longable = math.Long | number | string | LowHighBits; - } - - export class Long { - constructor(low?: number, high?: number, unsigned?: boolean); - - toInt(): number; - - toNumber(): number; - - toString(radix?: number): string; - - getHighBits(): number; - - getHighBitsUnsigned(): number; - - getLowBits(): number; - - getLowBitsUnsigned(): number; - - getNumBitsAbs(): number; - - isZero(): boolean; - - isNegative(): boolean; - - isPositive(): boolean; - - isOdd(): boolean; - - isEven(): boolean; - - equals(other: I.Longable): boolean; - - lessThan(other: I.Longable): boolean; - - lessThanOrEqual(other: I.Longable): boolean; - - greaterThan(other: I.Longable): boolean; - - greaterThanOrEqual(other: I.Longable): boolean; - - compare(other: I.Longable): number; - - negate(): Long; - - add(addend: I.Longable): Long; - - sub(subtrahend: I.Longable): Long; - - mul(multiplier: I.Longable): Long; - - div(divisor: I.Longable): Long; - - mod(divisor: I.Longable): Long; - - not(): Long; - - and(other: I.Longable): Long; - - or(other: I.Longable): Long; - - xor(other: I.Longable): Long; - - shl(numBits: number | Long): Long; - - shr(numBits: number | Long): Long; - - shru(numBits: number | Long): Long; - - toSigned(): Long; - - toUnsigned(): Long; - - toBytes(le?: boolean): number[]; - - toBytesLE(): number[]; - - toBytesBE(): number[]; - - static fromInt(value: number, unsigned?: boolean): Long; - - static fromNumber(value?: number, unsigned?: boolean): Long; - - static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; - - static fromString(str: string, unsigned?: boolean, radix?: number): Long; - - static fromString(str: string, radix?: number): Long; - - static fromValue(val: I.Longable): Long; - - static MIN_VALUE: Long; - - static MAX_VALUE: Long; - - static MAX_UNSIGNED_VALUE: Long; - - static ZERO: Long; - - static UZERO: Long; - - static ONE: Long; - - static UONE: Long; - - static NEG_ONE: Long; - } -} diff --git a/types/adone/glosses/math/index.d.ts b/types/adone/glosses/math/index.d.ts new file mode 100644 index 0000000000..2713196e6e --- /dev/null +++ b/types/adone/glosses/math/index.d.ts @@ -0,0 +1,759 @@ +/// +/// + +declare namespace adone { + /** + * math related things + */ + namespace math { + namespace I { + interface LowHighBits { + /** + * The low (signed) 32 bits of the long + */ + low: number; + /** + * The high (signed) 32 bits of the long + */ + high: number; + } + type Longable = Long | number | string | LowHighBits; + } + + /** + * Represents a 64 bit two's-complement integer + */ + class Long { + low: number; + high: number; + unsigned: boolean; + + /** + * @param low The low (signed) 32 bits of the long + * @param high The high (signed) 32 bits of the long + * @param unsigned Whether unsigned or not, defaults to false for signed + */ + constructor(low?: number, high?: number, unsigned?: boolean); + + /** + * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer + */ + toInt(): number; + + /** + * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa) + */ + toNumber(): number; + + /** + * Converts the Long to a string written in the specified radix + * + * @param radix Radix (2-36), 10 by default + */ + toString(radix?: number): string; + + inspect(): string; + + /** + * Gets the high 32 bits as a signed integer + */ + getHighBits(): number; + + /** + * Gets the high 32 bits as an unsigned integer + */ + getHighBitsUnsigned(): number; + + /** + * Gets the low 32 bits as a signed integer + */ + getLowBits(): number; + + /** + * Gets the low 32 bits as an unsigned integer + */ + getLowBitsUnsigned(): number; + + /** + * Gets the number of bits needed to represent the absolute value of this Long + */ + getNumBitsAbs(): number; + + /** + * Tests if this Long's value equals zero + */ + isZero(): boolean; + + /** + * Tests if this Long's value is negative + */ + isNegative(): boolean; + + /** + * Tests if this Long's value is positive + */ + isPositive(): boolean; + + /** + * Tests if this Long's value is odd + */ + isOdd(): boolean; + + /** + * Tests if this Long's value is even + */ + isEven(): boolean; + + /** + * Tests if this Long's value equals the specified's + */ + equals(other: I.Longable): boolean; + + /** + * Tests if this Long's value is less than the specified's + */ + lessThan(other: I.Longable): boolean; + + /** + * Tests if this Long's value is less than or equal the specified's + */ + lessThanOrEqual(other: I.Longable): boolean; + + /** + * Tests if this Long's value is greater than the specified's + */ + greaterThan(other: I.Longable): boolean; + + /** + * Tests if this Long's value is greater than or equal the specified's + */ + greaterThanOrEqual(other: I.Longable): boolean; + + /** + * Compares this Long's value with the specified's. + * Returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater + */ + compare(other: I.Longable): number; + + /** + * Negates this Long's value + */ + negate(): Long; + + /** + * Returns the sum of this and the specified Long + */ + add(addend: I.Longable): Long; + + /** + * Returns the difference of this and the specified Long + */ + sub(subtrahend: I.Longable): Long; + + /** + * Returns the product of this and the specified Long + */ + mul(multiplier: I.Longable): Long; + + /** + * Returns this Long divided by the specified + */ + div(divisor: I.Longable): Long; + + /** + * Returns this Long modulo the specified + */ + mod(divisor: I.Longable): Long; + + /** + * Returns the bitwise NOT of this Long + */ + not(): Long; + + /** + * Returns the bitwise AND of this Long and the specified + */ + and(other: I.Longable): Long; + + /** + * Returns the bitwise OR of this Long and the specifieds + */ + or(other: I.Longable): Long; + + /** + * Returns the bitwise XOR of this Long and the given one + */ + xor(other: I.Longable): Long; + + /** + * Returns this Long with bits shifted to the left by the given amount + */ + shl(numBits: number | Long): Long; + + /** + * Returns this Long with bits arithmetically shifted to the right by the given amount + */ + shr(numBits: number | Long): Long; + + /** + * Returns this Long with bits logically shifted to the right by the given amount + */ + shru(numBits: number | Long): Long; + + /** + * Converts this Long to signed + */ + toSigned(): Long; + + /** + * Converts this Long to unsigned + */ + toUnsigned(): Long; + + /** + * Converts this Long to an array of bytes, big-endian by default + * + * @param le Whether to return an array in little-endian format + */ + toBytes(le?: boolean): number[]; + + /** + * Converts this Long to an array of bytes in little-endian format + */ + toBytesLE(): number[]; + + /** + * Converts this Long to an array of bytes in big-endian format + */ + toBytesBE(): number[]; + + /** + * Returns a Long representing the given 32 bit integer value + */ + static fromInt(value: number, unsigned?: boolean): Long; + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned + */ + static fromNumber(value?: number, unsigned?: boolean): Long; + + /** + * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits + */ + static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; + + /** + * Returns a Long representation of the given string, written using the specified radix + */ + static fromString(str: string, unsigned?: boolean, radix?: number): Long; + + /** + * Returns a Long representation of the given string, written using the specified radix + */ + static fromString(str: string, radix?: number): Long; + + /** + * Converts the specified value to a Long + */ + static fromValue(val: I.Longable): Long; + + /** + * Minimum signed value + */ + static MIN_VALUE: Long; + + /** + * Maximum signed value + */ + static MAX_VALUE: Long; + + /** + * Maximum unsigned value + */ + static MAX_UNSIGNED_VALUE: Long; + + /** + * Signed zero + */ + static ZERO: Long; + + /** + * Unsigned zero + */ + static UZERO: Long; + + /** + * Signed one + */ + static ONE: Long; + + /** + * Unsigned one + */ + static UONE: Long; + + /** + * Signed negative one + */ + static NEG_ONE: Long; + } + + namespace I.BigNumber { + interface BufferConvertOptions { + endian?: 1 | -1 | "big" | "little"; + size?: "auto" | number; + } + } + + /** + * Represents a number of arbitrary precision + */ + class BigNumber { + /** + * Creates a BigNumber from the given value, the base is 10 + */ + constructor(n: number | string | BigNumber); + + /** + * Creates a BigNumber from the given string and base + */ + constructor(n: string, base: number); + + /** + * Converts the number to a string in the given base + */ + toString(base?: number): string; + + /** + * Converts the bignum into a Number. + * If the bignum is too big you'll lose precision or you'll get ±Infinity. + */ + toNumber(): number; + + /** + * Returns a new Buffer with the data from the bignum. + */ + toBuffer(opts?: I.BigNumber.BufferConvertOptions): Buffer; + + /** + * Returns a new bignum containing the instance value plus n + */ + add(n: number | string | BigNumber): BigNumber; + + /** + * Return a new bignum containing the instance value minus n + */ + sub(n: number | string | BigNumber): BigNumber; + + /** + * Returns a new bignum containing the instance value multiplied by n + */ + mul(n: number | string | BigNumber): BigNumber; + + /** + * Returns a new bignum containing the instance value integrally divided by n + */ + div(n: number | string | BigNumber): BigNumber; + + /** + * Returns a new bignum with the absolute value of the instance + */ + abs(): BigNumber; + + /** + * Returns a new bignum with the negative of the instance value + */ + neg(): BigNumber; + + /** + * Compares the instance value to n. + * + * Returns a positive integer if > n, a negative integer if < n, and 0 if == n + */ + cmp(n: number | string | BigNumber): number; + + /** + * Checks whether the instance value is greater than n (> n). + */ + gt(n: number | string | BigNumber): boolean; + + /** + * Checks whether the instance value is greater than or equal to n (>= n). + */ + ge(n: number | string | BigNumber): boolean; + + /** + * Checks whether the instance value is equal to n (== n). + */ + eq(n: number | string | BigNumber): boolean; + + /** + * Checks whether the instance value is less than n (< n). + */ + lt(n: number | string | BigNumber): boolean; + + /** + * Checks whether the instance value is less than or equal to n (<= n). + */ + le(n: number | string | BigNumber): boolean; + + /** + * Returns a new bignum with the instance value bitwise AND (&)-ed with n. + */ + and(n: number | string | BigNumber): BigNumber; + + /** + * Returns a new bignum with the instance value bitwise inclusive-OR (|)-ed with n. + */ + or(n: number | string | BigNumber): BigNumber; + + /** + * Returns a new bignum with the instance value bitwise exclusive-OR (^)-ed with n. + */ + xor(n: number | string | BigNumber): BigNumber; + + /** + * Returns a new bignum with the instance value modulo n. + */ + mod(n: number | string | BigNumber): BigNumber; + + /** + * Returns a new bignum with the instance value raised to the nth power. + */ + pow(n: number | string | BigNumber): BigNumber; + + /** + * Returns a new bignum with the instance value raised to the nth power modulo m. + */ + powm(n: number | string | BigNumber, m: number | string | BigNumber): BigNumber; + + /** + * Computes the multiplicative inverse modulo m. + */ + invertm(m: number | string | BigNumber): BigNumber; + + /** + * Returns a random number from 0 to this -1 + */ + rand(): BigNumber; + + /** + * Returns a random number from this to upperBound - 1 + */ + rand(upperBound: number | string | BigNumber): BigNumber; + + /** + * Checks whether the bignum is: + * + * - certainly prime (true) + * + * - probably prime ('maybe') + * + * - certainly composite (false) + */ + probPrime(): boolean | "maybe"; + + /** + * Returns the next prime number after this bignum + */ + nextPrime(): BigNumber; + + /** + * Returns a new bignum that is the square root. This truncates. + */ + sqrt(): BigNumber; + + /** + * Returns a new bignum that is the nth root. This truncates. + */ + root(n: number | string | BigNumber): BigNumber; + + /** + * Returns a new bignum that is the 2^n multiple. Equivalent of the << operator. + */ + shiftLeft(n: number | string | BigNumber): BigNumber; + + /** + * Returns a new bignum of the value integer divided by 2^n. Equivalent of the >> operator. + */ + shiftRight(n: number | string | BigNumber): BigNumber; + + /** + * Returns the greatest common divisor of the current bignum with n as a new bignum. + */ + gcd(n: number | string | BigNumber): BigNumber; + + /** + * Returns the Jacobi symbol (or Legendre symbol if n is prime) of the current bignum (= a) over n. + * Note that n must be odd and >= 3. 0 <= a < n. + * Returns -1 or 1 + */ + jacobi(n: number | string | BigNumber): number; + + /** + * Returns the number of bits used to represent the current bignum + */ + bitLength(): number; + + /** + * Checks whether the bit at the given index is set + */ + isBitSet(n: number): boolean; + + /** + * Generates a probable prime number of length bits. + * + * @param bits the number of bits + * @param safe If true, it will be a "safe" prime of the form p=2p'+1 where p' is also prime. Default: true + */ + static prime(bits: number, safe?: boolean): BigNumber; + + /** + * Creates a new bignum from a Buffer. + */ + static fromBuffer(buf: Buffer, opts?: I.BigNumber.BufferConvertOptions): BigNumber; + + /** + * One + */ + static ONE: BigNumber; + + /** + * Zero + */ + static ZERO: BigNumber; + } + + /** + * Represents a set of bits + */ + class BitSet { + /** + * Creates a new bitset of n bits + */ + constructor(n: number); + + /** + * Creates a new bitset from a dehydrated bitset + */ + constructor(key: string); + + /** + * Checks whether a bit at a specific index is set + */ + get(idx: number): boolean; + + /** + * Sets a single bit. + * Returns true if set was successfull + */ + set(idx: number): boolean; + + /** + * Sets a range of bits. + * Returns true if set was successfull + */ + setRange(from: number, to: number): boolean; + + /** + * Unsets a single bit. + * Returns true if unset was successfull + */ + unset(idx: number): boolean; + + /** + * Unsets a range of bits. + * Returns true if unset was successfull + */ + unsetRange(from: number, to: number): boolean; + + /** + * Toggles a single bit + */ + toggle(idx: number): boolean; + + /** + * Toggles a range of bits + */ + toggleRange(from: number, to: number): boolean; + + /** + * Clears the entire bitset + */ + clear(): boolean; + + /** + * Clones the set + */ + clone(): BitSet; + + /** + * Turns the bitset into a comma separated string that skips leading & trailing 0 words. + * Ends with the number of leading 0s and MAX_BIT. + * Useful if you need the bitset to be an object key (eg dynamic programming). + * Can rehydrate by passing the result into the constructor + */ + dehydrate(): string; + + /** + * Performs a bitwise AND on 2 bitsets or 1 bitset and 1 index. + * Both bitsets must have the same number of words, no length check is performed to prevent and overflow. + */ + and(value: number | BitSet): BitSet; + + /** + * Performs a bitwise OR on 2 bitsets or 1 bitset and 1 index. + * Both bitsets must have the same number of words, no length check is performed to prevent and overflow. + */ + or(value: number | BitSet): BitSet; + + /** + * Performs a bitwise XOR on 2 bitsets or 1 bitset and 1 index. + * Both bitsets must have the same number of words, no length check is performed to prevent and overflow. + */ + xor(value: number | BitSet): BitSet; + + /** + * Runs a custom function on every set bit. + * Faster than iterating over the entire bitset with a get(). + * If the callback returns `false` it stops iterating. + */ + forEach(callback: ((idx: number) => void | boolean)): void; + + /** + * Performs a circular shift bitset by an offset + * + * @param n number of positions that the bitset that will be shifted to the right. Using a negative number will result in a left shift. + */ + circularShift(n: number): BitSet; + + /** + * Gets the cardinality (count of set bits) for the entire bitset + */ + getCardinality(): number; + + /** + * Gets the indices of all set bits + */ + getIndices(): number[]; + + /** + * Checks if one bitset is subset of another. + */ + isSubsetOf(other: BitSet): boolean; + + /** + * Quickly determines if a bitset is empty + */ + isEmpty(): boolean; + + /** + * Quickly determines if both bitsets are equal (faster than checking if the XOR of the two is === 0). + * Both bitsets must have the same number of words, no length check is performed to prevent and overflow. + */ + isEqual(other: BitSet): boolean; + + /** + * Gets a string representation of the entire bitset, including leading 0s + */ + toString(): string; + + /** + * Finds first set bit (useful for processing queues, breadth-first tree searches, etc.). + * Returns -1 if not found + * + * @param startWord the word to start with (only used internally by nextSetBit) + */ + ffs(startWord?: number): number; + + /** + * Finds first zero (unset bit). + * Returns -1 if not found + * + * @param startWord the word to start with (only used internally by nextUnsetBit) + */ + ffz(startWord?: number): number; + + /** + * Finds last set bit. + * Returns -1 if not found + * + * @param startWord the word to start with (only used internally by previousSetBit) + */ + fls(startWord?: number): number; + + /** + * Finds last zero (unset bit). + * Returns -1 if not found + * + * @param startWord the word to start with (only used internally by previousUnsetBit) + */ + flz(startWord?: number): number; + + /** + * Finds first set bit, starting at a given index. + * Return -1 if not found + * + * @param idx the starting index for the next set bit + */ + nextSetBit(idx: number): number; + + /** + * Finds first unset bit, starting at a given index. + * Return -1 if not found + * + * @param idx the starting index for the next unset bit + */ + nextUnsetBit(idx: number): number; + + /** + * Finds last set bit, up to a given index. + * Returns -1 if not found + * + * @param idx the starting index for the next unset bit (going in reverse) + */ + previousSetBit(idx: number): number; + + /** + * Finds last unset bit, up to a given index. + * Returns -1 if not found + */ + previousUnsetBit(idx: number): number; + + /** + * Converts the bitset to a math.Long number + */ + toLong(): Long; + + /** + * Reads an unsigned integer of the given bits from the given offset + * + * @param bits number of bits, 1 by default + * @param offset offset, 0 by default + */ + readUInt(bits?: number, offset?: number): number; + + /** + * Writes the given unsigned integer + * + * @param val integer + * @param bits number of bits to write, 1 by default + * @param offset write offset, 0 by default + */ + writeUInt(val: number, bits?: number, offset?: number): void; + + /** + * Creates a new BitSet from the given math.Long number + */ + static fromLong(l: Long): BitSet; + } + + /** + * Returns a random number from min to max - 1 + * + * @param min lower bound, default is 0 + * @param max upper bound, default is 0xFFFFFFFF + */ + function random(min?: number, max?: number): number; + } +} diff --git a/types/adone/glosses/math/matrix.d.ts b/types/adone/glosses/math/matrix.d.ts new file mode 100644 index 0000000000..0340929ed6 --- /dev/null +++ b/types/adone/glosses/math/matrix.d.ts @@ -0,0 +1,3140 @@ +// based on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/gl-matrix + +declare namespace adone.math { + /** + * vector and matrix operations + */ + namespace matrix { + let EPSILON: number; + + /** + * Convert Degree To Radian + * + * @param a - Angle in Degrees + */ + function toRadian(a: number): number; + + /** + * Tests whether or not the arguments have approximately the same value, within an absolute + * or relative tolerance of EPSILON (an absolute tolerance is used for values less + * than or equal to 1.0, and a relative tolerance is used for larger values) + * + * @param a - The first number to test. + * @param b - The second number to test. + * @returns True if the numbers are approximately equal, false otherwise. + */ + function equals(a: number, b: number): boolean; + + namespace I { + type vec2 = Float32Array; + } + + /** + * 2 Dimensional Vector + */ + namespace vec2 { + /** + * Creates a new, empty vec2 + * + * @returns a new 2D vector + */ + function create(): I.vec2; + + /** + * Creates a new vec2 initialized with values from an existing vector + * + * @param a a vector to clone + * @returns a new 2D vector + */ + function clone(a: I.vec2 | number[]): I.vec2; + + /** + * Creates a new vec2 initialized with the given values + * + * @param x X component + * @param y Y component + * @returns a new 2D vector + */ + function fromValues(x: number, y: number): I.vec2; + + /** + * Copy the values from one vec2 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + function copy(out: I.vec2, a: I.vec2 | number[]): I.vec2; + + /** + * Set the components of a vec2 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @returns out + */ + function set(out: I.vec2, x: number, y: number): I.vec2; + + /** + * Adds two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function add(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[]): I.vec2; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function subtract(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[]): I.vec2; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function sub(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[]): I.vec2; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function multiply(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[]): I.vec2; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function mul(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[]): I.vec2; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function divide(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[]): I.vec2; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function div(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[]): I.vec2; + + /** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to ceil + * @returns {vec2} out + */ + function ceil(out: I.vec2, a: I.vec2 | number[]): I.vec2; + + /** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to floor + * @returns {vec2} out + */ + function floor(out: I.vec2, a: I.vec2 | number[]): I.vec2; + + /** + * Returns the minimum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function min(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[]): I.vec2; + + /** + * Returns the maximum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function max(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[]): I.vec2; + + /** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to round + * @returns {vec2} out + */ + function round(out: I.vec2, a: I.vec2 | number[]): I.vec2; + + /** + * Scales a vec2 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + function scale(out: I.vec2, a: I.vec2 | number[], b: number): I.vec2; + + /** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + function scaleAndAdd(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[], scale: number): I.vec2; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + function distance(a: I.vec2 | number[], b: I.vec2 | number[]): number; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + function dist(a: I.vec2 | number[], b: I.vec2 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + function squaredDistance(a: I.vec2 | number[], b: I.vec2 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + function sqrDist(a: I.vec2 | number[], b: I.vec2 | number[]): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + function length(a: I.vec2 | number[]): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + function len(a: I.vec2 | number[]): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + function squaredLength(a: I.vec2 | number[]): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + function sqrLen(a: I.vec2 | number[]): number; + + /** + * Negates the components of a vec2 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + function negate(out: I.vec2, a: I.vec2 | number[]): I.vec2; + + /** + * Returns the inverse of the components of a vec2 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + function inverse(out: I.vec2, a: I.vec2 | number[]): I.vec2; + + /** + * Normalize a vec2 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + function normalize(out: I.vec2, a: I.vec2 | number[]): I.vec2; + + /** + * Calculates the dot product of two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + function dot(a: I.vec2 | number[], b: I.vec2 | number[]): number; + + /** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function cross(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[]): I.vec2; + + /** + * Performs a linear interpolation between two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + function lerp(out: I.vec2, a: I.vec2 | number[], b: I.vec2 | number[], t: number): I.vec2; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + function random(out: I.vec2): I.vec2; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + function random(out: I.vec2, scale: number): I.vec2; + + /** + * Transforms the vec2 with a mat2 + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + function transformMat2(out: I.vec2, a: I.vec2 | number[], m: I.mat2): I.vec2; + + /** + * Transforms the vec2 with a mat2d + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + function transformMat2d(out: I.vec2, a: I.vec2 | number[], m: I.mat2d): I.vec2; + + /** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + function transformMat3(out: I.vec2, a: I.vec2 | number[], m: I.mat3): I.vec2; + + /** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + function transformMat4(out: I.vec2, a: I.vec2 | number[], m: I.mat4): I.vec2; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + */ + function forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: I.vec2 | number[], b: I.vec2 | number[], arg: any) => void, arg: any): Float32Array; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + */ + function forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: I.vec2 | number[], b: I.vec2 | number[]) => void): Float32Array; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + function str(a: I.vec2 | number[]): string; + + /** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + function exactEquals(a: I.vec2 | number[], b: I.vec2 | number[]): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + function equals(a: I.vec2 | number[], b: I.vec2 | number[]): boolean; + } + + namespace I { + type vec3 = Float32Array; + } + + /** + * 3 Dimensional Vector + */ + namespace vec3 { + /** + * Creates a new, empty vec3 + * + * @returns a new 3D vector + */ + function create(): I.vec3; + + /** + * Creates a new vec3 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 3D vector + */ + function clone(a: I.vec3 | number[]): I.vec3; + + /** + * Creates a new vec3 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @returns a new 3D vector + */ + function fromValues(x: number, y: number, z: number): I.vec3; + + /** + * Copy the values from one vec3 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + function copy(out: I.vec3, a: I.vec3 | number[]): I.vec3; + + /** + * Set the components of a vec3 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @returns out + */ + function set(out: I.vec3, x: number, y: number, z: number): I.vec3; + + /** + * Adds two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function add(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[]): I.vec3; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function subtract(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[]): I.vec3; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function sub(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[]): I.vec3; + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function multiply(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[]): I.vec3; + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function mul(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[]): I.vec3; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function divide(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[]): I.vec3; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function div(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[]): I.vec3; + + /** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to ceil + * @returns {vec3} out + */ + function ceil(out: I.vec3, a: I.vec3 | number[]): I.vec3; + + /** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to floor + * @returns {vec3} out + */ + function floor(out: I.vec3, a: I.vec3 | number[]): I.vec3; + + /** + * Returns the minimum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function min(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[]): I.vec3; + + /** + * Returns the maximum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function max(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[]): I.vec3; + + /** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to round + * @returns {vec3} out + */ + function round(out: I.vec3, a: I.vec3 | number[]): I.vec3; + + /** + * Scales a vec3 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + function scale(out: I.vec3, a: I.vec3 | number[], b: number): I.vec3; + + /** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + function scaleAndAdd(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[], scale: number): I.vec3; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + function distance(a: I.vec3 | number[], b: I.vec3 | number[]): number; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + function dist(a: I.vec3 | number[], b: I.vec3 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + function squaredDistance(a: I.vec3 | number[], b: I.vec3 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + function sqrDist(a: I.vec3 | number[], b: I.vec3 | number[]): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + function length(a: I.vec3 | number[]): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + function len(a: I.vec3 | number[]): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + function squaredLength(a: I.vec3 | number[]): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + function sqrLen(a: I.vec3 | number[]): number; + + /** + * Negates the components of a vec3 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + function negate(out: I.vec3, a: I.vec3 | number[]): I.vec3; + + /** + * Returns the inverse of the components of a vec3 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + function inverse(out: I.vec3, a: I.vec3 | number[]): I.vec3; + + /** + * Normalize a vec3 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + function normalize(out: I.vec3, a: I.vec3 | number[]): I.vec3; + + /** + * Calculates the dot product of two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + function dot(a: I.vec3 | number[], b: I.vec3 | number[]): number; + + /** + * Computes the cross product of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function cross(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[]): I.vec3; + + /** + * Performs a linear interpolation between two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + function lerp(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[], t: number): I.vec3; + + /** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + function hermite(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[], c: I.vec3 | number[], d: I.vec3 | number[], t: number): I.vec3; + + /** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + function bezier(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[], c: I.vec3 | number[], d: I.vec3 | number[], t: number): I.vec3; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + function random(out: I.vec3): I.vec3; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned + * @returns out + */ + function random(out: I.vec3, scale: number): I.vec3; + + /** + * Transforms the vec3 with a mat3. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m the 3x3 matrix to transform with + * @returns out + */ + function transformMat3(out: I.vec3, a: I.vec3 | number[], m: I.mat3): I.vec3; + + /** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + function transformMat4(out: I.vec3, a: I.vec3 | number[], m: I.mat4): I.vec3; + + /** + * Transforms the vec3 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + function transformQuat(out: I.vec3, a: I.vec3 | number[], q: I.quat): I.vec3; + + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + function rotateX(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[], c: number): I.vec3; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + function rotateY(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[], c: number): I.vec3; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + function rotateZ(out: I.vec3, a: I.vec3 | number[], b: I.vec3 | number[], c: number): I.vec3; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + function forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: I.vec3 | number[], b: I.vec3 | number[], arg: any) => void, arg: any): Float32Array; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + function forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: I.vec3 | number[], b: I.vec3 | number[]) => void): Float32Array; + + /** + * Get the angle between two 3D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + function angle(a: I.vec3 | number[], b: I.vec3 | number[]): number; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + function str(a: I.vec3 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + function exactEquals(a: I.vec3 | number[], b: I.vec3 | number[]): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + function equals(a: I.vec3 | number[], b: I.vec3 | number[]): boolean; + } + + namespace I { + type vec4 = Float32Array; + } + + /** + * 4 Dimensional Vector + */ + namespace vec4 { + /** + * Creates a new, empty vec4 + * + * @returns a new 4D vector + */ + function create(): I.vec4; + + /** + * Creates a new vec4 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 4D vector + */ + function clone(a: I.vec4 | number[]): I.vec4; + + /** + * Creates a new vec4 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new 4D vector + */ + function fromValues(x: number, y: number, z: number, w: number): I.vec4; + + /** + * Copy the values from one vec4 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + function copy(out: I.vec4, a: I.vec4 | number[]): I.vec4; + + /** + * Set the components of a vec4 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + */ + function set(out: I.vec4, x: number, y: number, z: number, w: number): I.vec4; + + /** + * Adds two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function add(out: I.vec4, a: I.vec4 | number[], b: I.vec4 | number[]): I.vec4; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function subtract(out: I.vec4, a: I.vec4 | number[], b: I.vec4 | number[]): I.vec4; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function sub(out: I.vec4, a: I.vec4 | number[], b: I.vec4 | number[]): I.vec4; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function multiply(out: I.vec4, a: I.vec4 | number[], b: I.vec4 | number[]): I.vec4; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function mul(out: I.vec4, a: I.vec4 | number[], b: I.vec4 | number[]): I.vec4; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function divide(out: I.vec4, a: I.vec4 | number[], b: I.vec4 | number[]): I.vec4; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function div(out: I.vec4, a: I.vec4 | number[], b: I.vec4 | number[]): I.vec4; + + /** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to ceil + * @returns {vec4} out + */ + function ceil(out: I.vec4, a: I.vec4 | number[]): I.vec4; + + /** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to floor + * @returns {vec4} out + */ + function floor(out: I.vec4, a: I.vec4 | number[]): I.vec4; + + /** + * Returns the minimum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function min(out: I.vec4, a: I.vec4 | number[], b: I.vec4 | number[]): I.vec4; + + /** + * Returns the maximum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + function max(out: I.vec4, a: I.vec4 | number[], b: I.vec4 | number[]): I.vec4; + + /** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to round + * @returns {vec4} out + */ + function round(out: I.vec4, a: I.vec4 | number[]): I.vec4; + + /** + * Scales a vec4 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + function scale(out: I.vec4, a: I.vec4 | number[], b: number): I.vec4; + + /** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + function scaleAndAdd(out: I.vec4, a: I.vec4 | number[], b: I.vec4 | number[], scale: number): I.vec4; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + function distance(a: I.vec4 | number[], b: I.vec4 | number[]): number; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + function dist(a: I.vec4 | number[], b: I.vec4 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + function squaredDistance(a: I.vec4 | number[], b: I.vec4 | number[]): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + function sqrDist(a: I.vec4 | number[], b: I.vec4 | number[]): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + function length(a: I.vec4 | number[]): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + function len(a: I.vec4 | number[]): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + function squaredLength(a: I.vec4 | number[]): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + function sqrLen(a: I.vec4 | number[]): number; + + /** + * Negates the components of a vec4 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + function negate(out: I.vec4, a: I.vec4 | number[]): I.vec4; + + /** + * Returns the inverse of the components of a vec4 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + function inverse(out: I.vec4, a: I.vec4 | number[]): I.vec4; + + /** + * Normalize a vec4 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + function normalize(out: I.vec4, a: I.vec4 | number[]): I.vec4; + + /** + * Calculates the dot product of two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + function dot(a: I.vec4 | number[], b: I.vec4 | number[]): number; + + /** + * Performs a linear interpolation between two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + function lerp(out: I.vec4, a: I.vec4 | number[], b: I.vec4 | number[], t: number): I.vec4; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + function random(out: I.vec4): I.vec4; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + function random(out: I.vec4, scale: number): I.vec4; + + /** + * Transforms the vec4 with a mat4. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + function transformMat4(out: I.vec4, a: I.vec4 | number[], m: I.mat4): I.vec4; + + /** + * Transforms the vec4 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + + function transformQuat(out: I.vec4, a: I.vec4 | number[], q: I.quat): I.vec4; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + function forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: I.vec4 | number[], b: I.vec4 | number[], arg: any) => void, arg: any): Float32Array; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + function forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: I.vec4 | number[], b: I.vec4 | number[]) => void): Float32Array; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + function str(a: I.vec4 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + function exactEquals(a: I.vec4 | number[], b: I.vec4 | number[]): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + function equals(a: I.vec4 | number[], b: I.vec4 | number[]): boolean; + } + + namespace I { + type mat2 = Float32Array; + } + + /** + * 2x2 Matrix + */ + namespace mat2 { + /** + * Creates a new identity mat2 + * + * @returns a new 2x2 matrix + */ + function create(): I.mat2; + + /** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x2 matrix + */ + function clone(a: I.mat2): I.mat2; + + /** + * Copy the values from one mat2 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function copy(out: I.mat2, a: I.mat2): I.mat2; + + /** + * Set a mat2 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + function identity(out: I.mat2): I.mat2; + + /** + * Create a new mat2 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ + function fromValues(m00: number, m01: number, m10: number, m11: number): I.mat2; + + /** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ + function set(out: I.mat2, m00: number, m01: number, m10: number, m11: number): I.mat2; + + /** + * Transpose the values of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function transpose(out: I.mat2, a: I.mat2): I.mat2; + + /** + * Inverts a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function invert(out: I.mat2, a: I.mat2): I.mat2 | null; + + /** + * Calculates the adjugate of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function adjoint(out: I.mat2, a: I.mat2): I.mat2; + + /** + * Calculates the determinant of a mat2 + * + * @param a the source matrix + * @returns determinant of a + */ + function determinant(a: I.mat2): number; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + function multiply(out: I.mat2, a: I.mat2, b: I.mat2): I.mat2; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + function mul(out: I.mat2, a: I.mat2, b: I.mat2): I.mat2; + + /** + * Rotates a mat2 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + function rotate(out: I.mat2, a: I.mat2, rad: number): I.mat2; + + /** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + */ + function scale(out: I.mat2, a: I.mat2, v: I.vec2 | number[]): I.mat2; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + function fromRotation(out: I.mat2, rad: number): I.mat2; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2} out + */ + function fromScaling(out: I.mat2, v: I.vec2 | number[]): I.mat2; + + /** + * Returns a string representation of a mat2 + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + function str(a: I.mat2): string; + + /** + * Returns Frobenius norm of a mat2 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + function frob(a: I.mat2): number; + + /** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param L the lower triangular matrix + * @param D the diagonal matrix + * @param U the upper triangular matrix + * @param a the input matrix to factorize + */ + function LDU(L: I.mat2, D: I.mat2, U: I.mat2, a: I.mat2): I.mat2; + + /** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + function add(out: I.mat2, a: I.mat2, b: I.mat2): I.mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + function subtract(out: I.mat2, a: I.mat2, b: I.mat2): I.mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + function sub(out: I.mat2, a: I.mat2, b: I.mat2): I.mat2; + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + function exactEquals(a: I.mat2, b: I.mat2): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + function equals(a: I.mat2, b: I.mat2): boolean; + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ + function multiplyScalar(out: I.mat2, a: I.mat2, b: number): I.mat2; + + /** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ + function multiplyScalarAndAdd(out: I.mat2, a: I.mat2, b: I.mat2, scale: number): I.mat2; + } + + namespace I { + type mat2d = Float32Array; + } + + /** + * 2x3 Matrix + */ + namespace mat2d { + /** + * Creates a new identity mat2d + * + * @returns a new 2x3 matrix + */ + function create(): I.mat2d; + + /** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x3 matrix + */ + function clone(a: I.mat2d): I.mat2d; + + /** + * Copy the values from one mat2d to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function copy(out: I.mat2d, a: I.mat2d): I.mat2d; + + /** + * Set a mat2d to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + function identity(out: I.mat2d): I.mat2d; + + /** + * Create a new mat2d with the given values + * + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} A new mat2d + */ + function fromValues(a: number, b: number, c: number, d: number, tx: number, ty: number): I.mat2d; + + /** + * Set the components of a mat2d to the given values + * + * @param {mat2d} out the receiving matrix + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} out + */ + function set(out: I.mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): I.mat2d; + + /** + * Inverts a mat2d + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function invert(out: I.mat2d, a: I.mat2d): I.mat2d | null; + + /** + * Calculates the determinant of a mat2d + * + * @param a the source matrix + * @returns determinant of a + */ + function determinant(a: I.mat2d): number; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + function multiply(out: I.mat2d, a: I.mat2d, b: I.mat2d): I.mat2d; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + function mul(out: I.mat2d, a: I.mat2d, b: I.mat2d): I.mat2d; + + /** + * Rotates a mat2d by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + function rotate(out: I.mat2d, a: I.mat2d, rad: number): I.mat2d; + + /** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to scale the matrix by + * @returns out + */ + function scale(out: I.mat2d, a: I.mat2d, v: I.vec2 | number[]): I.mat2d; + + /** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to translate the matrix by + * @returns out + */ + function translate(out: I.mat2d, a: I.mat2d, v: I.vec2 | number[]): I.mat2d; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.rotate(dest, dest, rad); + * + * @param {mat2d} out mat2d receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + function fromRotation(out: I.mat2d, rad: number): I.mat2d; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.scale(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2d} out + */ + function fromScaling(out: I.mat2d, v: I.vec2 | number[]): I.mat2d; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.translate(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Translation vector + * @returns {mat2d} out + */ + function fromTranslation(out: I.mat2d, v: I.vec2 | number[]): I.mat2d; + + /** + * Returns a string representation of a mat2d + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + function str(a: I.mat2d): string; + + /** + * Returns Frobenius norm of a mat2d + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + function frob(a: I.mat2d): number; + + /** + * Adds two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + function add(out: I.mat2d, a: I.mat2d, b: I.mat2d): I.mat2d; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + function subtract(out: I.mat2d, a: I.mat2d, b: I.mat2d): I.mat2d; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + function sub(out: I.mat2d, a: I.mat2d, b: I.mat2d): I.mat2d; + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2d} out + */ + function multiplyScalar(out: I.mat2d, a: I.mat2d, b: number): I.mat2d; + + /** + * Adds two mat2d's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2d} out the receiving vector + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2d} out + */ + function multiplyScalarAndAdd(out: I.mat2d, a: I.mat2d, b: I.mat2d, scale: number): I.mat2d; + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + function exactEquals(a: I.mat2d, b: I.mat2d): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + function equals(a: I.mat2d, b: I.mat2d): boolean; + } + + namespace I { + type mat3 = Float32Array; + } + + /** + * 3x3 Matrix + */ + namespace mat3 { + /** + * Creates a new identity mat3 + * + * @returns a new 3x3 matrix + */ + function create(): I.mat3; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {mat4} a the source 4x4 matrix + * @returns {mat3} out + */ + function fromMat4(out: I.mat3, a: I.mat4): I.mat3; + + /** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 3x3 matrix + */ + function clone(a: I.mat3): I.mat3; + + /** + * Copy the values from one mat3 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function copy(out: I.mat3, a: I.mat3): I.mat3; + + /** + * Create a new mat3 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ + function fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): I.mat3; + + /** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ + function set(out: I.mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): I.mat3; + + /** + * Set a mat3 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + function identity(out: I.mat3): I.mat3; + + /** + * Transpose the values of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function transpose(out: I.mat3, a: I.mat3): I.mat3; + + /** + * Inverts a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function invert(out: I.mat3, a: I.mat3): I.mat3 | null; + + /** + * Calculates the adjugate of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function adjoint(out: I.mat3, a: I.mat3): I.mat3; + + /** + * Calculates the determinant of a mat3 + * + * @param a the source matrix + * @returns determinant of a + */ + function determinant(a: I.mat3): number; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + function multiply(out: I.mat3, a: I.mat3, b: I.mat3): I.mat3; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + function mul(out: I.mat3, a: I.mat3, b: I.mat3): I.mat3; + + /** + * Translate a mat3 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + function translate(out: I.mat3, a: I.mat3, v: I.vec3 | number[]): I.mat3; + + /** + * Rotates a mat3 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + function rotate(out: I.mat3, a: I.mat3, rad: number): I.mat3; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + */ + function scale(out: I.mat3, a: I.mat3, v: I.vec2 | number[]): I.mat3; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Translation vector + * @returns {mat3} out + */ + function fromTranslation(out: I.mat3, v: I.vec2 | number[]): I.mat3; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + function fromRotation(out: I.mat3, rad: number): I.mat3; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat3} out + */ + function fromScaling(out: I.mat3, v: I.vec2 | number[]): I.mat3; + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + */ + function fromMat2d(out: I.mat3, a: I.mat2d): I.mat3; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + function fromQuat(out: I.mat3, q: I.quat): I.mat3; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + function normalFromMat4(out: I.mat3, a: I.mat4): I.mat3 | null; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + function str(mat: I.mat3): string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + function frob(a: I.mat3): number; + + /** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + function add(out: I.mat3, a: I.mat3, b: I.mat3): I.mat3; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + function subtract(out: I.mat3, a: I.mat3, b: I.mat3): I.mat3; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + function sub(out: I.mat3, a: I.mat3, b: I.mat3): I.mat3; + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ + function multiplyScalar(out: I.mat3, a: I.mat3, b: number): I.mat3; + + /** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ + function multiplyScalarAndAdd(out: I.mat3, a: I.mat3, b: I.mat3, scale: number): I.mat3; + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + function exactEquals(a: I.mat3, b: I.mat3): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + function equals(a: I.mat3, b: I.mat3): boolean; + } + + namespace I { + type mat4 = Float32Array; + } + + /** + * 4x4 Matrix + */ + namespace mat4 { + /** + * Creates a new identity mat4 + * + * @returns a new 4x4 matrix + */ + function create(): I.mat4; + + /** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 4x4 matrix + */ + function clone(a: I.mat4): I.mat4; + + /** + * Copy the values from one mat4 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function copy(out: I.mat4, a: I.mat4): I.mat4; + + /** + * Create a new mat4 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ + function fromValues( + m00: number, + m01: number, + m02: number, + m03: number, + m10: number, + m11: number, + m12: number, + m13: number, + m20: number, + m21: number, + m22: number, + m23: number, + m30: number, + m31: number, + m32: number, + m33: number + ): I.mat4; + + /** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ + function set( + out: I.mat4, + m00: number, + m01: number, + m02: number, + m03: number, + m10: number, + m11: number, + m12: number, + m13: number, + m20: number, + m21: number, + m22: number, + m23: number, + m30: number, + m31: number, + m32: number, + m33: number + ): I.mat4; + + /** + * Set a mat4 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + function identity(out: I.mat4): I.mat4; + + /** + * Transpose the values of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function transpose(out: I.mat4, a: I.mat4): I.mat4; + + /** + * Inverts a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function invert(out: I.mat4, a: I.mat4): I.mat4 | null; + + /** + * Calculates the adjugate of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + function adjoint(out: I.mat4, a: I.mat4): I.mat4; + + /** + * Calculates the determinant of a mat4 + * + * @param a the source matrix + * @returns determinant of a + */ + function determinant(a: I.mat4): number; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + function multiply(out: I.mat4, a: I.mat4, b: I.mat4): I.mat4; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + function mul(out: I.mat4, a: I.mat4, b: I.mat4): I.mat4; + + /** + * Translate a mat4 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + function translate(out: I.mat4, a: I.mat4, v: I.vec3 | number[]): I.mat4; + + /** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param out the receiving matrix + * @param a the matrix to scale + * @param v the vec3 to scale the matrix by + * @returns out + */ + function scale(out: I.mat4, a: I.mat4, v: I.vec3 | number[]): I.mat4; + + /** + * Rotates a mat4 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @param axis the axis to rotate around + * @returns out + */ + function rotate(out: I.mat4, a: I.mat4, rad: number, axis: I.vec3 | number[]): I.mat4; + + /** + * Rotates a matrix by the given angle around the X axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + function rotateX(out: I.mat4, a: I.mat4, rad: number): I.mat4; + + /** + * Rotates a matrix by the given angle around the Y axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + function rotateY(out: I.mat4, a: I.mat4, rad: number): I.mat4; + + /** + * Rotates a matrix by the given angle around the Z axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + function rotateZ(out: I.mat4, a: I.mat4, rad: number): I.mat4; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Translation vector + * @returns {mat4} out + */ + function fromTranslation(out: I.mat4, v: I.vec3 | number[]): I.mat4; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Scaling vector + * @returns {mat4} out + */ + function fromScaling(out: I.mat4, v: I.vec3 | number[]): I.mat4; + + /** + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out + */ + function fromRotation(out: I.mat4, rad: number, axis: I.vec3 | number[]): I.mat4; + + /** + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + function fromXRotation(out: I.mat4, rad: number): I.mat4; + + /** + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + function fromYRotation(out: I.mat4, rad: number): I.mat4; + + /** + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + function fromZRotation(out: I.mat4, rad: number): I.mat4; + + /** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @returns out + */ + function fromRotationTranslation(out: I.mat4, q: I.quat, v: I.vec3 | number[]): I.mat4; + + /** + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRotationTranslation, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + function getTranslation(out: I.vec3, mat: I.mat4): I.vec3; + + /** + * Returns the scaling factor component of a transformation matrix. + * If a matrix is built with fromRotationTranslationScale with a + * normalized Quaternion parameter, the returned vector will be + * the same as the scaling vector originally supplied. + * @param {vec3} out Vector to receive scaling factor component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + function getScaling(out: I.vec3, mat: I.mat4): I.vec3; + + /** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRotationTranslation, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ + function getRotation(out: I.quat, mat: I.mat4): I.quat; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @param s Scaling vector + * @returns out + */ + function fromRotationTranslationScale(out: I.mat4, q: I.quat, v: I.vec3 | number[], s: I.vec3 | number[]): I.mat4; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Rotation quaternion + * @param {vec3} v Translation vector + * @param {vec3} s Scaling vector + * @param {vec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ + function fromRotationTranslationScaleOrigin(out: I.mat4, q: I.quat, v: I.vec3 | number[], s: I.vec3 | number[], o: I.vec3 | number[]): I.mat4; + + /** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ + function fromQuat(out: I.mat4, q: I.quat): I.mat4; + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + function frustum(out: I.mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): I.mat4; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + function perspective(out: I.mat4, fovy: number, aspect: number, + near: number, far: number): I.mat4; + + /** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experimental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + function perspectiveFromFieldOfView( + out: I.mat4, + fov: { + upDegrees: number, + downDegrees: number, + leftDegrees: number, + rightDegrees: number + }, + near: number, + far: number + ): I.mat4; + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + function ortho(out: I.mat4, left: number, right: number, bottom: number, top: number, near: number, far: number): I.mat4; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + function lookAt(out: I.mat4, eye: I.vec3 | number[], center: I.vec3 | number[], up: I.vec3 | number[]): I.mat4; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + function str(mat: I.mat4): string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + function frob(a: I.mat4): number; + + /** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + function add(out: I.mat4, a: I.mat4, b: I.mat4): I.mat4; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + function subtract(out: I.mat4, a: I.mat4, b: I.mat4): I.mat4; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + function sub(out: I.mat4, a: I.mat4, b: I.mat4): I.mat4; + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ + function multiplyScalar(out: I.mat4, a: I.mat4, b: number): I.mat4; + + /** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ + function multiplyScalarAndAdd(out: I.mat4, a: I.mat4, b: I.mat4, scale: number): I.mat4; + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + function exactEquals(a: I.mat4, b: I.mat4): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + function equals(a: I.mat4, b: I.mat4): boolean; + } + + namespace I { + type quat = Float32Array; + } + + /** + * Quaternion + */ + namespace quat { + /** + * Creates a new identity quat + * + * @returns a new quaternion + */ + function create(): I.quat; + + /** + * Creates a new quat initialized with values from an existing quaternion + * + * @param a quaternion to clone + * @returns a new quaternion + * @function + */ + function clone(a: I.quat): I.quat; + + /** + * Creates a new quat initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new quaternion + * @function + */ + function fromValues(x: number, y: number, z: number, w: number): I.quat; + + /** + * Copy the values from one quat to another + * + * @param out the receiving quaternion + * @param a the source quaternion + * @returns out + * @function + */ + function copy(out: I.quat, a: I.quat): I.quat; + + /** + * Set the components of a quat to the given values + * + * @param out the receiving quaternion + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + * @function + */ + function set(out: I.quat, x: number, y: number, z: number, w: number): I.quat; + + /** + * Set a quat to the identity quaternion + * + * @param out the receiving quaternion + * @returns out + */ + function identity(out: I.quat): I.quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {vec3} a the initial vector + * @param {vec3} b the destination vector + * @returns {quat} out + */ + function rotationTo(out: I.quat, a: I.vec3 | number[], b: I.vec3 | number[]): I.quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param out the receiving quaternion. + * @param a the initial vector + * @param b the destination vector + * @returns out + */ + function rotationTo(out: I.quat, a: I.vec3 | number[], b: I.vec3 | number[]): I.quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + function setAxes(out: I.quat, view: I.vec3 | number[], right: I.vec3 | number[], up: I.vec3 | number[]): I.quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param out the receiving quat + * @param view the vector representing the viewing direction + * @param right the vector representing the local "right" direction + * @param up the vector representing the local "up" direction + * @returns out + */ + function setAxes(out: I.quat, view: I.vec3 | number[], right: I.vec3 | number[], up: I.vec3 | number[]): I.quat; + + /** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param out the receiving quaternion + * @param axis the axis around which to rotate + * @param rad the angle in radians + * @returns out + */ + function setAxisAngle(out: I.quat, axis: I.vec3 | number[], rad: number): I.quat; + + /** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * setAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {quat} q Quaternion to be decomposed + * @return {number} Angle, in radians, of the rotation + */ + function getAxisAngle(out_axis: I.vec3 | number[], q: I.quat): number; + + /** + * Adds two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + * @function + */ + function add(out: I.quat, a: I.quat, b: I.quat): I.quat; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + function multiply(out: I.quat, a: I.quat, b: I.quat): I.quat; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + function mul(out: I.quat, a: I.quat, b: I.quat): I.quat; + + /** + * Scales a quat by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + * @function + */ + function scale(out: I.quat, a: I.quat, b: number): I.quat; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + function length(a: I.quat): number; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + function len(a: I.quat): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + function squaredLength(a: I.quat): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + function sqrLen(a: I.quat): number; + + /** + * Normalize a quat + * + * @param out the receiving quaternion + * @param a quaternion to normalize + * @returns out + * @function + */ + function normalize(out: I.quat, a: I.quat): I.quat; + + /** + * Calculates the dot product of two quat's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + * @function + */ + function dot(a: I.quat, b: I.quat): number; + + /** + * Performs a linear interpolation between two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + * @function + */ + function lerp(out: I.quat, a: I.quat, b: I.quat, t: number): I.quat; + + /** + * Performs a spherical linear interpolation between two quat + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + function slerp(out: I.quat, a: I.quat, b: I.quat, t: number): I.quat; + + /** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {quat} c the third operand + * @param {quat} d the fourth operand + * @param {number} t interpolation amount + * @returns {quat} out + */ + function sqlerp(out: I.quat, a: I.quat, b: I.quat, c: I.quat, d: I.quat, t: number): I.quat; + + /** + * Calculates the inverse of a quat + * + * @param out the receiving quaternion + * @param a quat to calculate inverse of + * @returns out + */ + function invert(out: I.quat, a: I.quat): I.quat; + + /** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param out the receiving quaternion + * @param a quat to calculate conjugate of + * @returns out + */ + function conjugate(out: I.quat, a: I.quat): I.quat; + + /** + * Returns a string representation of a quaternion + * + * @param a quat to represent as a string + * @returns string representation of the quat + */ + function str(a: I.quat): string; + + /** + * Rotates a quaternion by the given angle about the X axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + function rotateX(out: I.quat, a: I.quat, rad: number): I.quat; + + /** + * Rotates a quaternion by the given angle about the Y axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + function rotateY(out: I.quat, a: I.quat, rad: number): I.quat; + + /** + * Rotates a quaternion by the given angle about the Z axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + function rotateZ(out: I.quat, a: I.quat, rad: number): I.quat; + + /** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param out the receiving quaternion + * @param m rotation matrix + * @returns out + * @function + */ + function fromMat3(out: I.quat, m: I.mat3): I.quat; + + /** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param out the receiving quaternion + * @param a quat to calculate W component of + * @returns out + */ + function calculateW(out: I.quat, a: I.quat): I.quat; + + /** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + function exactEquals(a: I.quat, b: I.quat): boolean; + + /** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + function equals(a: I.quat, b: I.quat): boolean; + } + } +} diff --git a/types/adone/glosses/math/simd.d.ts b/types/adone/glosses/math/simd.d.ts new file mode 100644 index 0000000000..a90d761036 --- /dev/null +++ b/types/adone/glosses/math/simd.d.ts @@ -0,0 +1,2053 @@ +// based on https://github.com/ConquestArrow/simd.d.ts + +declare namespace adone.math { + /** + * ES7 (proposed) SIMD numeric type polyfill + */ + namespace simd { + namespace I { + type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray + | Int16Array | Uint16Array + | Int32Array | Uint32Array + | Float32Array | Float64Array; + + /** + * 128-bits divided into 4 lanes storing single precision floating point values. + */ + interface Float32x4 { + constructor: Float32x4Constructor; + valueOf(): Float32x4; + toLocaleString(): string; + toString(): string; + + /** + * The initial value of the @@toStringTag property is the String value "SIMD.Float32x4". + */ + [Symbol.toStringTag]: string; + [Symbol.toPrimitive](hint: "string"): string; + [Symbol.toPrimitive](hint: "number"): number; + [Symbol.toPrimitive](hint: "default"): Float32x4; + [Symbol.toPrimitive](hint: string): any; + } + + interface Float32x4Constructor { + /** + * SIMD.Float32x4 constructor + * @param s0 A 32bit float specifying the value of the lane. + * @param s1 A 32bit float specifying the value of the lane. + * @param s2 A 32bit float specifying the value of the lane. + * @param s3 A 32bit float specifying the value of the lane. + * @return SIMD.Float32x4 object + */ + (s0?: number, s1?: number, s2?: number, s3?: number): Float32x4; + + prototype: Float32x4; + + /** + * Returns the value of the given lane. + * @param simd An instance of a corresponding SIMD type. + * @param lane An index number for which lane to extract. + * @return The value of the extracted lane. + */ + extractLane(simd: Float32x4, lane: number): number; + + /** + * Returns a new instance with the lane values swizzled. + * @param a + * @param l1 + * @param l2 + * @param l3 + * @param l4 + */ + swizzle(a: Float32x4, l1: number, l2: number, l3: number, l4: number): Float32x4; + + /** + * Returns a new instance with the lane values shuffled. + * @param a + * @param b + * @param l1 + * @param l2 + * @param l3 + * @param l4 + */ + shuffle(a: Float32x4, b: Float32x4, l1: number, l2: number, l3: number, l4: number): Float32x4; + + /** + * Returns a new instance if the parameter is a valid SIMD data type and the same as Float32x4. Throws a TypeError otherwise. + * @param a + */ + check(a: Float32x4): Float32x4; + + /** + * Creates a new SIMD.Float32x4 data type with all lanes set to a given value. + * @param n + */ + splat(n: number): Float32x4; + + /** + * Returns a new instance with the given lane value replaced. + * @param simd An instance of a corresponding SIMD type. + * @param lane + * @param value A new value to be used for the lane. + * @return A new SIMD data type with the given lane value replaced. + */ + replaceLane(simd: Float32x4, lane: number, value: number): Float32x4; + + /** + * Returns a new instance with the lane values being a mix of the lanes depending on the selector mask. + * @param selector the selector mask. + * @param a If the selector mask lane is `true`, pick the corresponding lane value from here. + * @param b If the selector mask lane is `false`, pick the corresponding lane value from here. + */ + select(selector: Bool32x4, a: Float32x4, b: Float32x4): Float32x4; + + equal(a: Float32x4, b: Float32x4): Bool32x4; + + notEqual(a: Float32x4, b: Float32x4): Bool32x4; + + lessThan(a: Float32x4, b: Float32x4): Bool32x4; + + lessThanOrEqual(a: Float32x4, b: Float32x4): Bool32x4; + + greaterThan(a: Float32x4, b: Float32x4): Bool32x4; + + greaterThanOrEqual(a: Float32x4, b: Float32x4): Bool32x4; + + add(a: Float32x4, b: Float32x4): Float32x4; + + sub(a: Float32x4, b: Float32x4): Float32x4; + + mul(a: Float32x4, b: Float32x4): Float32x4; + + div(a: Float32x4, b: Float32x4): Float32x4; + + /** + * + * @param a + */ + neg(a: Float32x4): Float32x4; + + /** + * + * @param a + */ + abs(a: Float32x4): Float32x4; + + min(a: Float32x4, b: Float32x4): Float32x4; + + max(a: Float32x4, b: Float32x4): Float32x4; + + minNum(a: Float32x4, b: Float32x4): Float32x4; + + maxNum(a: Float32x4, b: Float32x4): Float32x4; + + reciprocalApproximation(a: Float32x4, b: Float32x4): Float32x4; + + /** + * + * @param a + */ + reciprocalSqrtApproximation(a: Float32x4): Float32x4; + + /** + * + * @param a + */ + sqrt(a: Float32x4): Float32x4; + + /** + * Returns a new instance with all lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load(tarray: TypedArray, index: number): Float32x4; + + /** + * Returns a new instance with 1 lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load1(tarray: TypedArray, index: number): Float32x4; + + /** + * Returns a new instance with 2 lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load2(tarray: TypedArray, index: number): Float32x4; + + /** + * Returns a new instance with 3 lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load3(tarray: TypedArray, index: number): Float32x4; + + /** + * Store all values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store(tarray: TypedArray, index: number, value: Float32x4): Float32x4; + + /** + * Store 1 values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store1(tarray: TypedArray, index: number, value: Float32x4): Float32x4; + + /** + * Store 2 values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store2(tarray: TypedArray, index: number, value: Float32x4): Float32x4; + + /** + * Store 3 values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store3(tarray: Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array, index: number, value: Float32x4): Float32x4; + + /** + * Creates a new SIMD data type with a float conversion from a Int32x4. + * @param value An Int32x4 SIMD type to convert from. + */ + fromInt32x4(value: Int32x4): Float32x4; + + /** + * Creates a new SIMD data type with a float conversion from a Uint32x4. + * @param value An Uint32x4 SIMD type to convert from. + */ + fromUint32x4(value: Uint32x4): Float32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int32x4. + * @param value A Int32x4 SIMD type to convert from (bitwise). + */ + fromInt32x4Bits(value: Int32x4): Float32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int16x8. + * @param value A Int16x8 SIMD type to convert from (bitwise). + */ + fromInt16x8Bits(value: Int16x8): Float32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int8x16. + * @param value A Int8x16 SIMD type to convert from (bitwise). + */ + fromInt8x16Bits(value: Int8x16): Float32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint32x4. + * @param value A Uint32x4 SIMD type to convert from (bitwise). + */ + fromUint32x4Bits(value: Uint32x4): Float32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint16x8. + * @param value A Uint16x8 SIMD type to convert from (bitwise). + */ + fromUint16x8Bits(value: Uint16x8): Float32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint8x16. + * @param value A Uint8x16 SIMD type to convert from (bitwise). + */ + fromUint8x16Bits(value: Uint8x16): Float32x4; + } + + /** + * 128-bits divided into 4 lanes storing 32-bit signed integer values. + */ + interface Int32x4 { + constructor: Int32x4Constructor; + valueOf(): Int32x4; + toLocaleString(): string; + toString(): string; + + /** + * The initial value of the @@toStringTag property is the String value "SIMD.Int32x4". + */ + [Symbol.toStringTag]: string; + [Symbol.toPrimitive](hint: "string"): string; + [Symbol.toPrimitive](hint: "number"): number; + [Symbol.toPrimitive](hint: "default"): Int32x4; + [Symbol.toPrimitive](hint: string): any; + } + + interface Int32x4Constructor { + /** + * SIMD.Int32x4 constructor + * @param s0 A 32bit int specifying the value of the lane. + * @param s1 A 32bit int specifying the value of the lane. + * @param s2 A 32bit int specifying the value of the lane. + * @param s3 A 32bit int specifying the value of the lane. + * @return SIMD.Int32x4 object + */ + (s0?: number, s1?: number, s2?: number, s3?: number): Int32x4; + + prototype: Int32x4; + + /** + * Returns the value of the given lane. + * @param simd An instance of a corresponding SIMD type. + * @param lane An index number for which lane to extract. + * @return The value of the extracted lane. + */ + extractLane(simd: Int32x4, lane: number): number; + + /** + * Returns a new instance with the lane values swizzled. + * @param a + * @param l1 + * @param l2 + * @param l3 + * @param l4 + */ + swizzle(a: Int32x4, l1: number, l2: number, l3: number, l4: number): Int32x4; + + /** + * Returns a new instance with the lane values shuffled. + * @param a + * @param b + * @param l1 + * @param l2 + * @param l3 + * @param l4 + */ + shuffle(a: Int32x4, b: Int32x4, l1: number, l2: number, l3: number, l4: number): Int32x4; + + /** + * Returns a new instance if the parameter is a valid SIMD data type and the same as Int32x4. Throws a TypeError otherwise. + * @param a + */ + check(a: Int32x4): Int32x4; + + /** + * Creates a new SIMD.Int32x4 data type with all lanes set to a given value. + * @param n + */ + splat(n: number): Int32x4; + + /** + * Returns a new instance with the given lane value replaced. + * @param simd An instance of a corresponding SIMD type. + * @param lane + * @param value A new value to be used for the lane. + * @return A new SIMD data type with the given lane value replaced. + */ + replaceLane(simd: Int32x4, lane: number, value: number): Int32x4; + + /** + * Returns a new instance with the lane values being a mix of the lanes depending on the selector mask. + * @param selector the selector mask. + * @param a If the selector mask lane is `true`, pick the corresponding lane value from here. + * @param b If the selector mask lane is `false`, pick the corresponding lane value from here. + */ + select(selector: Bool32x4, a: Int32x4, b: Int32x4): Int32x4; + + equal(a: Int32x4, b: Int32x4): Bool32x4; + + notEqual(a: Int32x4, b: Int32x4): Bool32x4; + + lessThan(a: Int32x4, b: Int32x4): Bool32x4; + + lessThanOrEqual(a: Int32x4, b: Int32x4): Bool32x4; + + greaterThan(a: Int32x4, b: Int32x4): Bool32x4; + + greaterThanOrEqual(a: Int32x4, b: Int32x4): Bool32x4; + + and(a: Int32x4, b: Int32x4): Int32x4; + + or(a: Int32x4, b: Int32x4): Int32x4; + + xor(a: Int32x4, b: Int32x4): Int32x4; + + not(a: Int32x4, b: Int32x4): Int32x4; + + add(a: Int32x4, b: Int32x4): Int32x4; + + sub(a: Int32x4, b: Int32x4): Int32x4; + + mul(a: Int32x4, b: Int32x4): Int32x4; + + /** + * + * @param a + */ + neg(a: Int32x4): Int32x4; + + /** + * Returns a new instance with the lane values shifted left by a given bit count (`a << bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`). + */ + shiftLeftByScalar(a: Int32x4, bits: number): Int32x4; + + /** + * Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + */ + shiftRightByScalar(a: Int32x4, bits: number): Int32x4; + + /** + * Returns a new instance with all lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load(tarray: TypedArray, index: number): Int32x4; + + /** + * Returns a new instance with 1 lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load1(tarray: TypedArray, index: number): Int32x4; + + /** + * Returns a new instance with 2 lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load2(tarray: TypedArray, index: number): Int32x4; + + /** + * Returns a new instance with 3 lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load3(tarray: TypedArray, index: number): Int32x4; + + /** + * Store all values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store(tarray: TypedArray, index: number, value: Int32x4): Int32x4; + + /** + * Store 1 values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store1(tarray: TypedArray, index: number, value: Int32x4): Int32x4; + + /** + * Store 2 values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store2(tarray: TypedArray, index: number, value: Int32x4): Int32x4; + + /** + * Store 3 values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store3(tarray: TypedArray, index: number, value: Int32x4): Int32x4; + + /** + * Creates a new SIMD data type with a float conversion from a Float32x4. + * @param value An Float32x4 SIMD type to convert from. + */ + fromFloat32x4(value: Float32x4): Int32x4; + + /** + * Creates a new SIMD data type with a float conversion from a Uint32x4. + * @param value An Uint32x4 SIMD type to convert from. + */ + fromUint32x4(value: Uint32x4): Int32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Float32x4. + * @param value A Float32x4 SIMD type to convert from (bitwise). + */ + fromFloat32x4Bits(value: Float32x4): Int32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int16x8. + * @param value A Int16x8 SIMD type to convert from (bitwise). + */ + fromInt16x8Bits(value: Int16x8): Int32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int8x16. + * @param value A Int8x16 SIMD type to convert from (bitwise). + */ + fromInt8x16Bits(value: Int8x16): Int32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint32x4. + * @param value A Uint32x4 SIMD type to convert from (bitwise). + */ + fromUint32x4Bits(value: Uint32x4): Int32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint16x8. + * @param value A Uint16x8 SIMD type to convert from (bitwise). + */ + fromUint16x8Bits(value: Uint16x8): Int32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint8x16. + * @param value A Uint8x16 SIMD type to convert from (bitwise). + */ + fromUint8x16Bits(value: Uint8x16): Int32x4; + } + + /** + * 128-bits divided into 8 lanes storing 16-bit signed integer values. + */ + interface Int16x8 { + constructor: Int16x8Constructor; + valueOf(): Int16x8; + toLocaleString(): string; + toString(): string; + + /** + * The initial value of the @@toStringTag property is the String value "SIMD.Int16x8". + */ + [Symbol.toStringTag]: string; + [Symbol.toPrimitive](hint: "string"): string; + [Symbol.toPrimitive](hint: "number"): number; + [Symbol.toPrimitive](hint: "default"): Int16x8; + [Symbol.toPrimitive](hint: string): any; + } + + interface Int16x8Constructor { + /** + * SIMD.Int16x8 constructor + * @param s0 A 16bit int specifying the value of the lane. + * @param s1 A 16bit int specifying the value of the lane. + * @param s2 A 16bit int specifying the value of the lane. + * @param s3 A 16bit int specifying the value of the lane. + * @param s4 A 16bit int specifying the value of the lane. + * @param s5 A 16bit int specifying the value of the lane. + * @param s6 A 16bit int specifying the value of the lane. + * @param s7 A 16bit int specifying the value of the lane. + * @return SIMD.Int16x8 object + */ + (s0?: number, s1?: number, s2?: number, s3?: number, s4?: number, s5?: number, s6?: number, s7?: number): Int16x8; + + prototype: Int16x8; + + /** + * Returns the value of the given lane. + * @param simd An instance of a corresponding SIMD type. + * @param lane An index number for which lane to extract. + * @return The value of the extracted lane. + */ + extractLane(simd: Int16x8, lane: number): number; + + /** + * Returns a new instance with the lane values swizzled. + * @param a + * @param l1 + * @param l2 + * @param l3 + * @param l4 + * @param l5 + * @param l6 + * @param l7 + * @param l8 + */ + swizzle(a: Int16x8, l1: number, l2: number, l3: number, l4: number, l5: number, l6: number, l7: number, l8: number): Int16x8; + + /** + * Returns a new instance with the lane values shuffled. + * @param a + * @param b + * @param l1 + * @param l2 + * @param l3 + * @param l4 + * @param l5 + * @param l6 + * @param l7 + * @param l8 + */ + shuffle(a: Int16x8, b: Int16x8, l1: number, l2: number, l3: number, l4: number, l5: number, l6: number, l7: number, l8: number): Int16x8; + + /** + * Returns a new instance if the parameter is a valid SIMD data type and the same as Int16x8. Throws a TypeError otherwise. + * @param a + */ + check(a: Int16x8): Int16x8; + + /** + * Creates a new SIMD.Int16x8 data type with all lanes set to a given value. + * @param n + */ + splat(n: number): Int16x8; + + /** + * Returns a new instance with the given lane value replaced. + * @param simd An instance of a corresponding SIMD type. + * @param lane + * @param value A new value to be used for the lane. + * @return A new SIMD data type with the given lane value replaced. + */ + replaceLane(simd: Int16x8, lane: number, value: number): Int16x8; + + /** + * Returns a new instance with the lane values being a mix of the lanes depending on the selector mask. + * @param selector the selector mask. + * @param a If the selector mask lane is `true`, pick the corresponding lane value from here. + * @param b If the selector mask lane is `false`, pick the corresponding lane value from here. + */ + select(selector: Bool16x8, a: Int16x8, b: Int16x8): Int16x8; + + equal(a: Int16x8, b: Int16x8): Bool16x8; + + notEqual(a: Int16x8, b: Int16x8): Bool16x8; + + lessThan(a: Int16x8, b: Int16x8): Bool16x8; + + lessThanOrEqual(a: Int16x8, b: Int16x8): Bool16x8; + + greaterThan(a: Int16x8, b: Int16x8): Bool16x8; + + greaterThanOrEqual(a: Int16x8, b: Int16x8): Bool16x8; + + and(a: Int16x8, b: Int16x8): Int16x8; + + or(a: Int16x8, b: Int16x8): Int16x8; + + xor(a: Int16x8, b: Int16x8): Int16x8; + + not(a: Int16x8, b: Int16x8): Int16x8; + + add(a: Int16x8, b: Int16x8): Int16x8; + + sub(a: Int16x8, b: Int16x8): Int16x8; + + mul(a: Int16x8, b: Int16x8): Int16x8; + + /** + * + * @param a + */ + neg(a: Int16x8): Int16x8; + + /** + * Returns a new instance with the lane values shifted left by a given bit count (`a << bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`). + */ + shiftLeftByScalar(a: Int16x8, bits: number): Int16x8; + + /** + * Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + */ + shiftRightByScalar(a: Int16x8, bits: number): Int16x8; + + addSaturate(a: Int16x8, b: Int16x8): Int16x8; + + subSaturate(a: Int16x8, b: Int16x8): Int16x8; + + /** + * Returns a new instance with all lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load(tarray: TypedArray, index: number): Int16x8; + + /** + * Store all values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store(tarray: TypedArray, index: number, value: Int16x8): Int16x8; + + /** + * Creates a new SIMD data type with a float conversion from a Uint16x8. + * @param value An Uint16x8 SIMD type to convert from. + */ + fromUint16x8(value: Uint16x8): Int16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Float32x4. + * @param value A Float32x4 SIMD type to convert from (bitwise). + */ + fromFloat32x4Bits(value: Float32x4): Int16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int32x4. + * @param value A Int32x4 SIMD type to convert from (bitwise). + */ + fromInt32x4Bits(value: Int32x4): Int16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int8x16. + * @param value A Int8x16 SIMD type to convert from (bitwise). + */ + fromInt8x16Bits(value: Int8x16): Int16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint32x4. + * @param value A Uint32x4 SIMD type to convert from (bitwise). + */ + fromUint32x4Bits(value: Uint32x4): Int16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint16x8. + * @param value A Uint16x8 SIMD type to convert from (bitwise). + */ + fromUint16x8Bits(value: Uint16x8): Int16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint8x16. + * @param value A Uint8x16 SIMD type to convert from (bitwise). + */ + fromUint8x16Bits(value: Uint8x16): Int16x8; + } + + /** + * 128-bits divided into 16 lanes storing 8-bit signed integer values. + */ + interface Int8x16 { + constructor: Int8x16Constructor; + valueOf(): Int8x16; + toLocaleString(): string; + toString(): string; + + /** + * The initial value of the @@toStringTag property is the String value "SIMD.Int8x16". + */ + [Symbol.toStringTag]: string; + [Symbol.toPrimitive](hint: "string"): string; + [Symbol.toPrimitive](hint: "number"): number; + [Symbol.toPrimitive](hint: "default"): Int8x16; + [Symbol.toPrimitive](hint: string): any; + } + + interface Int8x16Constructor { + /** + * SIMD.Int8x16 constructor + * @param s0 A 8bit int specifying the value of the lane. + * @param s1 A 8bit int specifying the value of the lane. + * @param s2 A 8bit int specifying the value of the lane. + * @param s3 A 8bit int specifying the value of the lane. + * @param s4 A 8bit int specifying the value of the lane. + * @param s5 A 8bit int specifying the value of the lane. + * @param s6 A 8bit int specifying the value of the lane. + * @param s7 A 8bit int specifying the value of the lane. + * @param s8 A 8bit int specifying the value of the lane. + * @param s9 A 8bit int specifying the value of the lane. + * @param s10 A 8bit int specifying the value of the lane. + * @param s11 A 8bit int specifying the value of the lane. + * @param s12 A 8bit int specifying the value of the lane. + * @param s13 A 8bit int specifying the value of the lane. + * @param s14 A 8bit int specifying the value of the lane. + * @param s15 A 8bit int specifying the value of the lane. + * @return SIMD.Int8x16 object + */ + ( + s0?: number, + s1?: number, + s2?: number, + s3?: number, + s4?: number, + s5?: number, + s6?: number, + s7?: number, + s8?: number, + s9?: number, + s10?: number, + s11?: number, + s12?: number, + s13?: number, + s14?: number, + s15?: number + ): Int8x16; + + prototype: Int8x16; + + /** + * Returns the value of the given lane. + * @param simd An instance of a corresponding SIMD type. + * @param lane An index number for which lane to extract. + * @return The value of the extracted lane. + */ + extractLane(simd: Int8x16, lane: number): number; + + /** + * Returns a new instance with the lane values swizzled. + * @param a + * @param l1 + * @param l2 + * @param l3 + * @param l4 + * @param l5 + * @param l6 + * @param l7 + * @param l8 + * @param l9 + * @param l10 + * @param l11 + * @param l12 + * @param l13 + * @param l14 + * @param l15 + * @param l16 + */ + swizzle( + a: Int8x16, + l1: number, + l2: number, + l3: number, + l4: number, + l5: number, + l6: number, + l7: number, + l8: number, + l9: number, + l10: number, + l11: number, + l12: number, + l13: number, + l14: number, + l15: number, + l16: number + ): Int8x16; + + /** + * Returns a new instance with the lane values shuffled. + * @param a + * @param b + * @param l1 + * @param l2 + * @param l3 + * @param l4 + * @param l5 + * @param l6 + * @param l7 + * @param l8 + * @param l9 + * @param l10 + * @param l11 + * @param l12 + * @param l13 + * @param l14 + * @param l15 + * @param l16 + */ + shuffle( + a: Int8x16, + b: Int8x16, + l1: number, + l2: number, + l3: number, + l4: number, + l5: number, + l6: number, + l7: number, + l8: number, + l9: number, + l10: number, + l11: number, + l12: number, + l13: number, + l14: number, + l15: number, + l16: number + ): Int8x16; + + /** + * Returns a new instance if the parameter is a valid SIMD data type and the same as Int8x16. Throws a TypeError otherwise. + * @param a + */ + check(a: Int8x16): Int8x16; + + /** + * Creates a new SIMD.Int8x16 data type with all lanes set to a given value. + * @param n + */ + splat(n: number): Int8x16; + + /** + * Returns a new instance with the given lane value replaced. + * @param simd An instance of a corresponding SIMD type. + * @param lane + * @param value A new value to be used for the lane. + * @return A new SIMD data type with the given lane value replaced. + */ + replaceLane(simd: Int8x16, lane: number, value: number): Int8x16; + + /** + * Returns a new instance with the lane values being a mix of the lanes depending on the selector mask. + * @param selector the selector mask. + * @param a If the selector mask lane is `true`, pick the corresponding lane value from here. + * @param b If the selector mask lane is `false`, pick the corresponding lane value from here. + */ + select(selector: Bool8x16, a: Int8x16, b: Int8x16): Int8x16; + + equal(a: Int8x16, b: Int8x16): Bool8x16; + + notEqual(a: Int8x16, b: Int8x16): Bool8x16; + + lessThan(a: Int8x16, b: Int8x16): Bool8x16; + + lessThanOrEqual(a: Int8x16, b: Int8x16): Bool8x16; + + greaterThan(a: Int8x16, b: Int8x16): Bool8x16; + + greaterThanOrEqual(a: Int8x16, b: Int8x16): Bool8x16; + + and(a: Int8x16, b: Int8x16): Int8x16; + + or(a: Int8x16, b: Int8x16): Int8x16; + + xor(a: Int8x16, b: Int8x16): Int8x16; + + not(a: Int8x16, b: Int8x16): Int8x16; + + add(a: Int8x16, b: Int8x16): Int8x16; + + sub(a: Int8x16, b: Int8x16): Int8x16; + + mul(a: Int8x16, b: Int8x16): Int8x16; + + /** + * + * @param a + */ + neg(a: Int8x16): Int8x16; + + /** + * Returns a new instance with the lane values shifted left by a given bit count (`a << bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`). + */ + shiftLeftByScalar(a: Int8x16, bits: number): Int8x16; + + /** + * Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + */ + shiftRightByScalar(a: Int8x16, bits: number): Int8x16; + + addSaturate(a: Int8x16, b: Int8x16): Int8x16; + + subSaturate(a: Int8x16, b: Int8x16): Int8x16; + + /** + * Returns a new instance with all lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load(tarray: TypedArray, index: number): Int8x16; + + /** + * Store all values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store(tarray: TypedArray, index: number, value: Int8x16): Int8x16; + + /** + * Creates a new SIMD data type with a float conversion from a Uint8x16. + * @param value An Uint8x16 SIMD type to convert from. + */ + fromUint8x16(value: Uint8x16): Int8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Float32x4. + * @param value A Float32x4 SIMD type to convert from (bitwise). + */ + fromFloat32x4Bits(value: Float32x4): Int8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int32x4. + * @param value A Int32x4 SIMD type to convert from (bitwise). + */ + fromInt32x4Bits(value: Int32x4): Int8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int16x8. + * @param value A Int16x8 SIMD type to convert from (bitwise). + */ + fromInt16x8Bits(value: Int16x8): Int8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint32x4. + * @param value A Uint32x4 SIMD type to convert from (bitwise). + */ + fromUint32x4Bits(value: Uint32x4): Int8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint16x8. + * @param value A Uint16x8 SIMD type to convert from (bitwise). + */ + fromUint16x8Bits(value: Uint16x8): Int8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint8x16. + * @param value A Uint8x16 SIMD type to convert from (bitwise). + */ + fromUint8x16Bits(value: Uint8x16): Int8x16; + } + + /** + * 128-bits divided into 4 lanes storing 32-bit unsigned integer values. + */ + interface Uint32x4 { + constructor: Uint32x4Constructor; + valueOf(): Uint32x4; + toLocaleString(): string; + toString(): string; + + /** + * The initial value of the @@toStringTag property is the String value "SIMD.Uint32x4". + */ + [Symbol.toStringTag]: string; + [Symbol.toPrimitive](hint: "string"): string; + [Symbol.toPrimitive](hint: "number"): number; + [Symbol.toPrimitive](hint: "default"): Uint32x4; + [Symbol.toPrimitive](hint: string): any; + } + + interface Uint32x4Constructor { + /** + * SIMD.Uint32x4 constructor + * @param s0 A 32bit uint specifying the value of the lane. + * @param s1 A 32bit uint specifying the value of the lane. + * @param s2 A 32bit uint specifying the value of the lane. + * @param s3 A 32bit uint specifying the value of the lane. + * @return SIMD.Uint32x4 object + */ + (s0?: number, s1?: number, s2?: number, s3?: number): Uint32x4; + + prototype: Uint32x4; + + /** + * Returns the value of the given lane. + * @param simd An instance of a corresponding SIMD type. + * @param lane An index number for which lane to extract. + * @return The value of the extracted lane. + */ + extractLane(simd: Uint32x4, lane: number): number; + + /** + * Returns a new instance with the lane values swizzled. + * @param a + * @param l1 + * @param l2 + * @param l3 + * @param l4 + */ + swizzle(a: Uint32x4, l1: number, l2: number, l3: number, l4: number): Uint32x4; + + /** + * Returns a new instance with the lane values shuffled. + * @param a + * @param b + * @param l1 + * @param l2 + * @param l3 + * @param l4 + */ + shuffle(a: Uint32x4, b: Uint32x4, l1: number, l2: number, l3: number, l4: number): Uint32x4; + + /** + * Returns a new instance if the parameter is a valid SIMD data type and the same as Uint32x4. Throws a TypeError otherwise. + * @param a + */ + check(a: Uint32x4): Uint32x4; + + /** + * Creates a new SIMD.Uint32x4 data type with all lanes set to a given value. + * @param n + */ + splat(n: number): Uint32x4; + + /** + * Returns a new instance with the given lane value replaced. + * @param simd An instance of a corresponding SIMD type. + * @param lane + * @param value A new value to be used for the lane. + * @return A new SIMD data type with the given lane value replaced. + */ + replaceLane(simd: Uint32x4, lane: number, value: number): Uint32x4; + + /** + * Returns a new instance with the lane values being a mix of the lanes depending on the selector mask. + * @param selector the selector mask. + * @param a If the selector mask lane is `true`, pick the corresponding lane value from here. + * @param b If the selector mask lane is `false`, pick the corresponding lane value from here. + */ + select(selector: Bool32x4, a: Uint32x4, b: Uint32x4): Uint32x4; + + equal(a: Uint32x4, b: Uint32x4): Bool32x4; + + notEqual(a: Uint32x4, b: Uint32x4): Bool32x4; + + lessThan(a: Uint32x4, b: Uint32x4): Bool32x4; + + lessThanOrEqual(a: Uint32x4, b: Uint32x4): Bool32x4; + + greaterThan(a: Uint32x4, b: Uint32x4): Bool32x4; + + greaterThanOrEqual(a: Uint32x4, b: Uint32x4): Bool32x4; + + and(a: Uint32x4, b: Uint32x4): Uint32x4; + + or(a: Uint32x4, b: Uint32x4): Uint32x4; + + xor(a: Uint32x4, b: Uint32x4): Uint32x4; + + not(a: Uint32x4, b: Uint32x4): Uint32x4; + + add(a: Uint32x4, b: Uint32x4): Uint32x4; + + sub(a: Uint32x4, b: Uint32x4): Uint32x4; + + mul(a: Uint32x4, b: Uint32x4): Uint32x4; + + /** + * Returns a new instance with the lane values shifted left by a given bit count (`a << bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`). + */ + shiftLeftByScalar(a: Uint32x4, bits: number): Uint32x4; + + /** + * Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + */ + shiftRightByScalar(a: Uint32x4, bits: number): Uint32x4; + + /** + * Returns a new instance with all lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load(tarray: TypedArray, index: number): Uint32x4; + + /** + * Returns a new instance with 1 lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load1(tarray: TypedArray, index: number): Uint32x4; + + /** + * Returns a new instance with 2 lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load2(tarray: TypedArray, index: number): Uint32x4; + + /** + * Returns a new instance with 3 lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load3(tarray: TypedArray, index: number): Uint32x4; + + /** + * Store all values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store(tarray: TypedArray, index: number, value: Uint32x4): Uint32x4; + + /** + * Store 1 values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store1(tarray: TypedArray, index: number, value: Uint32x4): Uint32x4; + + /** + * Store 2 values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store2(tarray: TypedArray, index: number, value: Uint32x4): Uint32x4; + + /** + * Store 3 values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store3(tarray: TypedArray, index: number, value: Uint32x4): Uint32x4; + + /** + * Creates a new SIMD data type with a float conversion from a Float32x4. + * @param value An Float32x4 SIMD type to convert from. + */ + fromFloat32x4(value: Float32x4): Uint32x4; + + /** + * Creates a new SIMD data type with a float conversion from a Int32x4. + * @param value An Int32x4 SIMD type to convert from. + */ + fromInt32x4(value: Int32x4): Uint32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Float32x4. + * @param value A Float32x4 SIMD type to convert from (bitwise). + */ + fromFloat32x4Bits(value: Float32x4): Uint32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int32x4. + * @param value A Int32x4 SIMD type to convert from (bitwise). + */ + fromInt32x4Bits(value: Int32x4): Uint32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int16x8. + * @param value A Int16x8 SIMD type to convert from (bitwise). + */ + fromInt16x8Bits(value: Int16x8): Uint32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int8x16. + * @param value A Int8x16 SIMD type to convert from (bitwise). + */ + fromInt8x16Bits(value: Int8x16): Uint32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint16x8. + * @param value A Uint16x8 SIMD type to convert from (bitwise). + */ + fromUint16x8Bits(value: Uint16x8): Uint32x4; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint8x16. + * @param value A Uint8x16 SIMD type to convert from (bitwise). + */ + fromUint8x16Bits(value: Uint8x16): Uint32x4; + } + + /** + * 128-bits divided into 8 lanes storing 16-bit unsigned integer values. + */ + interface Uint16x8 { + constructor: Uint16x8Constructor; + valueOf(): Uint16x8; + toLocaleString(): string; + toString(): string; + + /** + * The initial value of the @@toStringTag property is the String value "SIMD.Uint16x8". + */ + [Symbol.toStringTag]: string; + [Symbol.toPrimitive](hint: "string"): string; + [Symbol.toPrimitive](hint: "number"): number; + [Symbol.toPrimitive](hint: "default"): Uint16x8; + [Symbol.toPrimitive](hint: string): any; + } + + interface Uint16x8Constructor { + /** + * SIMD.Uint16x8 constructor + * @param s0 A 16bit uint specifying the value of the lane. + * @param s1 A 16bit uint specifying the value of the lane. + * @param s2 A 16bit uint specifying the value of the lane. + * @param s3 A 16bit uint specifying the value of the lane. + * @param s4 A 16bit uint specifying the value of the lane. + * @param s5 A 16bit uint specifying the value of the lane. + * @param s6 A 16bit uint specifying the value of the lane. + * @param s7 A 16bit uint specifying the value of the lane. + * @return SIMD.Uint16x8 object + */ + (s0?: number, s1?: number, s2?: number, s3?: number, s4?: number, s5?: number, s6?: number, s7?: number): Uint16x8; + + prototype: Uint16x8; + + /** + * Returns the value of the given lane. + * @param simd An instance of a corresponding SIMD type. + * @param lane An index number for which lane to extract. + * @return The value of the extracted lane. + */ + extractLane(simd: Uint16x8, lane: number): number; + + /** + * Returns a new instance with the lane values swizzled. + * @param a + * @param l1 + * @param l2 + * @param l3 + * @param l4 + * @param l5 + * @param l6 + * @param l7 + * @param l8 + */ + swizzle(a: Uint16x8, l1: number, l2: number, l3: number, l4: number, l5: number, l6: number, l7: number, l8: number): Uint16x8; + + /** + * Returns a new instance with the lane values shuffled. + * @param a + * @param b + * @param l1 + * @param l2 + * @param l3 + * @param l4 + * @param l5 + * @param l6 + * @param l7 + * @param l8 + */ + shuffle(a: Uint16x8, b: Uint16x8, l1: number, l2: number, l3: number, l4: number, l5: number, l6: number, l7: number, l8: number): Uint16x8; + + /** + * Returns a new instance if the parameter is a valid SIMD data type and the same as Uint16x8. Throws a TypeError otherwise. + * @param a + */ + check(a: Uint16x8): Uint16x8; + + /** + * Creates a new SIMD.Uint16x8 data type with all lanes set to a given value. + * @param n + */ + splat(n: number): Uint16x8; + + /** + * Returns a new instance with the given lane value replaced. + * @param simd An instance of a corresponding SIMD type. + * @param lane + * @param value A new value to be used for the lane. + * @return A new SIMD data type with the given lane value replaced. + */ + replaceLane(simd: Uint16x8, lane: number, value: number): Uint16x8; + + /** + * Returns a new instance with the lane values being a mix of the lanes depending on the selector mask. + * @param selector the selector mask. + * @param a If the selector mask lane is `true`, pick the corresponding lane value from here. + * @param b If the selector mask lane is `false`, pick the corresponding lane value from here. + */ + select(selector: Bool16x8, a: Uint16x8, b: Uint16x8): Uint16x8; + + equal(a: Uint16x8, b: Uint16x8): Bool16x8; + + notEqual(a: Uint16x8, b: Uint16x8): Bool16x8; + + lessThan(a: Uint16x8, b: Uint16x8): Bool16x8; + + lessThanOrEqual(a: Uint16x8, b: Uint16x8): Bool16x8; + + greaterThan(a: Uint16x8, b: Uint16x8): Bool16x8; + + greaterThanOrEqual(a: Uint16x8, b: Uint16x8): Bool16x8; + + and(a: Uint16x8, b: Uint16x8): Uint16x8; + + or(a: Uint16x8, b: Uint16x8): Uint16x8; + + xor(a: Uint16x8, b: Uint16x8): Uint16x8; + + not(a: Uint16x8, b: Uint16x8): Uint16x8; + + add(a: Uint16x8, b: Uint16x8): Uint16x8; + + sub(a: Uint16x8, b: Uint16x8): Uint16x8; + + mul(a: Uint16x8, b: Uint16x8): Uint16x8; + + /** + * Returns a new instance with the lane values shifted left by a given bit count (`a << bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`). + */ + shiftLeftByScalar(a: Uint16x8, bits: number): Uint16x8; + + /** + * Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + */ + shiftRightByScalar(a: Uint16x8, bits: number): Uint16x8; + + addSaturate(a: Uint16x8, b: Uint16x8): Uint16x8; + + subSaturate(a: Uint16x8, b: Uint16x8): Uint16x8; + + /** + * Returns a new instance with all lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load(tarray: TypedArray, index: number): Uint16x8; + + /** + * Store all values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store(tarray: TypedArray, index: number, value: Uint16x8): Uint16x8; + + /** + * Creates a new SIMD data type with a float conversion from a Int16x8. + * @param value An Int16x8 SIMD type to convert from. + */ + fromInt16x8(value: Int16x8): Uint16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Float32x4. + * @param value A Float32x4 SIMD type to convert from (bitwise). + */ + fromFloat32x4Bits(value: Float32x4): Uint16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int32x4. + * @param value A Int32x4 SIMD type to convert from (bitwise). + */ + fromInt32x4Bits(value: Int32x4): Uint16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int16x8. + * @param value A Int16x8 SIMD type to convert from (bitwise). + */ + fromInt16x8Bits(value: Int16x8): Uint16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int8x16. + * @param value A Int8x16 SIMD type to convert from (bitwise). + */ + fromInt8x16Bits(value: Int8x16): Uint16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint32x4. + * @param value A Uint32x4 SIMD type to convert from (bitwise). + */ + fromUint32x4Bits(value: Uint32x4): Uint16x8; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint8x16. + * @param value A Uint8x16 SIMD type to convert from (bitwise). + */ + fromUint8x16Bits(value: Uint8x16): Uint16x8; + } + + /** + * 128-bits divided into 16 lanes storing 8-bit unsigned integer values. + */ + interface Uint8x16 { + constructor: Uint8x16Constructor; + valueOf(): Uint8x16; + toLocaleString(): string; + toString(): string; + + /** + * The initial value of the @@toStringTag property is the String value "SIMD.Uint8x16". + */ + [Symbol.toStringTag]: string; + [Symbol.toPrimitive](hint: "string"): string; + [Symbol.toPrimitive](hint: "number"): number; + [Symbol.toPrimitive](hint: "default"): Uint8x16; + [Symbol.toPrimitive](hint: string): any; + } + + interface Uint8x16Constructor { + /** + * SIMD.Uint8x16 constructor + * @param s0 A 8bit uint specifying the value of the lane. + * @param s1 A 8bit uint specifying the value of the lane. + * @param s2 A 8bit uint specifying the value of the lane. + * @param s3 A 8bit uint specifying the value of the lane. + * @param s4 A 8bit uint specifying the value of the lane. + * @param s5 A 8bit uint specifying the value of the lane. + * @param s6 A 8bit uint specifying the value of the lane. + * @param s7 A 8bit uint specifying the value of the lane. + * @param s8 A 8bit uint specifying the value of the lane. + * @param s9 A 8bit uint specifying the value of the lane. + * @param s10 A 8bit uint specifying the value of the lane. + * @param s11 A 8bit uint specifying the value of the lane. + * @param s12 A 8bit uint specifying the value of the lane. + * @param s13 A 8bit uint specifying the value of the lane. + * @param s14 A 8bit uint specifying the value of the lane. + * @param s15 A 8bit uint specifying the value of the lane. + * @return SIMD.Uint8x16 object + */ + ( + s0?: number, + s1?: number, + s2?: number, + s3?: number, + s4?: number, + s5?: number, + s6?: number, + s7?: number, + s8?: number, + s9?: number, + s10?: number, + s11?: number, + s12?: number, + s13?: number, + s14?: number, + s15?: number + ): Uint8x16; + + prototype: Uint8x16; + + /** + * Returns the value of the given lane. + * @param simd An instance of a corresponding SIMD type. + * @param lane An index number for which lane to extract. + * @return The value of the extracted lane. + */ + extractLane(simd: Uint8x16, lane: number): number; + + /** + * Returns a new instance with the lane values swizzled. + * @param a + * @param l1 + * @param l2 + * @param l3 + * @param l4 + * @param l5 + * @param l6 + * @param l7 + * @param l8 + * @param l9 + * @param l10 + * @param l11 + * @param l12 + * @param l13 + * @param l14 + * @param l15 + * @param l16 + */ + swizzle( + a: Uint8x16, + l1: number, + l2: number, + l3: number, + l4: number, + l5: number, + l6: number, + l7: number, + l8: number, + l9: number, + l10: number, + l11: number, + l12: number, + l13: number, + l14: number, + l15: number, + l16: number + ): Uint8x16; + + /** + * Returns a new instance with the lane values shuffled. + * @param a + * @param b + * @param l1 + * @param l2 + * @param l3 + * @param l4 + * @param l5 + * @param l6 + * @param l7 + * @param l8 + * @param l9 + * @param l10 + * @param l11 + * @param l12 + * @param l13 + * @param l14 + * @param l15 + * @param l16 + */ + shuffle( + a: Uint8x16, + b: Uint8x16, + l1: number, + l2: number, + l3: number, + l4: number, + l5: number, + l6: number, + l7: number, + l8: number, + l9: number, + l10: number, + l11: number, + l12: number, + l13: number, + l14: number, + l15: number, + l16: number + ): Uint8x16; + + /** + * Returns a new instance if the parameter is a valid SIMD data type and the same as Uint8x16. Throws a TypeError otherwise. + * @param a + */ + check(a: Uint8x16): Uint8x16; + + /** + * Creates a new SIMD.Uint8x16 data type with all lanes set to a given value. + * @param n + */ + splat(n: number): Uint8x16; + + /** + * Returns a new instance with the given lane value replaced. + * @param simd An instance of a corresponding SIMD type. + * @param lane + * @param value A new value to be used for the lane. + * @return A new SIMD data type with the given lane value replaced. + */ + replaceLane(simd: Uint8x16, lane: number, value: number): Uint8x16; + + /** + * Returns a new instance with the lane values being a mix of the lanes depending on the selector mask. + * @param selector the selector mask. + * @param a If the selector mask lane is `true`, pick the corresponding lane value from here. + * @param b If the selector mask lane is `false`, pick the corresponding lane value from here. + */ + select(selector: Bool8x16, a: Uint8x16, b: Uint8x16): Uint8x16; + + equal(a: Uint8x16, b: Uint8x16): Bool8x16; + + notEqual(a: Uint8x16, b: Uint8x16): Bool8x16; + + lessThan(a: Uint8x16, b: Uint8x16): Bool8x16; + + lessThanOrEqual(a: Uint8x16, b: Uint8x16): Bool8x16; + + greaterThan(a: Uint8x16, b: Uint8x16): Bool8x16; + + greaterThanOrEqual(a: Uint8x16, b: Uint8x16): Bool8x16; + + and(a: Uint8x16, b: Uint8x16): Uint8x16; + + or(a: Uint8x16, b: Uint8x16): Uint8x16; + + xor(a: Uint8x16, b: Uint8x16): Uint8x16; + + not(a: Uint8x16, b: Uint8x16): Uint8x16; + + add(a: Uint8x16, b: Uint8x16): Uint8x16; + + sub(a: Uint8x16, b: Uint8x16): Uint8x16; + + mul(a: Uint8x16, b: Uint8x16): Uint8x16; + + /** + * Returns a new instance with the lane values shifted left by a given bit count (`a << bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`). + */ + shiftLeftByScalar(a: Uint8x16, bits: number): Uint8x16; + + /** + * Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + * @param a An instance of a SIMD type. + * @param bits Bit count to shift by. + * @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`). + */ + shiftRightByScalar(a: Uint8x16, bits: number): Uint8x16; + + addSaturate(a: Uint8x16, b: Uint8x16): Uint8x16; + + subSaturate(a: Uint8x16, b: Uint8x16): Uint8x16; + + /** + * Returns a new instance with all lane values loaded from a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start loading in the typed array. + */ + load(tarray: TypedArray, index: number): Uint8x16; + + /** + * Store all values of a SIMD data type into a typed array. + * @param tarray An instance of a typed array. + * @param index A number for the index from where to start storing in the typed array. + * @param value An instance of a SIMD data type to store into the typed array. + * @return The value that has been stored (a SIMD data type). + */ + store(tarray: TypedArray, index: number, value: Uint8x16): Uint8x16; + + /** + * Creates a new SIMD data type with a float conversion from a Int8x16. + * @param value An Int8x16 SIMD type to convert from. + */ + fromInt8x16(value: Int8x16): Uint8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Float32x4. + * @param value A Float32x4 SIMD type to convert from (bitwise). + */ + fromFloat32x4Bits(value: Float32x4): Uint8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int32x4. + * @param value A Int32x4 SIMD type to convert from (bitwise). + */ + fromInt32x4Bits(value: Int32x4): Uint8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int16x8. + * @param value A Int16x8 SIMD type to convert from (bitwise). + */ + fromInt16x8Bits(value: Int16x8): Uint8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Int8x16. + * @param value A Int8x16 SIMD type to convert from (bitwise). + */ + fromInt8x16Bits(value: Int8x16): Uint8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint32x4. + * @param value A Uint32x4 SIMD type to convert from (bitwise). + */ + fromUint32x4Bits(value: Uint32x4): Uint8x16; + + /** + * Creates a new SIMD data type with a bit-wise copy from a Uint16x8. + * @param value A Uint16x8 SIMD type to convert from (bitwise). + */ + fromUint16x8Bits(value: Uint16x8): Uint8x16; + } + + /** + * A SIMD type representing 4 boolean values, as an intermediate value in manipulating 128-bit vectors. + */ + interface Bool32x4 { + constructor: Bool32x4Constructor; + valueOf(): Bool32x4; + toLocaleString(): string; + toString(): string; + + /** + * The initial value of the @@toStringTag property is the String value "SIMD.Bool32x4". + */ + [Symbol.toStringTag]: string; + [Symbol.toPrimitive](hint: "string"): string; + [Symbol.toPrimitive](hint: "number"): number; + [Symbol.toPrimitive](hint: "default"): Bool32x4; + [Symbol.toPrimitive](hint: string): any; + } + + interface Bool32x4Constructor { + /** + * SIMD.Bool32x4 constructor + * @param s0 A 32bit bool specifying the value of the lane. + * @param s1 A 32bit bool specifying the value of the lane. + * @param s2 A 32bit bool specifying the value of the lane. + * @param s3 A 32bit bool specifying the value of the lane. + * @return SIMD.Bool32x4 object + */ + (s0?: boolean, s1?: boolean, s2?: boolean, s3?: boolean): Bool32x4; + + prototype: Bool32x4; + + /** + * Returns the value of the given lane. + * @param simd An instance of a corresponding SIMD type. + * @param lane An index number for which lane to extract. + * @return The value of the extracted lane. + */ + extractLane(simd: Bool32x4, lane: number): boolean; + + /** + * Returns a new instance if the parameter is a valid SIMD data type and the same as Bool32x4. Throws a TypeError otherwise. + * @param a + */ + check(a: Bool32x4): Bool32x4; + + /** + * Creates a new SIMD.Bool32x4 data type with all lanes set to a given value. + * @param n + */ + splat(n: boolean): Bool32x4; + + /** + * Returns a new instance with the given lane value replaced. + * @param simd An instance of a corresponding SIMD type. + * @param lane + * @param value A new value to be used for the lane. + * @return A new SIMD data type with the given lane value replaced. + */ + replaceLane(simd: Bool32x4, lane: number, value: boolean): Bool32x4; + + /** + * If all lane values are `true`, return `true`. + * @param a + */ + allTrue(a: Bool32x4): boolean; + + /** + * If any lane values are `true`, return `true`. + * @param a + */ + anyTrue(a: Bool32x4): boolean; + + and(a: Bool32x4, b: Bool32x4): Bool32x4; + + or(a: Bool32x4, b: Bool32x4): Bool32x4; + + xor(a: Bool32x4, b: Bool32x4): Bool32x4; + + not(a: Bool32x4, b: Bool32x4): Bool32x4; + } + + /** + * A SIMD type representing 16 boolean values, as an intermediate value in manipulating 128-bit vectors + */ + interface Bool16x8 { + constructor: Bool16x8Constructor; + valueOf(): Bool16x8; + toLocaleString(): string; + toString(): string; + + /** + * The initial value of the @@toStringTag property is the String value "SIMD.Bool16x8". + */ + [Symbol.toStringTag]: string; + [Symbol.toPrimitive](hint: "string"): string; + [Symbol.toPrimitive](hint: "number"): number; + [Symbol.toPrimitive](hint: "default"): Bool16x8; + [Symbol.toPrimitive](hint: string): any; + } + + interface Bool16x8Constructor { + /** + * SIMD.Bool16x8 constructor + * @param s0 A 16bit bool specifying the value of the lane. + * @param s1 A 16bit bool specifying the value of the lane. + * @param s2 A 16bit bool specifying the value of the lane. + * @param s3 A 16bit bool specifying the value of the lane. + * @param s4 A 16bit bool specifying the value of the lane. + * @param s5 A 16bit bool specifying the value of the lane. + * @param s6 A 16bit bool specifying the value of the lane. + * @param s7 A 16bit bool specifying the value of the lane. + * @return SIMD.Bool16x8 object + */ + (s0?: boolean, s1?: boolean, s2?: boolean, s3?: boolean, s4?: boolean, s5?: boolean, s6?: boolean, s7?: boolean): Bool16x8; + + prototype: Bool16x8; + + /** + * Returns the value of the given lane. + * @param simd An instance of a corresponding SIMD type. + * @param lane An index number for which lane to extract. + * @return The value of the extracted lane. + */ + extractLane(simd: Bool16x8, lane: number): boolean; + + /** + * Returns a new instance if the parameter is a valid SIMD data type and the same as Bool16x8. Throws a TypeError otherwise. + * @param a + */ + check(a: Bool16x8): Bool16x8; + + /** + * Creates a new SIMD.Bool16x8 data type with all lanes set to a given value. + * @param n + */ + splat(n: boolean): Bool16x8; + + /** + * Returns a new instance with the given lane value replaced. + * @param simd An instance of a corresponding SIMD type. + * @param lane + * @param value A new value to be used for the lane. + * @return A new SIMD data type with the given lane value replaced. + */ + replaceLane(simd: Bool16x8, lane: number, value: boolean): Bool16x8; + + /** + * If all lane values are `true`, return `true`. + * @param a + */ + allTrue(a: Bool16x8): boolean; + + /** + * If any lane values are `true`, return `true`. + * @param a + */ + anyTrue(a: Bool16x8): boolean; + + and(a: Bool16x8, b: Bool16x8): Bool16x8; + + or(a: Bool16x8, b: Bool16x8): Bool16x8; + + xor(a: Bool16x8, b: Bool16x8): Bool16x8; + + not(a: Bool16x8, b: Bool16x8): Bool16x8; + } + + /** + * A SIMD type representing 8 boolean values, as an intermediate value in manipulating 128-bit vectors + */ + interface Bool8x16 { + constructor: Bool8x16Constructor; + valueOf(): Bool8x16; + toLocaleString(): string; + toString(): string; + + /** + * The initial value of the @@toStringTag property is the String value "SIMD.Bool8x16". + */ + [Symbol.toStringTag]: string; + [Symbol.toPrimitive](hint: "string"): string; + [Symbol.toPrimitive](hint: "number"): number; + [Symbol.toPrimitive](hint: "default"): Bool8x16; + [Symbol.toPrimitive](hint: string): any; + } + + interface Bool8x16Constructor { + /** + * SIMD.Bool8x16 constructor + * @param s0 A 8bit bool specifying the value of the lane. + * @param s1 A 8bit bool specifying the value of the lane. + * @param s2 A 8bit bool specifying the value of the lane. + * @param s3 A 8bit bool specifying the value of the lane. + * @param s4 A 8bit bool specifying the value of the lane. + * @param s5 A 8bit bool specifying the value of the lane. + * @param s6 A 8bit bool specifying the value of the lane. + * @param s7 A 8bit bool specifying the value of the lane. + * @param s8 A 8bit bool specifying the value of the lane. + * @param s9 A 8bit bool specifying the value of the lane. + * @param s10 A 8bit bool specifying the value of the lane. + * @param s11 A 8bit bool specifying the value of the lane. + * @param s12 A 8bit bool specifying the value of the lane. + * @param s13 A 8bit bool specifying the value of the lane. + * @param s14 A 8bit bool specifying the value of the lane. + * @param s15 A 8bit bool specifying the value of the lane. + * @return SIMD.Bool8x16 object + */ + ( + s0?: boolean, s1?: boolean, + s2?: boolean, + s3?: boolean, + s4?: boolean, + s5?: boolean, + s6?: boolean, + s7?: boolean, + s8?: boolean, + s9?: boolean, + s10?: boolean, + s11?: boolean, + s12?: boolean, + s13?: boolean, + s14?: boolean, + s15?: boolean + ): Bool8x16; + + prototype: Bool8x16; + + /** + * Returns the value of the given lane. + * @param simd An instance of a corresponding SIMD type. + * @param lane An index number for which lane to extract. + * @return The value of the extracted lane. + */ + extractLane(simd: Bool8x16, lane: number): boolean; + + /** + * Returns a new instance if the parameter is a valid SIMD data type and the same as Bool8x16. Throws a TypeError otherwise. + * @param a + */ + check(a: Bool8x16): Bool8x16; + + /** + * Creates a new SIMD.Bool8x16 data type with all lanes set to a given value. + * @param n + */ + splat(n: boolean): Bool8x16; + + /** + * Returns a new instance with the given lane value replaced. + * @param simd An instance of a corresponding SIMD type. + * @param lane + * @param value A new value to be used for the lane. + * @return A new SIMD data type with the given lane value replaced. + */ + replaceLane(simd: Bool8x16, lane: number, value: boolean): Bool8x16; + + /** + * If all lane values are `true`, return `true`. + * @param a + */ + allTrue(a: Bool8x16): boolean; + + /** + * If any lane values are `true`, return `true`. + * @param a + */ + anyTrue(a: Bool8x16): boolean; + + and(a: Bool8x16, b: Bool8x16): Bool8x16; + + or(a: Bool8x16, b: Bool8x16): Bool8x16; + + xor(a: Bool8x16, b: Bool8x16): Bool8x16; + + not(a: Bool8x16, b: Bool8x16): Bool8x16; + } + } + + const Float32x4: I.Float32x4Constructor; + const Int32x4: I.Int32x4Constructor; + const Int16x8: I.Int16x8Constructor; + const Int8x16: I.Int8x16Constructor; + const Uint32x4: I.Uint32x4Constructor; + const Uint16x8: I.Uint16x8Constructor; + const Uint8x16: I.Uint8x16Constructor; + const Bool32x4: I.Bool32x4Constructor; + const Bool16x8: I.Bool16x8Constructor; + const Bool8x16: I.Bool8x16Constructor; + } +} diff --git a/types/adone/glosses/promise.d.ts b/types/adone/glosses/promise.d.ts index a5267c69a3..d0f59b0340 100644 --- a/types/adone/glosses/promise.d.ts +++ b/types/adone/glosses/promise.d.ts @@ -1,114 +1,129 @@ -/** - * promise helpers - */ -export namespace promise { - namespace I { - interface Deferred { - /** - * Resolves the promise - */ - resolve(value?: T): void; +declare namespace adone { + /** + * promise helpers + */ + namespace promise { + namespace I { + interface Deferred { + /** + * Resolves the promise + */ + resolve(value?: T): void; - /** - * Rejects the promise - */ - reject(value?: any): void; + /** + * Rejects the promise + */ + reject(value?: any): void; - promise: Promise; + promise: Promise; + } } - } - /** - * Creates a promise and returns an interface to control the state - */ - export function defer(): I.Deferred; + /** + * Creates a promise and returns an interface to control the state + */ + export function defer(): I.Deferred; - /** - * Creates a promise that will be resolved after given milliseconds - * - * @param ms delay in milliseconds - * @param value resolving value - */ - export function delay(ms: number, value?: T): Promise; + /** + * Creates a promise that will be resolved after given milliseconds + * + * @param ms delay in milliseconds + * @param value resolving value + */ + export function delay(ms: number, value?: T): Promise; - /** - * Creates a promise that will be rejected after given milliseconds if the given promise is not fulfilled - * - * @param ms timeout in milliseconds - */ - export function timeout(promise: Promise, ms: number): Promise; + /** + * Creates a promise that will be rejected after given milliseconds if the given promise is not fulfilled + * + * @param ms timeout in milliseconds + */ + export function timeout(promise: Promise, ms: number): Promise; - /** - * Converts a promise to node.js style callback - */ - export function nodeify(promise: Promise, callback: (err?: any, value?: T) => void): Promise; + /** + * Converts a promise to node.js style callback + */ + export function nodeify(promise: Promise, callback: (err?: any, value?: T) => void): Promise; - namespace I { - interface PromisifyOptions { - /** - * Context to bind to new function - */ - context?: object; + /** + * Converts a function that returns promises to a node.js style callback function + * + * @param {Function} fn Function + * @returns {Promise} the original promise + */ + export function callbackify(fn: () => Promise): (callback: (err?: any, result?: R) => void) => Promise; + export function callbackify(fn: (a: T) => Promise): (a: T, callback: (err?: any, result?: R) => void) => Promise; + export function callbackify(fn: (a: T1, b: T2) => Promise): (a: T1, b: T2, callback: (err?: any, result?: R) => void) => Promise; + export function callbackify(fn: (a: T1, b: T2, c: T3) => Promise): (a: T1, b: T2, c: T3, callback: (err?: any, result?: R) => void) => Promise; + export function callbackify(fn: (a: T1, b: T2, c: T3, d: T4) => Promise): (a: T1, b: T2, c: T3, d: T4, callback: (err?: any, result?: R) => void) => Promise; + export function callbackify(fn: (...args: any[]) => Promise): (...args: any[]) => Promise; + + namespace I { + interface PromisifyOptions { + /** + * Context to bind to new function + */ + context?: object; + } } - } - /** - * Converts a callback function to a promise-based function - */ - export function promisify(fn: (callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): () => Promise; - export function promisify(fn: (a: T, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise; - export function promisify(fn: (a: T, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise; - export function promisify(fn: (a: T1, b: T2, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise; - export function promisify(fn: (a: T1, b: T2, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise; - export function promisify(fn: (a: T1, b: T2, c: T3, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise; - export function promisify(fn: (a: T1, b: T2, c: T3, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise; - export function promisify( - fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any, result?: R) => void) => void, - options?: I.PromisifyOptions - ): (a: T1, b: T2, c: T3, d: T4) => Promise; - export function promisify( - fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any) => void) => void, - options?: I.PromisifyOptions - ): (a: T1, b: T2, c: T3, d: T4) => Promise; - export function promisify( - fn: (a: T1, b: T2, c: T3, d: T4, e: T5, callback: (err?: any, result?: R) => void) => void, - options?: I.PromisifyOptions - ): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; - export function promisify( - fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any) => void) => void, - options?: I.PromisifyOptions - ): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; - export function promisify(fn: (...args: any[]) => void, options?: I.PromisifyOptions): (...args: any[]) => Promise; + /** + * Converts a callback function to a promise-based function + */ + export function promisify(fn: (callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): () => Promise; + export function promisify(fn: (a: T, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise; + export function promisify(fn: (a: T, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise; + export function promisify(fn: (a: T1, b: T2, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise; + export function promisify(fn: (a: T1, b: T2, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise; + export function promisify(fn: (a: T1, b: T2, c: T3, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise; + export function promisify(fn: (a: T1, b: T2, c: T3, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise; + export function promisify( + fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any, result?: R) => void) => void, + options?: I.PromisifyOptions + ): (a: T1, b: T2, c: T3, d: T4) => Promise; + export function promisify( + fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any) => void) => void, + options?: I.PromisifyOptions + ): (a: T1, b: T2, c: T3, d: T4) => Promise; + export function promisify( + fn: (a: T1, b: T2, c: T3, d: T4, e: T5, callback: (err?: any, result?: R) => void) => void, + options?: I.PromisifyOptions + ): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; + export function promisify( + fn: (a: T1, b: T2, c: T3, d: T4, e: T5, callback: (err?: any) => void) => void, + options?: I.PromisifyOptions + ): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; + export function promisify(fn: (...args: any[]) => void, options?: I.PromisifyOptions): (...args: any[]) => Promise; - namespace I { - interface PromisifyAllOptions { - /** - * Suffix to use for keys - */ - suffix?: string; + namespace I { + interface PromisifyAllOptions { + /** + * Suffix to use for keys + */ + suffix?: string; - /** - * Function to filter keys - */ + /** + * Function to filter keys + */ - filter?(key: string): boolean; - /** - * Context to bind to new functions - */ - context?: object; + filter?(key: string): boolean; + /** + * Context to bind to new functions + */ + context?: object; + } } + + /** + * Promisifies entire object + */ + export function promisifyAll(source: object, options?: I.PromisifyAllOptions): object; + + /** + * Executes a function after promise fulfillment + * + * @returns the original promise + */ + function _finally(promise: Promise, onFinally?: (...args: any[]) => void): Promise; + export { _finally as finally }; } - - /** - * Promisifies entire object - */ - export function promisifyAll(source: object, options?: I.PromisifyAllOptions): object; - - /** - * Executes a function after promise fulfillment - * - * @returns the original promise - */ - function _finally(promise: Promise, onFinally?: (...args: any[]) => void): Promise; - export { _finally as finally }; } diff --git a/types/adone/glosses/shani.d.ts b/types/adone/glosses/shani.d.ts index 788267c693..0b79633f78 100644 --- a/types/adone/glosses/shani.d.ts +++ b/types/adone/glosses/shani.d.ts @@ -1,1655 +1,1683 @@ -/** - * testing framework - */ -export namespace shani { - namespace I { - interface EngineOptions { - /** - * Default timeout for tests and block - */ - defaultTimeout?: number; +declare namespace adone { + /** + * testing framework + */ + namespace shani { + namespace I { + interface EngineOptions { + /** + * Default timeout for tests and block + */ + defaultTimeout?: number; - /** - * Default timeout for hooks - */ - defaultHookTimeout?: number; + /** + * Default timeout for hooks + */ + defaultHookTimeout?: number; - /** - * Options that transplirer uses when loads tests from files - */ - transpilerOptions?: object; // TODO: possible options to adone.js.compiler + /** + * Options that transplirer uses when loads tests from files + */ + transpilerOptions?: object; // TODO: possible options to adone.js.compiler - /** - * Forca calling gc function after each processed file - */ - callGc?: boolean; + /** + * Forca calling gc function after each processed file + */ + callGc?: boolean; + } + + interface DescribeOptions { + /** + * Specify that this block must be skipped + */ + skip?: boolean | (() => void); + + /** + * Specify the timeout for this block + */ + timeout?: number | (() => void); + } + + interface DescribeRuntimeContext { + /** + * Skip this block + */ + skip(): void; + + /** + * Specify timeout for this block + */ + timeout(ms: number): void; + + [key: string]: any; + } + + type DescribeCallback = (this: DescribeRuntimeContext) => void; + + interface DescribeFunction { + (description: string, callback: DescribeCallback): void; + (description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, description: string, callback: DescribeCallback): void; + (a: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, i: string, description: string, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, i: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; + (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, i: string, j: string, description: string, callback: DescribeCallback): void; + ( + a: string, b: string, c: string, + d: string, e: string, f: string, + g: string, h: string, i: string, + j: string, description: string, options: DescribeOptions, + callback: DescribeCallback + ): void; + (a: string, ...args: Array): void; + + /** + * Mark this block as inclusive + */ + only: DescribeFunction; + + /** + * Mark this block as exclusive + */ + skip: DescribeFunction; + } + + interface TestOptions { + /** + * Specify that this test must be skipped + */ + skip?: boolean | (() => void); + + /** + * Specify timeout for this test + */ + timeout?: number | (() => void); + + /** + * Add before hook for this test + */ + before?: HookCallback | [string, HookCallback]; + + /** + * Add after hook for this test + */ + after?: HookCallback | [string, HookCallback]; + } + + interface TestRuntimeContext { + /** + * Skip this test + */ + skip(): void; + + /** + * Specify timeout for this test + */ + timeout(ms: number): void; + + [key: string]: any; + } + + type TestCallback = (this: TestRuntimeContext, done: (err?: any) => void) => void; + + interface TestFunction { + (description: string, callback: TestCallback): void; + (description: string, options: TestOptions, callback: TestCallback): void; + /** + * Mark this test as inclusive + */ + only: TestFunction; + + /** + * Mark this test as exclusive + */ + skip: TestFunction; + } + + interface HookRuntimeContext { + /** + * Specify timeout for this hook + */ + timeout(ms: number): void; + + [key: string]: any; + } + + type HookCallback = (this: HookRuntimeContext, done: (err?: any) => void) => void; + + interface HookFunction { + (callback: HookCallback): void; + (description: string, callback: HookCallback): void; + } + + type StartHookEvent = "start before hook" | "start after hook" + | "start before each hook" | "start after each hook" + | "start before test hook" | "start after test hook"; + + type EndHookEvent = "end before hook" | "end after hook" + | "end before each hook" | "end after each hook" + | "end before test hook" | "end after test hook"; + + interface Emitter extends event.EventEmitter { + on(event: "enter block", listener: (event: { block: Block }) => void): this; + on(event: "exit block", listener: (event: { block: Block }) => void): this; + on(event: "start test", listener: (event: { block: Block, test: Test }) => void): this; + on(event: "end test", listener: (event: { block: Block, test: Test, meta: ExecutionResult }) => void): this; + on(event: "skip test", listener: (event: { block: Block, test: Test, runtime: boolean }) => void): this; + on(event: StartHookEvent, listener: (event: { block: Block, test: Test, hook: Hook }) => void): this; + on(event: EndHookEvent, listener: (event: { block: Block, test: Test, hook: Hook, meta: ExecutionResult }) => void): this; + on(event: "error", listener: (err: any) => void): this; + on(event: "done", listener: () => void): this; + + /** + * Stops testing + */ + stop(): void; + } + + interface ExecutionResult { + /** + * Resulting error + */ + err: any; + + /** + * Elapsed time in milliseconds + */ + elapsed: number; + } + + class Hook { + desctiption: string; + + constructor(description: string, callback: HookCallback, runtimeContext: object); + + /** + * Check if this hook has been run + */ + fired(): boolean; + + /** + * Check if this hook failed + */ + failed(): boolean; + + /** + * The cause of the fail + */ + cause(): any; + + /** + * Returns the timeout of the hook + */ + timeout(): number; + + /** + * Seta a timeout for this hook + */ + timeout(ms: number): this; + + /** + * Executes the hook + */ + run(): Promise; + } + + class Test { + description: string; + + constructor(description: string, callback: TestCallback, block: Block, runtimeContext: object, options: TestOptions); + + /** + * Handles params from options + */ + prepare(): Promise; + + /** + * Checks if this test is exclusive (has skip flag) + */ + isExclusive(): boolean; + + /** + * Checks if this test is exclusive (has only flag) + */ + isInclusive(): boolean; + + /** + * Skips this test + */ + skip(): this; + + /** + * Marks this test as inclusive + */ + only(): this; + + /** + * Returns the timeout of the test + */ + timeout(): number | null; + + /** + * Sets a timeout for this test + */ + timeout(ms: number): this; + + /** + * Returns a string of names from the root to this test + */ + chain(): string; + + /** + * Executes the test + */ + run(): Promise; + } + + class Block { + name: string; + hooks: { + before: Hook[]; + beforeEach: Hook[]; + afterEach: Hook[]; + after: Hook[]; + }; + children: Array; + + constructor(name: string, parent: Block, options: DescribeOptions); + + /** + * Handles params from options + */ + prepare(): Promise; + + /** + * Adds a new child into this block + */ + addChild(child: Block | Test): void; + + /** + * Before hooks iterator + */ + beforeHooks(): IterableIterator; + + /** + * After hooks iterator + */ + afterHooks(): IterableIterator; + + /** + * Before each hooks iterator + */ + beforeEachHooks(): IterableIterator; + + /** + * After each hooks iterator + */ + afterEachHooks(): IterableIterator; + + /** + * Checks if this block is exclusive (has skip flag) + */ + isExclusive(): boolean; + + /** + * Checks if this block is inclusive (has only flag) + */ + isInclusive(): boolean; + + /** + * Checks if this block has an inclusive node + */ + hasInclusive(): boolean; + + /** + * Skips this block + */ + skip(): this; + + /** + * Marks this block as inclusive + */ + only(): this; + + /** + * Returns the timeout of the block + */ + timeout(): number | null; + + /** + * Sets a timeout for this block + */ + timeout(ms: number): this; + + /** + * Returns the block's level, the length of parent blocks chain + */ + level(): number; + + /** + * Sets the block's level + */ + level(level: number): this; + + /** + * Returns a string of names from the root to this block + */ + chain(): string; + + /** + * Returns a chain of blocks from the root to this block + */ + blockChain(): Block[]; + } + + interface Context { + /** + * Defines a tests block + */ + describe: DescribeFunction; + + /** + * Defines a tests block + */ + context: DescribeFunction; + + /** + * Defines a test + */ + it: TestFunction; + + /** + * Defines a test + */ + specify: TestFunction; + + /** + * Defines a hook that will be called only once before the block's tests + */ + before: HookFunction; + + /** + * Defines a hook that will be called only once after the block's tests + */ + after: HookFunction; + + /** + * Defines a hook that will be called before each test + */ + beforeEach: HookFunction; + + /** + * Defines a hook that will be called after each test + */ + afterEach: HookFunction; + + /** + * Root node + */ + root: Block; + + /** + * Starts testing + */ + start(): Emitter; + } } - interface DescribeOptions { - /** - * Specify that this block must be skipped - */ - skip?: boolean | (() => void); + /** + * Represents a testing engine + */ + export class Engine { + constructor(options?: I.EngineOptions); /** - * Specify the timeout for this block + * Includes given files as test files */ - timeout?: number | (() => void); - } - - interface DescribeRuntimeContext { - /** - * Skip this block - */ - skip(): void; + include(...paths: string[]): void; /** - * Specify timeout for this block + * Excludes given paths from testing */ - timeout(ms: number): void; - - [key: string]: any; - } - - type DescribeCallback = (this: DescribeRuntimeContext) => void; - - interface DescribeFunction { - (description: string, callback: DescribeCallback): void; - (description: string, options: DescribeOptions, callback: DescribeCallback): void; - (a: string, description: string, callback: DescribeCallback): void; - (a: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; - (a: string, b: string, description: string, callback: DescribeCallback): void; - (a: string, b: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; - (a: string, b: string, c: string, description: string, callback: DescribeCallback): void; - (a: string, b: string, c: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, description: string, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, e: string, description: string, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, e: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, e: string, f: string, description: string, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, e: string, f: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, e: string, f: string, g: string, description: string, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, e: string, f: string, g: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, description: string, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, i: string, description: string, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, i: string, description: string, options: DescribeOptions, callback: DescribeCallback): void; - (a: string, b: string, c: string, d: string, e: string, f: string, g: string, h: string, i: string, j: string, description: string, callback: DescribeCallback): void; - ( - a: string, b: string, c: string, - d: string, e: string, f: string, - g: string, h: string, i: string, - j: string, description: string, options: DescribeOptions, - callback: DescribeCallback - ): void; - (a: string, ...args: Array): void; + exclude(...paths: string[]): void; /** - * Mark this block as inclusive + * Returns a testing context */ - only: DescribeFunction; - - /** - * Mark this block as exclusive - */ - skip: DescribeFunction; - } - - interface TestOptions { - /** - * Specify that this test must be skipped - */ - skip?: boolean | (() => void); - - /** - * Specify timeout for this test - */ - timeout?: number | (() => void); - - /** - * Add before hook for this test - */ - before?: HookCallback | [string, HookCallback]; - - /** - * Add after hook for this test - */ - after?: HookCallback | [string, HookCallback]; - } - - interface TestRuntimeContext { - /** - * Skip this test - */ - skip(): void; - - /** - * Specify timeout for this test - */ - timeout(ms: number): void; - - [key: string]: any; - } - - type TestCallback = (this: TestRuntimeContext, done: (err?: any) => void) => void; - - interface TestFunction { - (description: string, callback: TestCallback): void; - (description: string, options: TestOptions, callback: TestCallback): void; - /** - * Mark this test as inclusive - */ - only: TestFunction; - - /** - * Mark this test as exclusive - */ - skip: TestFunction; - } - - interface HookRuntimeContext { - /** - * Specify timeout for this hook - */ - timeout(ms: number): void; - - [key: string]: any; - } - - type HookCallback = (this: HookRuntimeContext, done: (err?: any) => void) => void; - - interface HookFunction { - (callback: HookCallback): void; - (description: string, callback: HookCallback): void; - } - - type StartHookEvent = "start before hook" | "start after hook" - | "start before each hook" | "start after each hook" - | "start before test hook" | "start after test hook"; - - type EndHookEvent = "end before hook" | "end after hook" - | "end before each hook" | "end after each hook" - | "end before test hook" | "end after test hook"; - - interface Emitter extends adone.EventEmitter { - on(event: "enter block", listener: (event: { block: Block }) => void): this; - on(event: "exit block", listener: (event: { block: Block }) => void): this; - on(event: "start test", listener: (event: { block: Block, test: Test }) => void): this; - on(event: "end test", listener: (event: { block: Block, test: Test, meta: ExecutionResult }) => void): this; - on(event: "skip test", listener: (event: { block: Block, test: Test, runtime: boolean }) => void): this; - on(event: StartHookEvent, listener: (event: { block: Block, test: Test, hook: Hook }) => void): this; - on(event: EndHookEvent, listener: (event: { block: Block, test: Test, hook: Hook, meta: ExecutionResult }) => void): this; - on(event: "error", listener: (err: any) => void): this; - on(event: "done", listener: () => void): this; - - /** - * Stops testing - */ - stop(): void; - } - - interface ExecutionResult { - /** - * Resulting error - */ - err: any; - - /** - * Elapsed time in milliseconds - */ - elapsed: number; - } - - class Hook { - desctiption: string; - - constructor(description: string, callback: HookCallback, runtimeContext: object); - - /** - * Check if this hook has been run - */ - fired(): boolean; - - /** - * Check if this hook failed - */ - failed(): boolean; - - /** - * The cause of the fail - */ - cause(): any; - - /** - * Returns the timeout of the hook - */ - timeout(): number; - - /** - * Seta a timeout for this hook - */ - timeout(ms: number): this; - - /** - * Executes the hook - */ - run(): Promise; - } - - class Test { - description: string; - - constructor(description: string, callback: TestCallback, block: Block, runtimeContext: object, options: TestOptions); - - /** - * Handles params from options - */ - prepare(): Promise; - - /** - * Checks if this test is exclusive (has skip flag) - */ - isExclusive(): boolean; - - /** - * Checks if this test is exclusive (has only flag) - */ - isInclusive(): boolean; - - /** - * Skips this test - */ - skip(): this; - - /** - * Marks this test as inclusive - */ - only(): this; - - /** - * Returns the timeout of the test - */ - timeout(): number | null; - - /** - * Sets a timeout for this test - */ - timeout(ms: number): this; - - /** - * Returns a string of names from the root to this test - */ - chain(): string; - - /** - * Executes the test - */ - run(): Promise; - } - - class Block { - name: string; - hooks: { - before: Hook[]; - beforeEach: Hook[]; - afterEach: Hook[]; - after: Hook[]; - }; - children: Array; - - constructor(name: string, parent: Block, options: DescribeOptions); - - /** - * Handles params from options - */ - prepare(): Promise; - - /** - * Adds a new child into this block - */ - addChild(child: Block | Test): void; - - /** - * Before hooks iterator - */ - beforeHooks(): IterableIterator; - - /** - * After hooks iterator - */ - afterHooks(): IterableIterator; - - /** - * Before each hooks iterator - */ - beforeEachHooks(): IterableIterator; - - /** - * After each hooks iterator - */ - afterEachHooks(): IterableIterator; - - /** - * Checks if this block is exclusive (has skip flag) - */ - isExclusive(): boolean; - - /** - * Checks if this block is inclusive (has only flag) - */ - isInclusive(): boolean; - - /** - * Checks if this block has an inclusive node - */ - hasInclusive(): boolean; - - /** - * Skips this block - */ - skip(): this; - - /** - * Marks this block as inclusive - */ - only(): this; - - /** - * Returns the timeout of the block - */ - timeout(): number | null; - - /** - * Sets a timeout for this block - */ - timeout(ms: number): this; - - /** - * Returns the block's level, the length of parent blocks chain - */ - level(): number; - - /** - * Sets the block's level - */ - level(level: number): this; - - /** - * Returns a string of names from the root to this block - */ - chain(): string; - - /** - * Returns a chain of blocks from the root to this block - */ - blockChain(): Block[]; - } - - interface Context { - /** - * Defines a tests block - */ - describe: DescribeFunction; - - /** - * Defines a tests block - */ - context: DescribeFunction; - - /** - * Defines a test - */ - it: TestFunction; - - /** - * Defines a test - */ - specify: TestFunction; - - /** - * Defines a hook that will be called only once before the block's tests - */ - before: HookFunction; - - /** - * Defines a hook that will be called only once after the block's tests - */ - after: HookFunction; - - /** - * Defines a hook that will be called before each test - */ - beforeEach: HookFunction; - - /** - * Defines a hook that will be called after each test - */ - afterEach: HookFunction; - - /** - * Root node - */ - root: Block; + context(): I.Context; /** * Starts testing */ - start(): Emitter; - } - } - - /** - * Represents a testing engine - */ - export class Engine { - constructor(options?: I.EngineOptions); - - /** - * Includes given files as test files - */ - include(...paths: string[]): void; - - /** - * Excludes given paths from testing - */ - exclude(...paths: string[]): void; - - /** - * Returns a testing context - */ - context(): I.Context; - - /** - * Starts testing - */ - start(): I.Emitter; - } - - namespace util { - namespace I { - // based on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/sinon - - interface SpyCallApi { - /** - * The call's this value - */ - thisValue: any; - - /** - * The call's arguments - */ - args: any[]; - - /** - * Exception throws if any - */ - exception: any; - - /** - * Return value - */ - returnValue: any; - - /** - * Whether the spy was called on obj (this value) - */ - calledOn(obj: any): boolean; - - /** - * Whether the arguments were args (and possibly others) - */ - calledWith(...args: any[]): boolean; - - /** - * Whether the arguments were exactly args (no others) - */ - calledWithExactly(...args: any[]): boolean; - - /** - * Whether the call received matching args (and possibly others) - */ - calledWithMatch(...args: any[]): boolean; - - /** - * Whether the call did not receive args - */ - notCalledWith(...args: any[]): boolean; - - /** - * Whether the call did not receive matching args - */ - notCalledWithMatch(...args: any[]): boolean; - - /** - * Whether the call returned the given value - */ - returned(value: any): boolean; - - /** - * Whether the call threw an exception - */ - threw(): boolean; - - /** - * Whether the call threw an exception of provided type - */ - threw(type: string): boolean; - - /** - * Whether the call threw obj - */ - threw(obj: any): boolean; - - /** - * Calls the argument at the given index - */ - callArg(pos: number): void; - - /** - * Calls the argument at the given index on the given context - */ - callArgOn(pos: number, obj: any): void; - - /** - * Calls the argument at the given index with arguments - */ - callArgWith(pos: number, ...args: any[]): void; - - /** - * Calls the argument at the given index on the given context and with the given arguments - */ - callArgOnWith(pos: number, obj: any, ...args: any[]): void; - - /** - * Calls a callback from the arguments with the given arguments - */ - yield(...args: any[]): void; - - /** - * Calls a callback from the arguments with the given arguments on the given context - */ - yieldOn(obj: any, ...args: any[]): void; - - /** - * Calls with the given arguments a callback that is a property of the call's argument with the given name - */ - yieldTo(property: string, ...args: any[]): void; - - /** - * Calls on the given context with the given arguments a callback that - * is a property of the call's argument with the given name - */ - yieldToOn(property: string, obj: any, ...args: any[]): void; - } - - interface SpyCall extends SpyCallApi { - /** - * Whether the call was called before the given call - */ - calledBefore(call: SpyCall): boolean; - - /** - * Whether the call was called after the given call - */ - calledAfter(call: SpyCall): boolean; - - /** - * Whether the call was called using the new operator - */ - calledWithNew(call: SpyCall): boolean; - } - - interface Spy extends SpyCallApi { - /** - * The number of recorded calls - */ - callCount: number; - - /** - * Whether the spy was called - */ - called: boolean; - - /** - * Whether the spy was not called - */ - notCalled: boolean; - - /** - * Whether the spy was called once - */ - calledOnce: boolean; - - /** - * Whether the spy was called twice - */ - calledTwice: boolean; - - /** - * Whether the spy was called thrice - */ - calledThrice: boolean; - - /** - * The first call - */ - firstCall: SpyCall; - - /** - * The second call - */ - secondCall: SpyCall; - - /** - * The third call - */ - thirdCall: SpyCall; - - /** - * The last call - */ - lastCall: SpyCall; - - /** - * Array of the calls contexts - */ - thisValues: any[]; - - /** - * Array of the calls arguments - */ - args: any[][]; - - /** - * Array of the calls exceptions - */ - exceptions: any[]; - - /** - * Array of the calls return values - */ - returnValues: any[]; - - (...args: any[]): any; - /** - * Whether the spy was called before another spy - */ - calledBefore(anotherSpy: Spy): boolean; - - /** - * Whether the spy was called after another spy - */ - calledAfter(anotherSpy: Spy): boolean; - - /** - * Whether the spy was called before another spy and no spies occured between them - */ - calledImmediatelyBefore(anotherSpy: Spy): boolean; - - /** - * Whether the spy was called after another spy and no spies occured between them - */ - calledImmediatelyAfter(anotherSpy: Spy): boolean; - - /** - * Whether the spy was called using the new operator - */ - calledWithNew(): boolean; - - /** - * Creates a spy that record calls only with the given arguments - */ - withArgs(...args: any[]): Spy; - - /** - * Whether the spy was called on the given context (this value) - */ - alwaysCalledOn(obj: any): boolean; - - /** - * Whether the spy was called with the given arguments (and possibly others) - */ - alwaysCalledWith(...args: any[]): boolean; - - /** - * Whether the spy was called exactly with the given arguments (no others) - */ - alwaysCalledWithExactly(...args: any[]): boolean; - - /** - * Whether the spy was called with the matching arguments (and possibly others) - */ - alwaysCalledWithMatch(...args: any[]): boolean; - - /** - * Whether the spy was never called with the given arguments - */ - neverCalledWith(...args: any[]): boolean; - - /** - * Whether the spy was neven called with the matching arguments - */ - neverCalledWithMatch(...args: any[]): boolean; - - /** - * Whether the spy always threw exceptions - */ - alwaysThrew(): boolean; - - /** - * Whether the spy always threw exceptions of the given types - */ - alwaysThrew(type: string): boolean; - - /** - * Whether the spy always threw the given object - */ - alwaysThrew(obj: any): boolean; - - /** - * Whether the spy always returned the given object - */ - alwaysReturned(obj: any): boolean; - - /** - * Invokes the callbacks passed in the arguments with the given arguments - */ - invokeCallback(...args: any[]): void; - - /** - * Returns the call with the given index - */ - getCall(n: number): SpyCall; - - /** - * Returns all the calls - */ - getCalls(): SpyCall[]; - - /** - * Resets the state of the spy - */ - reset(): void; - - /** - * Returns the passed format string with the given replacements - */ - printf(format: string, ...args: any[]): string; - - /** - * Replaces the spy with the original method if the spy replaced an original method - */ - restore(): void; - } - - interface Stub extends Spy { - /** - * Resets the stub's behavior to the default behavior - */ - resetBehavior(): void; - - /** - * Resets the stub's history - */ - resetHistory(): void; - - /** - * Causes the stub to return promises using the given promise library - */ - usingPromise(promiseLibrary: any): Stub; - - /** - * Makes the stub return the given object - */ - returns(obj: any): Stub; - - /** - * Causes the stub to return the argument at the given index - */ - returnsArg(index: number): Stub; - - /** - * Causes the stub to return its this value - */ - returnsThis(): Stub; - - /** - * Causes the stub to return a promise that resolves to the given value - */ - resolves(value?: any): Stub; - - /* - * Causes the stub to throw an exception of the given type - */ - throws(type?: string): Stub; - - /** - * Causes the stub to throw the given object - */ - throws(obj: any): Stub; - - /** - * Causes the stub to throw the argument at the given index - */ - throwsArg(index: number): Stub; - - /* - * Causes the stub to throw an exception of the given type - */ - throwsException(type?: string): Stub; - - /** - * Causes the stub to throw the argument at the given index - */ - throwsException(obj: any): Stub; - - /** - * Causes the stub to reject - */ - rejects(): Stub; - - /** - * Causes the stub to reject with the given type - */ - rejects(errorType: string): Stub; - - /** - * Causes the stub to reject with the given value - */ - rejects(value: any): Stub; - - /** - * Causes the stub to call the argument at the provided index as a callback function - */ - callsArg(index: number): Stub; - - /** - * Causes the original method wrapped into the stub to be called when none of the conditional stubs are matched - */ - callThrough(): Stub; - - /** - * Causes the stub to call the argument at the provided index as a callback function on the given context - */ - callsArgOn(index: number, context: any): Stub; - - /** - * Causes the stub to call the argument at the provided index as a callback function with the given arguments - */ - callsArgWith(index: number, ...args: any[]): Stub; - - /** - * Causes the stub to call the argument at the provided index as a callback function on the given context with the given arguments - */ - callsArgOnWith(index: number, context: any, ...args: any[]): Stub; - - /** - * Causes the stub to asynchronously call the argument at the provided index as a callback function - */ - callsArgAsync(index: number): Stub; - - /** - * Causes the stub to asynchronously call the argument at the provided index as a callback function on the given context - */ - callsArgOnAsync(index: number, context: any): Stub; - - /** - * Causes the stub to asynchronously call the argument at the provided index as a callback function on the given context with the given arguments - */ - callsArgWithAsync(index: number, ...args: any[]): Stub; - - /** - * Causes the stub to asynchronously call the argument at the provided index as a callback function on the given context with the given arguments - */ - callsArgOnWithAsync(index: number, context: any, ...args: any[]): Stub; - - /** - * Makes the stub call the provided fake function - */ - callsFake(func: (...args: any[]) => void): Stub; - - /** - * Replaces a new getter with this stub - */ - get(func: () => any): Stub; - - /** - * Replaces a new getter with this stub - */ - set(func: (v: any) => void): Stub; - - /** - * Defines the behavior of the stub on the call with the given index - */ - onCall(n: number): Stub; - - /** - * Defines the behavior of the stub on the first call - */ - onFirstCall(): Stub; - - /** - * Defines the behavior of the stub on the second call - */ - onSecondCall(): Stub; - - /** - * Defines the behavior of the stub on the third call - */ - onThirdCall(): Stub; - - /** - * Defines a new value for this stub - */ - value(val: any): Stub; - - /** - * Causes the stub to call the first callback it receives with the provided arguments - */ - yields(...args: any[]): Stub; - - /** - * Causes the stub to call the first callback it receives with the provided arguments on the given context - */ - yieldsOn(context: any, ...args: any[]): Stub; - - /** - * Causes the stub to call the last callback it receives with the provided arguments - */ - yieldsRight(...args: any[]): Stub; - - /** - * Causes the stub to invoke a callback passed as a property of an object to the spy - */ - yieldsTo(property: string, ...args: any[]): Stub; - - /** - * Causes the stub to invoke a callback passed as a property of an object to the spy on the given context - */ - yieldsToOn(property: string, context: any, ...args: any[]): Stub; - - /** - * Causes the stub to asynchronously call the first callback it receives with the provided arguments - */ - yieldsAsync(...args: any[]): Stub; - - /** - * Causes the stub to asynchronously call the first callback it receives with the provided arguments on the given context - */ - yieldsOnAsync(context: any, ...args: any[]): Stub; - - /** - * Causes the stub to asynchronously invoke a callback passed as a property of an object to the spy - */ - yieldsToAsync(property: string, ...args: any[]): Stub; - - /** - * Causes the stub to asynchronously invoke a callback passed as a property of an object to the spy on the given context - */ - yieldsToOnAsync(property: string, context: any, ...args: any[]): Stub; - - /** - * Stubs the method only for the provided arguments - */ - withArgs(...args: any[]): Stub; - } - - interface Expectation extends Stub { - /** - * Specifies the minimum amount of calls expected - */ - atLeast(n: number): Expectation; - - /** - * Specifies the maximum amount of calls expected - */ - atMost(n: number): Expectation; - - /** - * Expects the method to never be called - */ - never(): Expectation; - - /** - * Expects the method to be called exactly once - */ - once(): Expectation; - - /** - * Expects the method to be called exactly twice - */ - twice(): Expectation; - - /** - * Expects the method to be called exactly thrice - */ - thrice(): Expectation; - - /** - * Expects the method to be called exactly n times - */ - exactly(n: number): Expectation; - - /** - * Expects the method to be called with the provided arguments and possibly others - */ - withArgs(...args: any[]): Expectation; - - /** - * Expects the method to be called with the provided arguments and no others - */ - withExactArgs(...args: any[]): Expectation; - - /** - * Expects the method to be called with obj as this - */ - on(obj: any): Expectation; - - /** - * Verifies the expectation and throws an exception if it’s not met - */ - verify(): Expectation; - - /** - * Restores all mocked methods - */ - restore(): void; - } - - interface ExpectationStatic { - /** - * Creates a new expectation - */ - create(methodName?: string): Expectation; - } - - interface Mock { - /** - * Overrides obj.method with a mock function and returns it - */ - expects(method: string): Expectation; - - /** - * Restores all mocked methods - */ - restore(): void; - - /** - * Verifies all expectations on the mock - */ - verify(): void; - } - - interface ExposeOptions { - /** - * prefix to give assertions - */ - prefix?: string; - - /** - * Whether to copy the fail and failException properties - */ - includeFail?: boolean; - } - - interface Assert { - /** - * Default error type thrown by .fail - */ - failException: string; - - /** - * Every assertion fails by calling this method - */ - fail(message?: string): void; - - /** - * Called every time assertion passes - */ - pass(assertion: any): void; - - /** - * Passes if spy was never called - */ - notCalled(spy: Spy): void; - - /** - * Passes if spy was called at least once - */ - called(spy: Spy): void; - - /** - * Passes if spy was called once and only once - */ - calledOnce(spy: Spy): void; - - /** - * Passes if spy was called exactly twice - */ - calledTwice(spy: Spy): void; - - /** - * Passes if spy was called exactly three times - */ - calledThrice(spy: Spy): void; - - /** - * Passes if spy was called exactly count times - */ - callCount(spy: Spy, count: number): void; - - /** - * Passes if provided spies were called in the specified order - */ - callOrder(...spies: Spy[]): void; - - /** - * Passes if spy was ever called with obj as its this value - */ - calledOn(spy: Spy, obj: any): void; - - /** - * Passes if spy was always called with obj as its this value - */ - alwaysCalledOn(spy: Spy, obj: any): void; - - /** - * Passes if spy was called with the provided arguments - */ - calledWith(spy: Spy, ...args: any[]): void; - - /** - * Passes if spy was always called with the provided arguments - */ - alwaysCalledWith(spy: Spy, ...args: any[]): void; - - /** - * Passes if spy was never called with the provided arguments - */ - neverCalledWith(spy: Spy, ...args: any[]): void; - - /** - * Passes if spy was called with the provided arguments and no others - */ - calledWithExactly(spy: Spy, ...args: any[]): void; - - /** - * Passes if spy was always called with the provided arguments and no others - */ - alwaysCalledWithExactly(spy: Spy, ...args: any[]): void; - - /** - * Passes if spy was called with matching arguments. - */ - calledWithMatch(spy: Spy, ...args: any[]): void; - - /** - * Passes if spy was always called with matching arguments - */ - alwaysCalledWithMatch(spy: Spy, ...args: any[]): void; - - /** - * Passes if spy was never called with matching arguments - */ - neverCalledWithMatch(spy: Spy, ...args: any[]): void; - - /** - * Passes if spy threw - */ - threw(spy: Spy): void; - - /** - * Passes if spy threw the given exception type - */ - threw(spy: Spy, exception: string): void; - - /** - * Passes if spy threw the given object - */ - threw(spy: Spy, exception: any): void; - - /** - * Passes if always spy threw - */ - alwaysThrew(spy: Spy): void; - - /** - * Passes if spy always threw the given exception type - */ - alwaysThrew(spy: Spy, exception: string): void; - - /** - * Passes if spy always threw the given object - */ - alwaysThrew(spy: Spy, exception: any): void; - - /** - * Exposes assertions into another object, to better integrate with the test framework - */ - expose(obj: any, options?: ExposeOptions): void; - } - - interface Matcher { - /** - * Logical and - */ - and(expr: Matcher): Matcher; - - /** - * Logical or - */ - or(expr: Matcher): Matcher; - } - - interface ArrayMatcher extends Matcher { - /** - * Requires an Array to be deep equal another one. - */ - deepEquals(expected: any[]): Matcher; - - /** - * Requires an Array to start with the same values as another one. - */ - startsWith(expected: any[]): Matcher; - - /** - * Requires an Array to end with the same values as another one. - */ - endsWith(expected: any[]): Matcher; - - /** - * Requires an Array to contain each one of the values the given array has. - */ - contains(expected: any[]): Matcher; - } - - interface MapMatcher extends Matcher { - /** - * Requires a Map to be deep equal another one. - */ - deepEquals(expected: Map): Matcher; - - /** - * Requires a Map to contain each one of the items the given map has. - */ - contains(expected: Map): Matcher; - } - - interface SetMatcher extends Matcher { - /** - * Requires a Set to be deep equal another one. - */ - deepEquals(expected: Set): Matcher; - - /** - * Requires a Set to contain each one of the items the given set has. - */ - contains(expected: Set): Matcher; - } - - interface Match { - /** - * Requires the value to be == to the given number - */ - (value: number): Matcher; - - /** - * Requires the value to be a string and have the expectation as a substring - */ - (value: string): Matcher; - - /** - * Requires the value to be a string and match the given regular expression - */ - (expr: RegExp): Matcher; - - /** - * Requires the value to be not null or undefined and have at least the same properties as expectation - */ - (obj: any): Matcher; - - /** - * Specify a custom matcher - */ - (callback: (value: any) => boolean, message?: string): Matcher; - - /** - * Matches anything - */ - any: Matcher; - - /** - * Requires the value to be defined - */ - defined: Matcher; - - /** - * Requires the value to be truthy - */ - truthy: Matcher; - - /** - * Requires the value to be falsy - */ - falsy: Matcher; - - /** - * Requires the value to be a boolean - */ - bool: Matcher; - - /** - * Requires the value to be a number - */ - number: Matcher; - - /** - * Requires the value to be a string - */ - string: Matcher; - - /** - * Requires the value to be an object - */ - object: Matcher; - - /** - * Requires the value to be a function - */ - func: Matcher; - - /** - * Requires the value to be a map. - */ - map: MapMatcher; - - /** - * Requires the value to be a set. - */ - set: SetMatcher; - - /** - * Requires the value to be an array. - */ - array: ArrayMatcher; - - /** - * Requires the value to be a regular expression - */ - regexp: Matcher; - - /** - * Requires the value to be a date object - */ - date: Matcher; - - /** - * Requires the value to be a symbol - */ - symbol: Matcher; - - /** - * Requires the value to strictly equal obj - */ - same(obj: any): Matcher; - - /** - * Requires the value to be of the given type - */ - typeOf(type: adone.util.I.PossibleTypes): Matcher; - typeOf(type: string): Matcher; - - /** - * Requires the value to be an instance of the given type - */ - instanceOf(type: any): Matcher; - - /** - * Requires the value to define the given property - */ - has(property: string, expect?: any): Matcher; - - /** - * Requires the value to define the given property by itself - */ - hasOwn(property: string, expect?: any): Matcher; - } - - interface SandboxConfig { - /** - * An object to add properties to - */ - injectInto?: any; - - /** - * What properties to inject - */ - properties?: string[]; - } - - interface Sandbox { - /** - * A convenience reference for assert - */ - assert: Assert; - - /** - * Works exactly like spy, only also adds the returned spy to the internal collection of fakes - */ - spy: typeof spy; - - /** - * Works exactly like stub, only also adds the returned spy to the internal collection of fakes - */ - stub: typeof stub; - - /** - * Works exactly like mock, only also adds the returned spy to the internal collection of fakes - */ - mock: typeof mock; - - /** - * Restores all fakes created through sandbox - */ - restore(): void; - - /** - * Resets the internal state of all fakes created through sandbox - */ - reset(): void; - - /** - * Resets the history of all stubs created through the sandbox - */ - resetHistory(): void; - - /** - * Resets the behaviour of all stubs created through the sandbox - */ - resetBehavior(): void; - - /** - * Causes all stubs created from the sandbox to return promises using a specific promise library - */ - usingPromise(promiseLibrary: any): Sandbox; - - /** - * Verifies all mocks created through the sandbox - */ - verify(): void; - - /** - * Verifies all mocks and restores all fakes created through the sandbox - */ - verifyAndRestore(): void; - } - - interface SandboxStatic { - /** - * Creates a sandbox object with spies, stubs, and mocks - */ - create(config?: SandboxConfig): Sandbox; - } + start(): I.Emitter; } - /** - * Return a function that records arguments, return value, the value of this and exception thrown (if any) for all its calls - */ - function spy(func?: (...args: any[]) => void): I.Spy; - function spy(object: T, method: keyof T): I.Spy; + namespace util { + namespace I { + // based on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/sinon - /** - * Creates a function (spy) with pre-programmed behavior - */ - function stub(obj?: any): I.Stub; - function stub(obj: T, method: keyof T): I.Stub; + interface SpyCallApi { + /** + * The call's this value + */ + thisValue: any; - const expectation: I.ExpectationStatic; + /** + * The call's arguments + */ + args: any[]; - /** - * Creates a fake method (like spy) with pre-programmed behavior (like stub) - */ - function mock(): I.Expectation; - function mock(obj: any): I.Mock; + /** + * Exception throws if any + */ + exception: any; - /** - * Assertions for spies/stubs - */ - export const assert: I.Assert; + /** + * Return value + */ + returnValue: any; - /** - * Creates a matcher function - */ - export const match: I.Match; + /** + * Whether the spy was called on obj (this value) + */ + calledOn(obj: any): boolean; - /** - * Removes the need to keep track of every fake created - */ - export const sandbox: I.SandboxStatic; + /** + * Whether the arguments were args (and possibly others) + */ + calledWith(...args: any[]): boolean; - namespace I { - interface Response extends adone.std.http.IncomingMessage { - body: Buffer; + /** + * Whether the arguments were exactly args (no others) + */ + calledWithExactly(...args: any[]): boolean; + + /** + * Whether the call received matching args (and possibly others) + */ + calledWithMatch(...args: any[]): boolean; + + /** + * Whether the call did not receive args + */ + notCalledWith(...args: any[]): boolean; + + /** + * Whether the call did not receive matching args + */ + notCalledWithMatch(...args: any[]): boolean; + + /** + * Whether the call returned the given value + */ + returned(value: any): boolean; + + /** + * Whether the call threw an exception + */ + threw(): boolean; + + /** + * Whether the call threw an exception of provided type + */ + threw(type: string): boolean; + + /** + * Whether the call threw obj + */ + threw(obj: any): boolean; + + /** + * Calls the argument at the given index + */ + callArg(pos: number): void; + + /** + * Calls the argument at the given index on the given context + */ + callArgOn(pos: number, obj: any): void; + + /** + * Calls the argument at the given index with arguments + */ + callArgWith(pos: number, ...args: any[]): void; + + /** + * Calls the argument at the given index on the given context and with the given arguments + */ + callArgOnWith(pos: number, obj: any, ...args: any[]): void; + + /** + * Calls a callback from the arguments with the given arguments + */ + yield(...args: any[]): void; + + /** + * Calls a callback from the arguments with the given arguments on the given context + */ + yieldOn(obj: any, ...args: any[]): void; + + /** + * Calls with the given arguments a callback that is a property of the call's argument with the given name + */ + yieldTo(property: string, ...args: any[]): void; + + /** + * Calls on the given context with the given arguments a callback that + * is a property of the call's argument with the given name + */ + yieldToOn(property: string, obj: any, ...args: any[]): void; + } + + interface SpyCall extends SpyCallApi { + /** + * Whether the call was called before the given call + */ + calledBefore(call: SpyCall): boolean; + + /** + * Whether the call was called after the given call + */ + calledAfter(call: SpyCall): boolean; + + /** + * Whether the call was called using the new operator + */ + calledWithNew(call: SpyCall): boolean; + } + + interface Spy extends SpyCallApi { + /** + * The number of recorded calls + */ + callCount: number; + + /** + * Whether the spy was called + */ + called: boolean; + + /** + * Whether the spy was not called + */ + notCalled: boolean; + + /** + * Whether the spy was called once + */ + calledOnce: boolean; + + /** + * Whether the spy was called twice + */ + calledTwice: boolean; + + /** + * Whether the spy was called thrice + */ + calledThrice: boolean; + + /** + * The first call + */ + firstCall: SpyCall; + + /** + * The second call + */ + secondCall: SpyCall; + + /** + * The third call + */ + thirdCall: SpyCall; + + /** + * The last call + */ + lastCall: SpyCall; + + /** + * Array of the calls contexts + */ + thisValues: any[]; + + /** + * Array of the calls arguments + */ + args: any[][]; + + /** + * Array of the calls exceptions + */ + exceptions: any[]; + + /** + * Array of the calls return values + */ + returnValues: any[]; + + (...args: any[]): any; + /** + * Whether the spy was called before another spy + */ + calledBefore(anotherSpy: Spy): boolean; + + /** + * Whether the spy was called after another spy + */ + calledAfter(anotherSpy: Spy): boolean; + + /** + * Whether the spy was called before another spy and no spies occured between them + */ + calledImmediatelyBefore(anotherSpy: Spy): boolean; + + /** + * Whether the spy was called after another spy and no spies occured between them + */ + calledImmediatelyAfter(anotherSpy: Spy): boolean; + + /** + * Whether the spy was called using the new operator + */ + calledWithNew(): boolean; + + /** + * Creates a spy that record calls only with the given arguments + */ + withArgs(...args: any[]): Spy; + + /** + * Whether the spy was called on the given context (this value) + */ + alwaysCalledOn(obj: any): boolean; + + /** + * Whether the spy was called with the given arguments (and possibly others) + */ + alwaysCalledWith(...args: any[]): boolean; + + /** + * Whether the spy was called exactly with the given arguments (no others) + */ + alwaysCalledWithExactly(...args: any[]): boolean; + + /** + * Whether the spy was called with the matching arguments (and possibly others) + */ + alwaysCalledWithMatch(...args: any[]): boolean; + + /** + * Whether the spy was never called with the given arguments + */ + neverCalledWith(...args: any[]): boolean; + + /** + * Whether the spy was neven called with the matching arguments + */ + neverCalledWithMatch(...args: any[]): boolean; + + /** + * Whether the spy always threw exceptions + */ + alwaysThrew(): boolean; + + /** + * Whether the spy always threw exceptions of the given types + */ + alwaysThrew(type: string): boolean; + + /** + * Whether the spy always threw the given object + */ + alwaysThrew(obj: any): boolean; + + /** + * Whether the spy always returned the given object + */ + alwaysReturned(obj: any): boolean; + + /** + * Invokes the callbacks passed in the arguments with the given arguments + */ + invokeCallback(...args: any[]): void; + + /** + * Returns the call with the given index + */ + getCall(n: number): SpyCall; + + /** + * Returns all the calls + */ + getCalls(): SpyCall[]; + + /** + * Resets the state of the spy + */ + reset(): void; + + /** + * Returns the passed format string with the given replacements + */ + printf(format: string, ...args: any[]): string; + + /** + * Replaces the spy with the original method if the spy replaced an original method + */ + restore(): void; + + /** + * Waits for the call where the given match function returns true + */ + waitFor(match: (call: SpyCall) => boolean): Promise; + waitFor(match: (call: SpyCall) => boolean, ret: (call: SpyCall) => T): Promise; + + /** + * Waits for a call + */ + waitForCall(): Promise; + + /** + * Waits for n calls + */ + waitForNCalls(n: number): Promise; + + /** + * Waits for the call with the given value at the given index (deep equal) + */ + waitForArg(index: number, value: any): Promise; + + /** + * Waits for the call where the first args are deeply equal to the given, it can have more args than given + */ + waitForArgs(...args: any[]): Promise; + } + + interface Stub extends Spy { + /** + * Resets the stub's behavior to the default behavior + */ + resetBehavior(): void; + + /** + * Resets the stub's history + */ + resetHistory(): void; + + /** + * Causes the stub to return promises using the given promise library + */ + usingPromise(promiseLibrary: any): Stub; + + /** + * Makes the stub return the given object + */ + returns(obj: any): Stub; + + /** + * Causes the stub to return the argument at the given index + */ + returnsArg(index: number): Stub; + + /** + * Causes the stub to return its this value + */ + returnsThis(): Stub; + + /** + * Causes the stub to return a promise that resolves to the given value + */ + resolves(value?: any): Stub; + + /* + * Causes the stub to throw an exception of the given type + */ + throws(type?: string): Stub; + + /** + * Causes the stub to throw the given object + */ + throws(obj: any): Stub; + + /** + * Causes the stub to throw the argument at the given index + */ + throwsArg(index: number): Stub; + + /* + * Causes the stub to throw an exception of the given type + */ + throwsException(type?: string): Stub; + + /** + * Causes the stub to throw the argument at the given index + */ + throwsException(obj: any): Stub; + + /** + * Causes the stub to reject + */ + rejects(): Stub; + + /** + * Causes the stub to reject with the given type + */ + rejects(errorType: string): Stub; + + /** + * Causes the stub to reject with the given value + */ + rejects(value: any): Stub; + + /** + * Causes the stub to call the argument at the provided index as a callback function + */ + callsArg(index: number): Stub; + + /** + * Causes the original method wrapped into the stub to be called when none of the conditional stubs are matched + */ + callThrough(): Stub; + + /** + * Causes the stub to call the argument at the provided index as a callback function on the given context + */ + callsArgOn(index: number, context: any): Stub; + + /** + * Causes the stub to call the argument at the provided index as a callback function with the given arguments + */ + callsArgWith(index: number, ...args: any[]): Stub; + + /** + * Causes the stub to call the argument at the provided index as a callback function on the given context with the given arguments + */ + callsArgOnWith(index: number, context: any, ...args: any[]): Stub; + + /** + * Causes the stub to asynchronously call the argument at the provided index as a callback function + */ + callsArgAsync(index: number): Stub; + + /** + * Causes the stub to asynchronously call the argument at the provided index as a callback function on the given context + */ + callsArgOnAsync(index: number, context: any): Stub; + + /** + * Causes the stub to asynchronously call the argument at the provided index as a callback function on the given context with the given arguments + */ + callsArgWithAsync(index: number, ...args: any[]): Stub; + + /** + * Causes the stub to asynchronously call the argument at the provided index as a callback function on the given context with the given arguments + */ + callsArgOnWithAsync(index: number, context: any, ...args: any[]): Stub; + + /** + * Makes the stub call the provided fake function + */ + callsFake(func: (...args: any[]) => void): Stub; + + /** + * Replaces a new getter with this stub + */ + get(func: () => any): Stub; + + /** + * Replaces a new getter with this stub + */ + set(func: (v: any) => void): Stub; + + /** + * Defines the behavior of the stub on the call with the given index + */ + onCall(n: number): Stub; + + /** + * Defines the behavior of the stub on the first call + */ + onFirstCall(): Stub; + + /** + * Defines the behavior of the stub on the second call + */ + onSecondCall(): Stub; + + /** + * Defines the behavior of the stub on the third call + */ + onThirdCall(): Stub; + + /** + * Defines a new value for this stub + */ + value(val: any): Stub; + + /** + * Causes the stub to call the first callback it receives with the provided arguments + */ + yields(...args: any[]): Stub; + + /** + * Causes the stub to call the first callback it receives with the provided arguments on the given context + */ + yieldsOn(context: any, ...args: any[]): Stub; + + /** + * Causes the stub to call the last callback it receives with the provided arguments + */ + yieldsRight(...args: any[]): Stub; + + /** + * Causes the stub to invoke a callback passed as a property of an object to the spy + */ + yieldsTo(property: string, ...args: any[]): Stub; + + /** + * Causes the stub to invoke a callback passed as a property of an object to the spy on the given context + */ + yieldsToOn(property: string, context: any, ...args: any[]): Stub; + + /** + * Causes the stub to asynchronously call the first callback it receives with the provided arguments + */ + yieldsAsync(...args: any[]): Stub; + + /** + * Causes the stub to asynchronously call the first callback it receives with the provided arguments on the given context + */ + yieldsOnAsync(context: any, ...args: any[]): Stub; + + /** + * Causes the stub to asynchronously invoke a callback passed as a property of an object to the spy + */ + yieldsToAsync(property: string, ...args: any[]): Stub; + + /** + * Causes the stub to asynchronously invoke a callback passed as a property of an object to the spy on the given context + */ + yieldsToOnAsync(property: string, context: any, ...args: any[]): Stub; + + /** + * Stubs the method only for the provided arguments + */ + withArgs(...args: any[]): Stub; + } + + interface Expectation extends Stub { + /** + * Specifies the minimum amount of calls expected + */ + atLeast(n: number): Expectation; + + /** + * Specifies the maximum amount of calls expected + */ + atMost(n: number): Expectation; + + /** + * Expects the method to never be called + */ + never(): Expectation; + + /** + * Expects the method to be called exactly once + */ + once(): Expectation; + + /** + * Expects the method to be called exactly twice + */ + twice(): Expectation; + + /** + * Expects the method to be called exactly thrice + */ + thrice(): Expectation; + + /** + * Expects the method to be called exactly n times + */ + exactly(n: number): Expectation; + + /** + * Expects the method to be called with the provided arguments and possibly others + */ + withArgs(...args: any[]): Expectation; + + /** + * Expects the method to be called with the provided arguments and no others + */ + withExactArgs(...args: any[]): Expectation; + + /** + * Expects the method to be called with obj as this + */ + on(obj: any): Expectation; + + /** + * Verifies the expectation and throws an exception if it’s not met + */ + verify(): Expectation; + + /** + * Restores all mocked methods + */ + restore(): void; + } + + interface ExpectationStatic { + /** + * Creates a new expectation + */ + create(methodName?: string): Expectation; + } + + interface Mock { + /** + * Overrides obj.method with a mock function and returns it + */ + expects(method: string): Expectation; + + /** + * Restores all mocked methods + */ + restore(): void; + + /** + * Verifies all expectations on the mock + */ + verify(): void; + } + + interface ExposeOptions { + /** + * prefix to give assertions + */ + prefix?: string; + + /** + * Whether to copy the fail and failException properties + */ + includeFail?: boolean; + } + + interface Assert { + /** + * Default error type thrown by .fail + */ + failException: string; + + /** + * Every assertion fails by calling this method + */ + fail(message?: string): void; + + /** + * Called every time assertion passes + */ + pass(assertion: any): void; + + /** + * Passes if spy was never called + */ + notCalled(spy: Spy): void; + + /** + * Passes if spy was called at least once + */ + called(spy: Spy): void; + + /** + * Passes if spy was called once and only once + */ + calledOnce(spy: Spy): void; + + /** + * Passes if spy was called exactly twice + */ + calledTwice(spy: Spy): void; + + /** + * Passes if spy was called exactly three times + */ + calledThrice(spy: Spy): void; + + /** + * Passes if spy was called exactly count times + */ + callCount(spy: Spy, count: number): void; + + /** + * Passes if provided spies were called in the specified order + */ + callOrder(...spies: Spy[]): void; + + /** + * Passes if spy was ever called with obj as its this value + */ + calledOn(spy: Spy, obj: any): void; + + /** + * Passes if spy was always called with obj as its this value + */ + alwaysCalledOn(spy: Spy, obj: any): void; + + /** + * Passes if spy was called with the provided arguments + */ + calledWith(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was always called with the provided arguments + */ + alwaysCalledWith(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was never called with the provided arguments + */ + neverCalledWith(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was called with the provided arguments and no others + */ + calledWithExactly(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was always called with the provided arguments and no others + */ + alwaysCalledWithExactly(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was called with matching arguments. + */ + calledWithMatch(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was always called with matching arguments + */ + alwaysCalledWithMatch(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy was never called with matching arguments + */ + neverCalledWithMatch(spy: Spy, ...args: any[]): void; + + /** + * Passes if spy threw + */ + threw(spy: Spy): void; + + /** + * Passes if spy threw the given exception type + */ + threw(spy: Spy, exception: string): void; + + /** + * Passes if spy threw the given object + */ + threw(spy: Spy, exception: any): void; + + /** + * Passes if always spy threw + */ + alwaysThrew(spy: Spy): void; + + /** + * Passes if spy always threw the given exception type + */ + alwaysThrew(spy: Spy, exception: string): void; + + /** + * Passes if spy always threw the given object + */ + alwaysThrew(spy: Spy, exception: any): void; + + /** + * Exposes assertions into another object, to better integrate with the test framework + */ + expose(obj: any, options?: ExposeOptions): void; + } + + interface Matcher { + /** + * Logical and + */ + and(expr: Matcher): Matcher; + + /** + * Logical or + */ + or(expr: Matcher): Matcher; + } + + interface ArrayMatcher extends Matcher { + /** + * Requires an Array to be deep equal another one. + */ + deepEquals(expected: any[]): Matcher; + + /** + * Requires an Array to start with the same values as another one. + */ + startsWith(expected: any[]): Matcher; + + /** + * Requires an Array to end with the same values as another one. + */ + endsWith(expected: any[]): Matcher; + + /** + * Requires an Array to contain each one of the values the given array has. + */ + contains(expected: any[]): Matcher; + } + + interface MapMatcher extends Matcher { + /** + * Requires a Map to be deep equal another one. + */ + deepEquals(expected: Map): Matcher; + + /** + * Requires a Map to contain each one of the items the given map has. + */ + contains(expected: Map): Matcher; + } + + interface SetMatcher extends Matcher { + /** + * Requires a Set to be deep equal another one. + */ + deepEquals(expected: Set): Matcher; + + /** + * Requires a Set to contain each one of the items the given set has. + */ + contains(expected: Set): Matcher; + } + + interface Match { + /** + * Requires the value to be == to the given number + */ + (value: number): Matcher; + + /** + * Requires the value to be a string and have the expectation as a substring + */ + (value: string): Matcher; + + /** + * Requires the value to be a string and match the given regular expression + */ + (expr: RegExp): Matcher; + + /** + * Requires the value to be not null or undefined and have at least the same properties as expectation + */ + (obj: any): Matcher; + + /** + * Specify a custom matcher + */ + (callback: (value: any) => boolean, message?: string): Matcher; + + /** + * Matches anything + */ + any: Matcher; + + /** + * Requires the value to be defined + */ + defined: Matcher; + + /** + * Requires the value to be truthy + */ + truthy: Matcher; + + /** + * Requires the value to be falsy + */ + falsy: Matcher; + + /** + * Requires the value to be a boolean + */ + bool: Matcher; + + /** + * Requires the value to be a number + */ + number: Matcher; + + /** + * Requires the value to be a string + */ + string: Matcher; + + /** + * Requires the value to be an object + */ + object: Matcher; + + /** + * Requires the value to be a function + */ + func: Matcher; + + /** + * Requires the value to be a map. + */ + map: MapMatcher; + + /** + * Requires the value to be a set. + */ + set: SetMatcher; + + /** + * Requires the value to be an array. + */ + array: ArrayMatcher; + + /** + * Requires the value to be a regular expression + */ + regexp: Matcher; + + /** + * Requires the value to be a date object + */ + date: Matcher; + + /** + * Requires the value to be a symbol + */ + symbol: Matcher; + + /** + * Requires the value to strictly equal obj + */ + same(obj: any): Matcher; + + /** + * Requires the value to be of the given type + */ + typeOf(type: adone.util.I.PossibleTypes): Matcher; + typeOf(type: string): Matcher; + + /** + * Requires the value to be an instance of the given type + */ + instanceOf(type: any): Matcher; + + /** + * Requires the value to define the given property + */ + has(property: string, expect?: any): Matcher; + + /** + * Requires the value to define the given property by itself + */ + hasOwn(property: string, expect?: any): Matcher; + } + + interface SandboxConfig { + /** + * An object to add properties to + */ + injectInto?: any; + + /** + * What properties to inject + */ + properties?: string[]; + } + + interface Sandbox { + /** + * A convenience reference for assert + */ + assert: Assert; + + /** + * Works exactly like spy, only also adds the returned spy to the internal collection of fakes + */ + spy: typeof spy; + + /** + * Works exactly like stub, only also adds the returned spy to the internal collection of fakes + */ + stub: typeof stub; + + /** + * Works exactly like mock, only also adds the returned spy to the internal collection of fakes + */ + mock: typeof mock; + + /** + * Restores all fakes created through sandbox + */ + restore(): void; + + /** + * Resets the internal state of all fakes created through sandbox + */ + reset(): void; + + /** + * Resets the history of all stubs created through the sandbox + */ + resetHistory(): void; + + /** + * Resets the behaviour of all stubs created through the sandbox + */ + resetBehavior(): void; + + /** + * Causes all stubs created from the sandbox to return promises using a specific promise library + */ + usingPromise(promiseLibrary: any): Sandbox; + + /** + * Verifies all mocks created through the sandbox + */ + verify(): void; + + /** + * Verifies all mocks and restores all fakes created through the sandbox + */ + verifyAndRestore(): void; + } + + interface SandboxStatic { + /** + * Creates a sandbox object with spies, stubs, and mocks + */ + create(config?: SandboxConfig): Sandbox; + } } - interface ExpectBodyOptions { - decompress?: boolean; + /** + * Return a function that records arguments, return value, the value of this and exception thrown (if any) for all its calls + */ + function spy(func?: (...args: any[]) => void): I.Spy; + function spy(object: T, method: keyof T): I.Spy; + + /** + * Creates a function (spy) with pre-programmed behavior + */ + function stub(obj?: any): I.Stub; + function stub(obj: T, method: keyof T): I.Stub; + + const expectation: I.ExpectationStatic; + + /** + * Creates a fake method (like spy) with pre-programmed behavior (like stub) + */ + function mock(): I.Expectation; + function mock(obj: any): I.Mock; + + /** + * Assertions for spies/stubs + */ + export const assert: I.Assert; + + /** + * Creates a matcher function + */ + export const match: I.Match; + + /** + * Removes the need to keep track of every fake created + */ + export const sandbox: I.SandboxStatic; + + namespace I { + interface Response extends nodestd.http.IncomingMessage { + body: Buffer; + } + + interface ExpectBodyOptions { + decompress?: boolean; + } + + interface AttachOptions { + type?: string; + filename?: string; + } + + interface Request extends Promise { + /** + * Sets the request method to GET + */ + get(path: string): this; + + /** + * Sets the request method to HEAD + */ + head(path: string): this; + + /** + * Sets the request method to POST + */ + post(path: string): this; + + /** + * Attaches an attachment + */ + attach(name: string, contents: string | Buffer, options?: AttachOptions): this; + + /** + * Attaches an attachment like a field + */ + field(name: string, value: string): this; + + /** + * Sets the request body + */ + send(value: string): this; + + /** + * Sets the request method to OPTIONS + */ + options(path: string): this; + + /** + * Sets the request method to PUT + */ + put(path: string): this; + + /** + * Sets a header value + */ + setHeader(key: string, value: string): this; + + /** + * Sets the basic auth header + */ + auth(username: string, password: string): this; + + /** + * Executes a function with the response and asserts it returns true + */ + expect(fn: (response: Response) => boolean | Promise): this; + + /** + * Asserts the response status + */ + expectStatus(code: number, message?: string): this; + + /** + * Asserts the respose status message + */ + expectStatusMessage(value: string): this; + + /** + * Asserts the response body + */ + expectBody(body: RegExp | string | Buffer, options?: ExpectBodyOptions): this; + + /** + * Asserts the response json body + */ + expectBody(body: object, options?: ExpectBodyOptions): this; + + /** + * Asserts that the response body is empty + */ + expectEmptyBody(): this; + + /** + * Asserts that the response has a header with the given key and value + */ + expectHeader(key: string, value: string | RegExp): this; + + /** + * Asserts that the response has a header with the given name + */ + expectHeaderExists(key: string): this; + + /** + * Asserts that the response does not have a header with the given name + */ + expectNoHeader(key: string): this; + } } - interface AttachOptions { - type?: string; - filename?: string; + /** + * Assertion tool for http server responses + */ + function request(server: any): I.Request; // TODO: sever must be adone.net.http.server.Server or standard node.js server + + namespace FS { + // TODO: after fs } - interface Request extends Promise { - /** - * Sets the request method to GET - */ - get(path: string): this; - - /** - * Sets the request method to HEAD - */ - head(path: string): this; - - /** - * Sets the request method to POST - */ - post(path: string): this; - - /** - * Attaches an attachment - */ - attach(name: string, contents: string | Buffer, options?: AttachOptions): this; - - /** - * Attaches an attachment like a field - */ - field(name: string, value: string): this; - - /** - * Sets the request body - */ - send(value: string): this; - - /** - * Sets the request method to OPTIONS - */ - options(path: string): this; - - /** - * Sets the request method to PUT - */ - put(path: string): this; - - /** - * Sets a header value - */ - setHeader(key: string, value: string): this; - - /** - * Sets the basic auth header - */ - auth(username: string, password: string): this; - - /** - * Executes a function with the response and asserts it returns true - */ - expect(fn: (response: Response) => boolean | Promise): this; - - /** - * Asserts the response status - */ - expectStatus(code: number, message?: string): this; - - /** - * Asserts the respose status message - */ - expectStatusMessage(value: string): this; - - /** - * Asserts the response body - */ - expectBody(body: RegExp | string | Buffer, options?: ExpectBodyOptions): this; - - /** - * Asserts the response json body - */ - expectBody(body: object, options?: ExpectBodyOptions): this; - - /** - * Asserts that the response body is empty - */ - expectEmptyBody(): this; - - /** - * Asserts that the response has a header with the given key and value - */ - expectHeader(key: string, value: string | RegExp): this; - - /** - * Asserts that the response has a header with the given name - */ - expectHeaderExists(key: string): this; - - /** - * Asserts that the response does not have a header with the given name - */ - expectNoHeader(key: string): this; + namespace nock { + // TODO: after revision } } - - /** - * Assertion tool for http server responses - */ - function request(server: any): I.Request; // TODO: sever must be adone.net.http.server.Server or standard node.js server - - namespace FS { - // TODO: after fs - } - - namespace nock { - // TODO: after revision - } } } diff --git a/types/adone/glosses/std.d.ts b/types/adone/glosses/std.d.ts index 9c30b41f62..ec4bc4c37a 100644 --- a/types/adone/glosses/std.d.ts +++ b/types/adone/glosses/std.d.ts @@ -63,3 +63,5 @@ export { timers, dgram, }; + +export as namespace nodestd; diff --git a/types/adone/glosses/streams.d.ts b/types/adone/glosses/streams.d.ts new file mode 100644 index 0000000000..012a6aadc3 --- /dev/null +++ b/types/adone/glosses/streams.d.ts @@ -0,0 +1,223 @@ +declare namespace adone { + namespace stream { + namespace I.CoreStream { + interface ConstructorOptions { + /** + * Whether the initial stream is asynchronous + */ + async?: boolean; + + /** + * Whether the initial stream is synchronous + */ + sync?: boolean; + + /** + * The initial transform (passthrough is default) + */ + transform?: TransformFunction; + + /** + * The initial flush function + */ + flush?: FlushFunction; + } + + type Source = S[] | CoreStream; + + interface TransformContext { + /** + * Pushes the given value into the stream + */ + push(value: T): boolean; + } + + type TransformFunction = (this: TransformContext, value: S) => void; + type FlushFunction = (this: TransformContext) => void; + } + + /** + * Represents a chain of transform streams + */ + class CoreStream implements PromiseLike { + constructor(source?: I.CoreStream.Source, options?: I.CoreStream.ConstructorOptions); + + /** + * Writes the given value into the stream + */ + write(value: S): boolean; + + /** + * Pushes the given value into the stream + */ + push(value: T): boolean; + + /** + * Ends the stream + */ + end(): this; + + /** + * Destroys the stream + */ + destroy(): this; + + /** + * Pauses the stream + */ + pause(): this; + + /** + * Resumes the stream + */ + resume(): this; + + /** + * Whether the stream is paused + */ + isPaused(): boolean; + + /** + * Whether the stream is ended + */ + isEnded(): boolean; + + /** + * Pipes this stream to another + */ + pipe(stream: T, options?: { end?: boolean }): T; + + /** + * Adds a new synchronous transform stream into the chain + */ + throughSync(transform: I.CoreStream.TransformFunction, flush?: I.CoreStream.FlushFunction): CoreStream; + + /** + * Adds a new asynchronous transform stream into the chain + */ + throughAsync(transform: I.CoreStream.TransformFunction, flush?: I.CoreStream.FlushFunction): CoreStream; + + /** + * Adds a new transform stream into the chain + */ + through(transform: I.CoreStream.TransformFunction, flush?: I.CoreStream.FlushFunction): CoreStream; + + /** + * Adds a new map transform into the chain. + * + * Note: synchronous functions create a synchronous transform. + * If your function returns a promise use an asynchronous function if you don't want to pass a promise through the stream + */ + map(callback: (value: T) => R | Promise): CoreStream; + + /** + * Adds a new conditional map transform into the chain + */ + mapIf(condition: (value: T) => boolean | Promise, callback: (value: T) => R): CoreStream; + + /** + * Adds a new filter transform into the chain + */ + filter(callback: (value: T) => boolean | Promise): this; + + /** + * Adds a new transform that calls the given callback for each value from the stream. + * + * This method resumes the stream. + */ + forEach(callback: (value: T) => void, options?: { + /** + * Whethe to wait for asynchronous functions (await) + */ + wait?: boolean, + + /** + * Passthrough the read values, by default it eats everything + */ + passthrough?: boolean + }): this; + + /** + * Adds a new transform that calls the given callback when the underlying stream ends. + * + * This method resumes the stream. + */ + done(callback: () => void, options?: { + /** + * Passthrough the read values, by default it eats everything + */ + passthrough?: boolean + }): this; + + /** + * Adds a new transform that gather all the read values into an array and calls the given callback + * when the underlying stream ends. + * + * This method resumes the stream. + */ + toArray(callback: (result: T[]) => void, options?: { + /** + * Passthrough the read values, by default it eats everything + */ + passthrough?: boolean + }): this; + + /** + * Adds a new transform that filters the values by their uniqueness + * + * @param prop callback that calculates value's hash which is used in uniqueness checks + */ + unique(prop?: (value: T) => any): this; + + /** + * Adds a new transform that filters the values using the given given function with ability to restore the filtered values + */ + stash(name: string, filter: (value: T) => boolean): this; + stash(filter: (value: T) => boolean): this; + + /** + * Adds a new transform that restores the previous stashed values + */ + unstash(name?: string): CoreStream; // ?? + + /** + * Flattens all the read array values + */ + flatten(): CoreStream; // ?? + + /** + * Merges the given stream into a core stream + */ + static merge(streams: Array | nodestd.stream.Transform | nodestd.stream.Readable | nodestd.stream.Duplex>, options?: { + /** + * Whether to end the stream when all the given streams end + */ + end?: boolean, + + /** + * Options for the initial core stream + */ + sourceOptions?: I.CoreStream.ConstructorOptions + }): CoreStream; + + /** + * Creates a promise that will be fulfilled with an array of all the emitted values or the first occurred error. + * + * This method resumes the stream. + */ + then(onResolve?: (value: T[]) => T1 | PromiseLike, onReject?: (reason: any) => T2 | PromiseLike): Promise; + + /** + * Creates a promise that will be fulfilled with an array of all the emitted values or the first occurred error. + * + * This method resumes the stream. + */ + catch(onReject?: (reason: any) => T1 | PromiseLike): Promise; + } + + /** + * Creates a CoreStream instance + */ + function core(source?: I.CoreStream.Source, options?: I.CoreStream.ConstructorOptions): CoreStream; + } +} diff --git a/types/adone/glosses/utils.d.ts b/types/adone/glosses/utils.d.ts index 8f90ae180b..6a05273ffd 100644 --- a/types/adone/glosses/utils.d.ts +++ b/types/adone/glosses/utils.d.ts @@ -1,473 +1,576 @@ -/** - * various utility functions - */ -export namespace util { - function arrify(val: T[]): T[]; - function arrify(val: T): [T]; +declare namespace adone { + /** + * various utility functions + */ + namespace util { + function arrify(val: T[]): T[]; + function arrify(val: T): [T]; - function slice(args: T[], sliceStart?: number, sliceEnd?: number): T[]; + function slice(args: T[], sliceStart?: number, sliceEnd?: number): T[]; - function spliceOne(list: any[], index: number): void; + function spliceOne(list: any[], index: number): void; - function normalizePath(str: string, stripTrailing?: boolean): string; + function normalizePath(str: string, stripTrailing?: boolean): string; - function unixifyPath(filePath: string, unescape?: boolean): string; + function unixifyPath(filePath: string, unescape?: boolean): string; - function functionName(fn: (...args: any[]) => any): string; + function functionName(fn: (...args: any[]) => any): string; - function mapArguments(argmap: (...args: any[]) => any | any[]): (...args: any[]) => any; - function mapArguments(argmap: number): (...args: T[]) => T[]; - function mapArguments(...args: any[]): (x: T) => T; + function mapArguments(argmap: (...args: any[]) => any): (...args: any[]) => any; + function mapArguments(argmap: number): (...args: T[]) => T[]; + function mapArguments(...args: any[]): (x: T) => T; - namespace I { - interface ParseMsResult { - days: number; - hours: number; - minutes: number; - seconds: number; - milliseconds: number; - } - } - function parseMs(ms: number): I.ParseMsResult; - - function pluralizeWord(str: string, plural?: string, count?: number): string; - - function functionParams(func: (...args: any[]) => any): string[]; - - function randomChoice(arrayLike: ArrayLike, from?: number, to?: number): T; - - function shuffleArray(array: T[]): T[]; - - function enumerate(iterable: Iterable, start?: number): IterableIterator<[number, T]>; - - function zip(a: Iterable, b: Iterable): IterableIterator<[T1, T2]>; - function zip(a: Iterable, b: Iterable, c: Iterable): IterableIterator<[T1, T2, T3]>; - function zip(a: Iterable, b: Iterable, c: Iterable, d: Iterable): IterableIterator<[T1, T2, T3, T4]>; - function zip(...iterables: Array>): IterableIterator; - - namespace I { - interface KeysOptions { - onlyEnumerable?: boolean; - followProto?: boolean; - all?: boolean; - } - } - function keys(object: object, options?: I.KeysOptions): string[]; - - function values(object: object, options?: I.KeysOptions): any[]; - - function entries(object: object, options?: I.KeysOptions): Array; - - function toDotNotation(object: object): object; - - namespace I { - interface FlattenOptions { - depth?: number; - } - } - function flatten(array: any[], options?: I.FlattenOptions): any[]; - - function globParent(str: string): string; - - namespace I { - interface ByResult { - (a: S, b: S): R; - compare(a: T, b: T): R; - by(a: S): T; - } - } - function by(by: (a: S) => T, compare?: (a: T, b: T) => R): I.ByResult; - - function toFastProperties(object: object): object; - - function stripBom(x: string): string; - - namespace I { - interface SortKeysOptions { - deep?: boolean; - compare?(a: any, b: any): number; - } - } - function sortKeys(object: object, options?: I.SortKeysOptions): object; - - namespace I { - interface GlobizeOptions { - exts?: string; - recursively?: boolean; - } - } - function globize(path: string, options?: I.GlobizeOptions): string; - - function unique(array: T[], projection?: (a: T) => any): T[]; - - function invertObject(source: object, options?: I.KeysOptions): object; - - namespace I { - interface HumanizeTimeOptions { - msDecimalDigits?: number; - secDecimalDigits?: number; - verbose?: boolean; - compact?: boolean; - } - } - function humanizeTime(ms: number, options?: I.HumanizeTimeOptions): string; - function humanizeSize(num: number, space?: string): string; - - function parseSize(str: string | number): number | null; - - namespace I { - interface CloneOptions { - deep?: boolean; - } - } - function clone(object: object, options?: I.CloneOptions): object; - - function toUTF8Array(str: string): number[]; - - function asyncIter(array: T[], iter: (elem: T, index: number, cb: () => void) => any, cb: () => void): void; - - function asyncFor(obj: { [key: string]: T }, iter: (key: string, value: T, index: number, length: number, next: () => void) => void, cb: () => void): void; - - namespace I { - interface OnceOptions { - silent: boolean; - } - } - function once(fn: (...args: any[]) => T, options?: I.OnceOptions): (...args: any[]) => T; - - namespace I { - type WaterFallTask = (...args: any[]) => void; - } - function asyncWaterfall(tasks: I.WaterFallTask[], callback?: (err?: Error | null, ...args: any[]) => void): void; - - function xrange(start?: number, stop?: number, step?: number): IterableIterator; - - function range(start?: number, stop?: number, step?: number): number[]; - - function reFindAll(regexp: RegExp, str: string): RegExpExecArray[]; - - function assignDeep(target: T, ...sources: object[]): T; - - namespace I { - interface MatchOptions { - index?: boolean; - start?: number; - end?: number; - dot?: boolean; - } - } - function match(criteria: any | any[], options?: I.MatchOptions): (value: any | any[], options?: I.MatchOptions) => number | boolean; - function match(criteria: any | any[], value: any | any[], options?: I.MatchOptions): number | boolean; - - namespace I { - interface ToposortFunction { - (edges: Array<[T, T]>): T[]; - array(nodes: T[], edges: Array<[T, T]>): T[]; - } - } - const toposort: I.ToposortFunction; - - namespace I { - interface JSEscOptions { - escapeEverything?: boolean; - minimal?: boolean; - isScriptContext?: boolean; - quotes?: string; - wrap?: boolean; - es6?: boolean; - json?: boolean; - compact?: boolean; - lowercaseHex?: boolean; - numbers?: string; - indent?: string; - indentLevel?: number; - __inline1__?: boolean; - __inline2__?: boolean; - } - } - function jsesc(argument: any, options?: I.JSEscOptions): string; - - namespace I { - type PossibleTypes = "object" | "class" | "null" | "global" | "Array" | "RegExp" | "Date" - | "Promise" | "Set" | "Map" | "WeakSet" | "DataView" | "Map Iterator" | "Set Iterator" - | "Array Iterator" | "String Iterator" | "Object" | "function" | "boolean" | "number" - | "undefined" | "string" | "symbol"; - } - - function typeOf(obj: any): I.PossibleTypes; - function typeOf(obj: any): string; - - namespace memcpy { - function utou(target: Buffer, targetOffset: number, source: Buffer, sourceStart: number, sourceEnd: number): number; - function atoa(target: ArrayBuffer, targetOffset: number, source: ArrayBuffer, sourceStart: number, sourceEnd: number): number; - function atou(target: Buffer, targetOffset: number, source: ArrayBuffer, sourceStart: number, sourceEnd: number): number; - function utoa(target: ArrayBuffer, targetOffset: number, source: Buffer, sourceStart: number, sourceEnd: number): number; - function copy(target: Buffer | ArrayBuffer, targetOffset: number, source: Buffer | ArrayBuffer, sourceStart: number, sourceEnd: number): number; - } - - namespace uuid { namespace I { - interface V1Options { - clockseq?: number; - msecs?: number; - nsecs?: number; + interface ParseMsResult { + days: number; + hours: number; + minutes: number; + seconds: number; + milliseconds: number; } } - function v1(options?: I.V1Options): string; - function v1(options: I.V1Options, buf: any[], offset?: number): number[]; + function parseMs(ms: number): I.ParseMsResult; - function v4(options?: any): string; - function v4(options: any, buf: any[], offset?: number): number[]; + function pluralizeWord(str: string, plural?: string, count?: number): string; - function v5(name: string | number[], namespace: string | number[]): string; - function v5(name: string | number[], namespace: string | number[], buf: any[], offset?: number): number[]; - } + function functionParams(func: (...args: any[]) => any): string[]; - namespace I { - interface Delegator { - method(name: string): Delegator; - access(name: string): Delegator; - getter(name: string): Delegator; - setter(name: string): Delegator; - } - } - function delegate(object: object, property: string): I.Delegator; + function randomChoice(arrayLike: ArrayLike, from?: number, to?: number): T; - namespace I { - interface GlobExpOptions { - nocomment?: boolean; - nonegate?: boolean; - nobrace?: boolean; - noglobstar?: boolean; - nocase?: boolean; - dot?: boolean; - noext?: boolean; - matchBase?: boolean; - flipNegate?: boolean; - } - } + function shuffleArray(array: T[]): T[]; - class GlobExp { - constructor(pattern: string, options?: I.GlobExpOptions); + function enumerate(iterable: Iterable, start?: number): IterableIterator<[number, T]>; - hasMagic(): boolean; + function zip(a: Iterable, b: Iterable): IterableIterator<[T1, T2]>; + function zip(a: Iterable, b: Iterable, c: Iterable): IterableIterator<[T1, T2, T3]>; + function zip(a: Iterable, b: Iterable, c: Iterable, d: Iterable): IterableIterator<[T1, T2, T3, T4]>; + function zip(...iterables: Array>): IterableIterator; - static hasMagic(pattern: string, options?: I.GlobExpOptions): boolean; - - expandBraces(): string[]; - - static expandBraces(pattern: string, options?: I.GlobExpOptions): string[]; - - makeRe(): RegExp; - - static makeRe(pattern: string, options?: I.GlobExpOptions): RegExp; - - static test(p: string, pattern: string, options?: I.GlobExpOptions): boolean; - - test(p: string): boolean; - } - - namespace iconv { - // TODO: need to normalize source code - } - - namespace sqlstring { - function escapeId(val: string | string[], forbidQualified?: boolean): string; - function dateToString(date: any, timeZone?: string): string; - function arrayToList(array: any[]): string; - function bufferToString(buffer: Buffer): string; - function objectToValues(object: object, timeZone?: string): string; - function escape(value: any, stringifyObjects?: boolean, timeZone?: string): string; - function format(sql: string, values?: any | any[], stringifyObjects?: boolean, timeZone?: string): string; - } - - namespace I { - interface EditorOptions { - text?: string; - editor?: string; - path?: string; - ext?: string; - } - } - class Editor { - static DEFAULT: string; - - constructor(options?: I.EditorOptions); - - spawn(): Promise; - - run(): Promise; - - cleanup(): Promise; - - static edit(options?: I.EditorOptions): Promise; - } - - namespace I { - interface BinarySearchFunction { - (aHaystack: T[], aNeedle: number, aLow?: number, aHigh?: number, aCompare?: (a: T, b: T) => number, aBias?: number): T; - GREATEST_LOWER_BOUND: number; - LEAST_UPPER_BOUND: number; - } - } - const binarySearch: I.BinarySearchFunction; - - namespace buffer { - function concat(list: Buffer[], totalLength: number): Buffer; - function mask(buffer: Buffer, mask: Buffer, output: Buffer, offset: number, length: number): void; - function unmask(buffer: Buffer, mask: Buffer): void; - } - - function shebang(str: string): string | null; - - class ReInterval { - constructor(callback: (...args: any[]) => void, interval: number, args?: any[]); - - reschedule(interval: number): void; - - clear(): void; - - destroy(): void; - } - - class RateLimiter { - constructor(tokensPerInterval?: number, interval?: number, fireImmediately?: boolean); - - removeTokens(count: number): Promise; - - tryRemoveTokens(count: number): boolean; - - getTokensRemaining(): number; - } - - namespace I { - interface ThrottleOptions { - max?: number; - interval?: number; - ordered?: boolean; - waitForReturn?: boolean; - } - } - function throttle(fn: () => R, options?: I.ThrottleOptions): () => Promise; - function throttle(fn: (a: T1) => R, options?: I.ThrottleOptions): (a: T1) => Promise; - function throttle(fn: (a: T1, b: T2) => R, options?: I.ThrottleOptions): (a: T1, b: T2) => Promise; - function throttle(fn: (a: T1, b: T2, c: T3) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3) => Promise; - function throttle(fn: (a: T1, b: T2, c: T3, d: T4) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4) => Promise; - function throttle(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; - function throttle(fn: (...args: any[]) => R, options?: I.ThrottleOptions): (...args: any[]) => Promise; - - namespace I.fakeClock { - interface Timer { - id: number; - ref(): void; - unref(): void; - } - interface Clock { - setTimeout(func: (...args: any[]) => void, timeout: number, ...args: any[]): Timer; - clearTimeout(timer: Timer): void; - nextTick(func: (...args: any[]) => void, ...args: any[]): void; - setInterval(func: (...args: any[]) => void, ...args: any[]): Timer; - clearInterval(timer: Timer): void; - setImmediate(func: (...args: any[]) => void, ...args: any[]): Timer; - clearImmediate(timer: Timer): void; - updateHrTime(newNow: number): void; - tick(ms: number): number; - next(): number; - runAll(): number; - runToLast(): number; - setSystemTime(systemTime: number): void; - hrtime(prev?: [number, number]): [number, number]; - } - interface InstalledClock extends Clock { - uninstall(): void; - } - interface InstallOptions { - target?: object; - now?: number; - toFake?: string[]; - loopLimit?: number; - shouldAdvanceTime?: boolean; - advanceTimeDelta?: number; - } - - interface Timers { - setTimeout: typeof global.setTimeout; - clearTimeout: typeof global.clearTimeout; - setInterval: typeof global.setInterval; - clearInterval: typeof global.clearInterval; - setImmediate: typeof global.setImmediate; - clearImmediate: typeof global.clearImmediate; - Date: typeof global.Date; - hrtime: typeof global.process.hrtime; - nextTick: typeof global.process.nextTick; - } - - interface FakeClock { - timers: Timers; - createClock(now?: number, loopLimit?: number): Clock; - install(now?: number | Date | InstallOptions): InstalledClock; - } - } - - const fakeClock: I.fakeClock.FakeClock; - - namespace ltgt { namespace I { - interface Range { - lt?: T; - lte?: T; - gt?: T; - gte?: T; - min?: T; - max?: T; - start?: T; - end?: T; - reverse?: boolean; + interface KeysOptions { + onlyEnumerable?: boolean; + followProto?: boolean; + all?: boolean; } - type Comparator = (a: T, b: T) => number; } - function contains(range: I.Range, key: T, compare?: I.Comparator): boolean; + function keys(object: object, options?: I.KeysOptions): string[]; - function filter(range: I.Range, compare?: I.Comparator): (key: T) => boolean; + function values(object: object, options?: I.KeysOptions): any[]; - function toLtgt( - range: I.Range, - _range: object, - map?: (value: T, isUpperBound: boolean) => R, - lowerBound?: T, - upperBound?: T - ): I.Range; + function entries(object: object, options?: I.KeysOptions): Array<[string, any]>; - function endInclusive(range: I.Range): boolean; + function toDotNotation(object: object): object; - function startInclusive(range: I.Range): boolean; + namespace I { + interface FlattenOptions { + depth?: number; + } + } + function flatten(array: any[], options?: I.FlattenOptions): any[]; - function end(range: I.Range): T | undefined; + function globParent(str: string): string; - function end(range: I.Range, defaultValue: R): T | R; + namespace I { + interface ByResult { + (a: S, b: S): R; + compare(a: T, b: T): R; + by(a: S): T; + } + } + function by(by: (a: S) => T, compare?: (a: T, b: T) => R): I.ByResult; - function start(range: I.Range): T | undefined; + function toFastProperties(object: object): object; - function start(range: I.Range, defaultValue?: R): T | R; + function stripBom(x: string): string; - function upperBound(range: I.Range): T | undefined; + namespace I { + interface SortKeysOptions { + deep?: boolean; + compare?(a: any, b: any): number; + } + } + function sortKeys(object: object, options?: I.SortKeysOptions): object; - function upperBound(range: I.Range, defaultValue: R): T | R; + namespace I { + interface GlobizeOptions { + exts?: string; + recursively?: boolean; + } + } + function globize(path: string, options?: I.GlobizeOptions): string; - function upperBoundKey(range: I.Range): T | undefined; + function unique(array: T[], projection?: (a: T) => any): T[]; - function upperBoundExclusive(range: I.Range): boolean; + function invertObject(source: object, options?: I.KeysOptions): object; - function lowerBoundExclusive(range: I.Range): boolean; + namespace I { + interface HumanizeTimeOptions { + msDecimalDigits?: number; + secDecimalDigits?: number; + verbose?: boolean; + compact?: boolean; + } + } + function humanizeTime(ms: number, options?: I.HumanizeTimeOptions): string; + function humanizeSize(num: number, space?: string): string; - function upperBoundInclusive(range: I.Range): boolean; + function parseSize(str: string | number): number | null; - function lowerBoundInclusive(range: I.Range): boolean; + namespace I { + interface CloneOptions { + deep?: boolean; + } + } + function clone(object: object, options?: I.CloneOptions): object; - function lowerBound(range: I.Range): T | undefined; + function toUTF8Array(str: string): number[]; - function lowerBound(range: I.Range, defaultValue: R): T | R; + function asyncIter(array: T[], iter: (elem: T, index: number, cb: () => void) => any, cb: () => void): void; - function lowerBoundKey(range: I.Range): T | undefined; + function asyncFor(obj: { [key: string]: T }, iter: (key: string, value: T, index: number, length: number, next: () => void) => void, cb: () => void): void; + + namespace I { + interface OnceOptions { + silent: boolean; + } + } + function once(fn: (...args: any[]) => T, options?: I.OnceOptions): (...args: any[]) => T; + + namespace I { + type WaterFallTask = (...args: any[]) => void; + } + function asyncWaterfall(tasks: I.WaterFallTask[], callback?: (err?: Error | null, ...args: any[]) => void): void; + + function xrange(start?: number, stop?: number, step?: number): IterableIterator; + + function range(start?: number, stop?: number, step?: number): number[]; + + function reFindAll(regexp: RegExp, str: string): RegExpExecArray[]; + + function assignDeep(target: T, ...sources: object[]): T; + + namespace I { + interface MatchOptions { + index?: boolean; + start?: number; + end?: number; + dot?: boolean; + } + } + function match(criteria: any, options?: I.MatchOptions): (value: any, options?: I.MatchOptions) => number | boolean; + function match(criteria: any, value: any, options?: I.MatchOptions): number | boolean; + + namespace I { + interface ToposortFunction { + (edges: Array<[T, T]>): T[]; + array(nodes: T[], edges: Array<[T, T]>): T[]; + } + } + const toposort: I.ToposortFunction; + + namespace I { + interface JSEscOptions { + escapeEverything?: boolean; + minimal?: boolean; + isScriptContext?: boolean; + quotes?: string; + wrap?: boolean; + es6?: boolean; + json?: boolean; + compact?: boolean; + lowercaseHex?: boolean; + numbers?: string; + indent?: string; + indentLevel?: number; + __inline1__?: boolean; + __inline2__?: boolean; + } + } + function jsesc(argument: any, options?: I.JSEscOptions): string; + + namespace I { + type PossibleTypes = "object" | "class" | "null" | "global" | "Array" | "RegExp" | "Date" + | "Promise" | "Set" | "Map" | "WeakSet" | "DataView" | "Map Iterator" | "Set Iterator" + | "Array Iterator" | "String Iterator" | "Object" | "function" | "boolean" | "number" + | "undefined" | "string" | "symbol"; + } + + function typeOf(obj: any): I.PossibleTypes; + function typeOf(obj: any): string; + + namespace memcpy { + function utou(target: Buffer, targetOffset: number, source: Buffer, sourceStart: number, sourceEnd: number): number; + function atoa(target: ArrayBuffer, targetOffset: number, source: ArrayBuffer, sourceStart: number, sourceEnd: number): number; + function atou(target: Buffer, targetOffset: number, source: ArrayBuffer, sourceStart: number, sourceEnd: number): number; + function utoa(target: ArrayBuffer, targetOffset: number, source: Buffer, sourceStart: number, sourceEnd: number): number; + function copy(target: Buffer | ArrayBuffer, targetOffset: number, source: Buffer | ArrayBuffer, sourceStart: number, sourceEnd: number): number; + } + + namespace uuid { + namespace I { + interface V1Options { + clockseq?: number; + msecs?: number; + nsecs?: number; + } + } + function v1(options?: I.V1Options): string; + function v1(options: I.V1Options, buf: any[], offset?: number): number[]; + + function v4(options?: any): string; + function v4(options: any, buf: any[], offset?: number): number[]; + + function v3(name: string | number[], namespace: string | number[]): string; + function v3(name: string | number[], namespace: string | number[], buf: any[], offset?: number): number[]; + + function v5(name: string | number[], namespace: string | number[]): string; + function v5(name: string | number[], namespace: string | number[], buf: any[], offset?: number): number[]; + } + + namespace I { + interface Delegator { + method(name: string): Delegator; + access(name: string): Delegator; + getter(name: string): Delegator; + setter(name: string): Delegator; + } + } + function delegate(object: object, property: string): I.Delegator; + + namespace I { + interface GlobExpOptions { + nocomment?: boolean; + nonegate?: boolean; + nobrace?: boolean; + noglobstar?: boolean; + nocase?: boolean; + dot?: boolean; + noext?: boolean; + matchBase?: boolean; + flipNegate?: boolean; + } + } + + class GlobExp { + constructor(pattern: string, options?: I.GlobExpOptions); + + hasMagic(): boolean; + + static hasMagic(pattern: string, options?: I.GlobExpOptions): boolean; + + expandBraces(): string[]; + + static expandBraces(pattern: string, options?: I.GlobExpOptions): string[]; + + makeRe(): RegExp; + + static makeRe(pattern: string, options?: I.GlobExpOptions): RegExp; + + static test(p: string, pattern: string, options?: I.GlobExpOptions): boolean; + + test(p: string): boolean; + } + + namespace iconv { + // TODO: need to normalize source code + } + + namespace sqlstring { + function escapeId(val: string | string[], forbidQualified?: boolean): string; + function dateToString(date: any, timeZone?: string): string; + function arrayToList(array: any[]): string; + function bufferToString(buffer: Buffer): string; + function objectToValues(object: object, timeZone?: string): string; + function escape(value: any, stringifyObjects?: boolean, timeZone?: string): string; + function format(sql: string, values?: any, stringifyObjects?: boolean, timeZone?: string): string; + } + + namespace I { + interface EditorOptions { + text?: string; + editor?: string; + path?: string; + ext?: string; + } + } + class Editor { + static DEFAULT: string; + + constructor(options?: I.EditorOptions); + + spawn(): Promise; + + run(): Promise; + + cleanup(): Promise; + + static edit(options?: I.EditorOptions): Promise; + } + + namespace I { + interface BinarySearchFunction { + (aHaystack: T[], aNeedle: number, aLow?: number, aHigh?: number, aCompare?: (a: T, b: T) => number, aBias?: number): T; + GREATEST_LOWER_BOUND: number; + LEAST_UPPER_BOUND: number; + } + } + const binarySearch: I.BinarySearchFunction; + + namespace buffer { + function concat(list: Buffer[], totalLength: number): Buffer; + function mask(buffer: Buffer, mask: Buffer, output: Buffer, offset: number, length: number): void; + function unmask(buffer: Buffer, mask: Buffer): void; + } + + function shebang(str: string): string | null; + + class ReInterval { + constructor(callback: (...args: any[]) => void, interval: number, args?: any[]); + + reschedule(interval: number): void; + + clear(): void; + + destroy(): void; + } + + class RateLimiter { + constructor(tokensPerInterval?: number, interval?: number, fireImmediately?: boolean); + + removeTokens(count: number): Promise; + + tryRemoveTokens(count: number): boolean; + + getTokensRemaining(): number; + } + + namespace I { + interface ThrottleOptions { + max?: number; + interval?: number; + ordered?: boolean; + waitForReturn?: boolean; + } + } + function throttle(fn: () => R, options?: I.ThrottleOptions): () => Promise; + function throttle(fn: (a: T1) => R, options?: I.ThrottleOptions): (a: T1) => Promise; + function throttle(fn: (a: T1, b: T2) => R, options?: I.ThrottleOptions): (a: T1, b: T2) => Promise; + function throttle(fn: (a: T1, b: T2, c: T3) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3) => Promise; + function throttle(fn: (a: T1, b: T2, c: T3, d: T4) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4) => Promise; + function throttle(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise; + function throttle(fn: (...args: any[]) => R, options?: I.ThrottleOptions): (...args: any[]) => Promise; + + namespace I.fakeClock { + interface Timer { + id: number; + ref(): void; + unref(): void; + } + interface Clock { + setTimeout(func: (...args: any[]) => void, timeout: number, ...args: any[]): Timer; + clearTimeout(timer: Timer): void; + nextTick(func: (...args: any[]) => void, ...args: any[]): void; + setInterval(func: (...args: any[]) => void, ...args: any[]): Timer; + clearInterval(timer: Timer): void; + setImmediate(func: (...args: any[]) => void, ...args: any[]): Timer; + clearImmediate(timer: Timer): void; + updateHrTime(newNow: number): void; + tick(ms: number): number; + next(): number; + runAll(): number; + runToLast(): number; + setSystemTime(systemTime: number): void; + hrtime(prev?: [number, number]): [number, number]; + } + interface InstalledClock extends Clock { + uninstall(): void; + } + interface InstallOptions { + target?: object; + now?: number; + toFake?: string[]; + loopLimit?: number; + shouldAdvanceTime?: boolean; + advanceTimeDelta?: number; + } + + interface Timers { + setTimeout: typeof global.setTimeout; + clearTimeout: typeof global.clearTimeout; + setInterval: typeof global.setInterval; + clearInterval: typeof global.clearInterval; + setImmediate: typeof global.setImmediate; + clearImmediate: typeof global.clearImmediate; + Date: typeof global.Date; + hrtime: typeof global.process.hrtime; + nextTick: typeof global.process.nextTick; + } + + interface FakeClock { + timers: Timers; + createClock(now?: number, loopLimit?: number): Clock; + install(now?: number | Date | InstallOptions): InstalledClock; + } + } + + const fakeClock: I.fakeClock.FakeClock; + + namespace ltgt { + namespace I { + interface Range { + lt?: T; + lte?: T; + gt?: T; + gte?: T; + min?: T; + max?: T; + start?: T; + end?: T; + reverse?: boolean; + } + type Comparator = (a: T, b: T) => number; + } + function contains(range: I.Range, key: T, compare?: I.Comparator): boolean; + + function filter(range: I.Range, compare?: I.Comparator): (key: T) => boolean; + + function toLtgt( + range: I.Range, + _range: object, + map?: (value: T, isUpperBound: boolean) => R, + lowerBound?: T, + upperBound?: T + ): I.Range; + + function endInclusive(range: I.Range): boolean; + + function startInclusive(range: I.Range): boolean; + + function end(range: I.Range): T | undefined; + + function end(range: I.Range, defaultValue: R): T | R; + + function start(range: I.Range): T | undefined; + + function start(range: I.Range, defaultValue?: R): T | R; + + function upperBound(range: I.Range): T | undefined; + + function upperBound(range: I.Range, defaultValue: R): T | R; + + function upperBoundKey(range: I.Range): T | undefined; + + function upperBoundExclusive(range: I.Range): boolean; + + function lowerBoundExclusive(range: I.Range): boolean; + + function upperBoundInclusive(range: I.Range): boolean; + + function lowerBoundInclusive(range: I.Range): boolean; + + function lowerBound(range: I.Range): T | undefined; + + function lowerBound(range: I.Range, defaultValue: R): T | R; + + function lowerBoundKey(range: I.Range): T | undefined; + } + + /** + * Utils for uid/gid + */ + namespace userid { + /** + * Returns uid by the given username + */ + function uid(username: string): { uid: number, gid: number }; + + /** + * Returns gid by the given groupname + */ + function gid(groupname: string): number; + + /** + * Returns username by the given uid + */ + function username(uid: number): string; + + /** + * Returns groupname by the given gid + */ + function groupname(gid: number): string; + + /** + * Returns gids the given user belongs + */ + function gids(username: string): number[]; + } + + /** + * Represents a log file rotator + */ + class LogRotator { + /** + * @param target filepath + */ + constructor(target: string, options?: { + /** + * rotator reads file's stats with this delay + */ + checkInterval?: number | string, + /** + * maximum size of the file that triggers rotation + */ + maxSize?: number | string, + /** + * number of files at time + */ + maxFiles?: number, + /** + * compress old log files with gz + */ + compress?: boolean + }); + + /** + * Completes a rotate iteration + */ + rotate(): Promise; + + /** + * Starts checking using the given interval, the first check is completed on the next tick + */ + start(): void; + + /** + * Stops checking + */ + stop(): void; + } + + namespace I { + interface DebounceOptions { + /** + * whether to invoke on the leading edge + */ + leading?: boolean; + + /** + * whether to invoke on the trailing edge, if both are true the trailing call is performed only if the function is invoked more that once during the interval + */ + trailing?: boolean; + } + } + + /** + * Creates a function that delays invoking of the given function until after "timeout" ms + * have elapsed since the last invoking + */ + function debounce(fn: () => R, timeout: number, options?: I.DebounceOptions): () => R; + function debounce(fn: (a: T1) => R, timeout: number, options?: I.DebounceOptions): (a: T1) => R; + function debounce(fn: (a: T1, b: T2) => R, timeout: number, options?: I.DebounceOptions): (a: T1, b: T2) => R; + function debounce(fn: (a: T1, b: T2, c: T3) => R, timeout: number, options?: I.DebounceOptions): (a: T1, b: T2, c: T3) => R; + function debounce(fn: (a: T1, b: T2, c: T3, d: T4) => R, timeout: number, options?: I.DebounceOptions): (a: T1, b: T2, c: T3, d: T4) => R; + function debounce(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => R, timeout: number, options?: I.DebounceOptions): (a: T1, b: T2, c: T3, d: T4, e: T5) => R; + function debounce(fn: (...args: any[]) => R, timeout: number, options?: I.DebounceOptions): (...args: any[]) => R; } } diff --git a/types/adone/index.d.ts b/types/adone/index.d.ts index 663e8c8407..74883c2185 100644 --- a/types/adone/index.d.ts +++ b/types/adone/index.d.ts @@ -4,6 +4,27 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -import * as adone from "./adone"; +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// -export default adone; +declare const _adone: typeof adone; + +export { _adone as adone }; diff --git a/types/adone/test/glosses/archives.ts b/types/adone/test/glosses/archives.ts new file mode 100644 index 0000000000..2fc38fc8ba --- /dev/null +++ b/types/adone/test/glosses/archives.ts @@ -0,0 +1,292 @@ +namespace archivesTests { + const { archive } = adone; + + namespace tarTests { + const { tar } = archive; + + namespace rawPackStreamTests { + const { RawPackStream } = tar; + + new RawPackStream(); + new RawPackStream({}); + { + const a: nodestd.stream.Writable = new RawPackStream().entry({ + type: "file", + gid: 0, + mode: 10, + mtime: 10, + name: "path", + size: 10, + uid: 10 + }); + } + { + const a = new RawPackStream().entry({ + type: "symlink", + gid: 0, + mode: 10, + mtime: 10, + name: "path", + size: 10, + uid: 10 + }); + a.linkname; + } + { + const a: nodestd.stream.Writable = new RawPackStream().entry({ + type: "symlink", + gid: 0, + mode: 10, + mtime: 10, + name: "path", + size: 10, + uid: 10, + linkname: "/" + }); + } + { + const a: nodestd.stream.Writable = new RawPackStream().entry({ + type: "file", + gid: 0, + mode: 10, + mtime: 10, + name: "path", + size: 10, + uid: 10 + }, (err: any) => {}); + } + { + const a: nodestd.stream.Writable = new RawPackStream().entry({ + name: "path" + }, Buffer.from("hello")); + } + { + const a: nodestd.stream.Writable = new RawPackStream().entry({ + type: "file", + gid: 0, + mode: 10, + mtime: 10, + name: "path", + size: 10, + uid: 10 + }, Buffer.from("hello"), (err: any) => {}); + } + + new RawPackStream().finalize(); + + new RawPackStream().destroy(); + new RawPackStream().destroy(new Error()); + } + + namespace rawUnpackStreamTest { + const { RawUnpackStream } = tar; + + type Header = adone.archive.tar.I.Header; + type UnpackSourceStream = adone.archive.tar.I.UnpackSourceStream; + type RawUnpackStream = adone.archive.tar.RawUnpackStream; + + new RawUnpackStream(); + new RawUnpackStream().on("entry", (header: Header, stream: UnpackSourceStream, next) => { + { const a: string = header.type; } + { const a: string | undefined = header.linkname; } + { const a: number = header.mode; } + { const a: number = header.mtime; } + { const a: string = header.name; } + { const a: number = header.size; } + { const a: number = header.uid; } + { const a: number = header.gid; } + { const a: nodestd.stream.Readable = stream; } + { const a: RawUnpackStream = stream._parent; } + next(); + next(123); + }); + new RawUnpackStream().once("entry", (header: Header, stream: UnpackSourceStream, next) => { + { const a: string = header.type; } + { const a: string | undefined = header.linkname; } + { const a: number = header.mode; } + { const a: number = header.mtime; } + { const a: string = header.name; } + { const a: number = header.size; } + { const a: number = header.uid; } + { const a: number = header.gid; } + { const a: nodestd.stream.Readable = stream; } + { const a: RawUnpackStream = stream._parent; } + next(); + next(123); + }); + } + + namespace packStreamTests { + const { packStream } = tar; + type RawPackStream = adone.archive.tar.RawPackStream; + type Header = adone.archive.tar.I.Header; + + { const a: RawPackStream = packStream("."); } + { const a: RawPackStream = packStream(".", {}); } + { const a: RawPackStream = packStream(".", { dereference: true }); } + { const a: RawPackStream = packStream(".", { dmode: 0o777 }); } + { const a: RawPackStream = packStream(".", { entries: ["."] }); } + { const a: RawPackStream = packStream(".", { fmode: 0o777 }); } + { const a: RawPackStream = packStream(".", { ignore: (name: string) => true }); } + { const a: RawPackStream = packStream(".", { map: (header: Header) => header }); } + { const a: RawPackStream = packStream(".", { map: (header: Header) => undefined }); } + { const a: RawPackStream = packStream(".", { mapStream: (stream: nodestd.stream.Readable, header: Header) => stream }); } + { const a: RawPackStream = packStream(".", { mapStream: (stream: nodestd.stream.Readable, header: Header) => stream }); } + { const a: RawPackStream = packStream(".", { pack: new tar.RawPackStream() }); } + { const a: RawPackStream = packStream(".", { readable: false }); } + { const a: RawPackStream = packStream(".", { sort: true }); } + { const a: RawPackStream = packStream(".", { strict: false }); } + { const a: RawPackStream = packStream(".", { strip: 2 }); } + { const a: RawPackStream = packStream(".", { umask: 2 }); } + { const a: RawPackStream = packStream(".", { writable: false }); } + } + + namespace unpackStreamTests { + const { unpackStream } = tar; + type RawUnpackStream = adone.archive.tar.RawUnpackStream; + type UnpackSourceStream = adone.archive.tar.I.UnpackSourceStream; + type Header = adone.archive.tar.I.Header; + + { const a: RawUnpackStream = unpackStream("."); } + { const a: RawUnpackStream = unpackStream(".", {}); } + { const a: RawUnpackStream = unpackStream(".", { chown: false }); } + { const a: RawUnpackStream = unpackStream(".", { dmode: 0o777 }); } + { const a: RawUnpackStream = unpackStream(".", { unpack: new tar.RawUnpackStream() }); } + { const a: RawUnpackStream = unpackStream(".", { fmode: 0o755 }); } + { const a: RawUnpackStream = unpackStream(".", { hardlinkAsFilesFallback: false }); } + { const a: RawUnpackStream = unpackStream(".", { ignore: (name: string) => true }); } + { const a: RawUnpackStream = unpackStream(".", { map: (header: Header) => header }); } + { const a: RawUnpackStream = unpackStream(".", { map: (header: Header) => undefined }); } + { const a: RawUnpackStream = unpackStream(".", { mapStream: (stream: UnpackSourceStream, header) => stream }); } + { const a: RawUnpackStream = unpackStream(".", { readable: false }); } + { const a: RawUnpackStream = unpackStream(".", { strip: 2 }); } + { const a: RawUnpackStream = unpackStream(".", { umask: 2 }); } + { const a: RawUnpackStream = unpackStream(".", { utimes: false }); } + { const a: RawUnpackStream = unpackStream(".", { writable: false }); } + } + } + + namespace zipTests { + const { zip } = archive; + + namespace packTests { + const { fs } = adone; + const { pack } = zip; + type ZipFile = adone.archive.zip.pack.ZipFile; + + const file = new pack.ZipFile(); + { const a: ZipFile = file.addBuffer(Buffer.from("buffer"), "file"); } + { const a: ZipFile = file.addBuffer(Buffer.from("buffer"), "file", {}); } + { const a: ZipFile = file.addBuffer(Buffer.from("buffer"), "file", { compress: true }); } + { const a: ZipFile = file.addBuffer(Buffer.from("buffer"), "file", { forceZip64Format: true }); } + { const a: ZipFile = file.addBuffer(Buffer.from("buffer"), "file", { mode: 0 }); } + { const a: ZipFile = file.addBuffer(Buffer.from("buffer"), "file", { mtime: 0 }); } + + { const a: ZipFile = file.addEmptyDirectory("hello"); } + { const a: ZipFile = file.addEmptyDirectory("hello", {}); } + { const a: ZipFile = file.addEmptyDirectory("hello", { mode: 0 }); } + { const a: ZipFile = file.addEmptyDirectory("hello", { mtime: 0 }); } + + { const a: ZipFile = file.addFile("hello", "hello"); } + { const a: ZipFile = file.addFile("hello", "hello", {}); } + { const a: ZipFile = file.addFile("hello", "hello", { compress: true }); } + { const a: ZipFile = file.addFile("hello", "hello", { forceZip64Format: false }); } + { const a: ZipFile = file.addFile("hello", "hello", { mode: 0o111 }); } + { const a: ZipFile = file.addFile("hello", "hello", { mtime: 13 }); } + + { const a: ZipFile = file.addReadStream(fs.createReadStream("a"), "hello"); } + { const a: ZipFile = file.addReadStream(fs.createReadStream("a"), "hello", {}); } + { const a: ZipFile = file.addReadStream(fs.createReadStream("a"), "hello", { compress: true }); } + { const a: ZipFile = file.addReadStream(fs.createReadStream("a"), "hello", { forceZip64Format: false }); } + { const a: ZipFile = file.addReadStream(fs.createReadStream("a"), "hello", { mode: 0 }); } + { const a: ZipFile = file.addReadStream(fs.createReadStream("a"), "hello", { mtime: 0 }); } + { const a: ZipFile = file.addReadStream(fs.createReadStream("a"), "hello", { size: 0 }); } + + { const a: nodestd.stream.Readable = file.outputStream; } + file.end().then((x: number) => {}); + } + + namespace unpackTests { + const { unpack } = zip; + const { fs } = adone; + type ZipFile = adone.archive.zip.unpack.I.ZipFile; + type Entry = adone.archive.zip.unpack.I.Entry; + + { + const a: ZipFile = unpack.open("hello"); + { const b: boolean = a.isOpen; } + { const b: number = a.entryCount; } + { const b: string = a.comment; } + a.close(); + a.readEntry().then((x) => {}); + a.on("entry", async (entry: Entry) => { + { const a: number = entry.versionMadeBy; } + { const a: number = entry.versionNeededToExtract; } + { const a: number = entry.generalPurposeBitFlag; } + { const a: number = entry.compressionMethod; } + { const a: number = entry.lastModFileDate; } + { const a: number = entry.lastModFileTime; } + { const a: number = entry.crc32; } + { const a: number = entry.compressedSize; } + { const a: number = entry.uncompressedSize; } + { const a: number = entry.fileNameLength; } + { const a: number = entry.extraFieldLength; } + { const a: number = entry.fileCommentLength; } + { const a: number = entry.internalFileAttributes; } + { const a: number = entry.externalFileAttributes; } + { const a: number = entry.relativeOffsetOfLocalHeader; } + { const a: Array<{ id: number, data: Buffer }> = entry.extraFields; } + { const a: string = entry.fileComment; } + { const a: string = entry.fileName; } + { const a: adone.I.datetime.Datetime = entry.getLastModDate(); } + { const a: boolean = entry.isEncrypted(); } + { const a: boolean = entry.isCompressed(); } + { const stream: nodestd.stream.Readable = await a.openReadStream(entry); } + { const stream: nodestd.stream.Readable = await a.openReadStream(entry, {}); } + { const stream: nodestd.stream.Readable = await a.openReadStream(entry, { decompress: true }); } + { const stream: nodestd.stream.Readable = await a.openReadStream(entry, { decrypt: false }); } + { const stream: nodestd.stream.Readable = await a.openReadStream(entry, { end: 0 }); } + { const stream: nodestd.stream.Readable = await a.openReadStream(entry, { start: 0 }); } + }); + a.on("end", () => {}); + a.on("close", () => {}); + a.on("error", (e: any) => {}); + } + { + const a: ZipFile = unpack.open("hello", { decodeStrings: false }); + { const b: Buffer = a.comment; } + a.on("entry", (entry: Entry) => { + { const a: Buffer = entry.fileComment; } + { const a: Buffer = entry.fileName; } + }); + } + + { const a: ZipFile = unpack.open("hello", {}); } + { const a: ZipFile = unpack.open("hello", { autoClose: true }); } + { const a: ZipFile = unpack.open("hello", { lazyEntries: true }); } + { const a: ZipFile = unpack.open("hello", { validateEntrySizes: false }); } + + { const a: ZipFile = unpack.fromBuffer(Buffer.from("123")); } + { const a: ZipFile = unpack.fromBuffer(Buffer.from("123"), {}); } + { const a: ZipFile = unpack.fromBuffer(Buffer.from("123"), { decodeStrings: false }); } + { const a: ZipFile = unpack.fromBuffer(Buffer.from("123"), { lazyEntries: false }); } + { const a: ZipFile = unpack.fromBuffer(Buffer.from("123"), { validateEntrySizes: false }); } + + { const a: ZipFile = unpack.fromFd(0); } + { const a: ZipFile = unpack.fromFd(0, {}); } + { const a: ZipFile = unpack.fromFd(0, { autoClose: false }); } + { const a: ZipFile = unpack.fromFd(0, { decodeStrings: false }); } + { const a: ZipFile = unpack.fromFd(0, { lazyEntries: true }); } + { const a: ZipFile = unpack.fromFd(0, { validateEntrySizes: false }); } + + { const a: ZipFile = unpack.fromRandomAccessReader(new fs.RandomAccessBufferReader(Buffer.from("asd")), 1); } + { const a: ZipFile = unpack.fromRandomAccessReader(new fs.RandomAccessBufferReader(Buffer.from("asd")), 1, {}); } + { const a: ZipFile = unpack.fromRandomAccessReader(new fs.RandomAccessBufferReader(Buffer.from("asd")), 1, { autoClose: false }); } + { const a: ZipFile = unpack.fromRandomAccessReader(new fs.RandomAccessBufferReader(Buffer.from("asd")), 1, { decodeStrings: false }); } + { const a: ZipFile = unpack.fromRandomAccessReader(new fs.RandomAccessBufferReader(Buffer.from("asd")), 1, { lazyEntries: false }); } + { const a: ZipFile = unpack.fromRandomAccessReader(new fs.RandomAccessBufferReader(Buffer.from("asd")), 1, { validateEntrySizes: false }); } + + { const a: string | null = unpack.validateFileName("hello"); } + } + } +} diff --git a/types/adone/test/glosses/collections.ts b/types/adone/test/glosses/collections.ts new file mode 100644 index 0000000000..ec227d4440 --- /dev/null +++ b/types/adone/test/glosses/collections.ts @@ -0,0 +1,1003 @@ +namespace collectionTests { + const { collection } = adone; + + namespace linkedListTests { + const { LinkedList } = collection; + + namespace creation { + new LinkedList(); + new LinkedList(10); + } + + namespace properties { + { const a: boolean = new LinkedList().full; } + { const a: boolean = new LinkedList().empty; } + { const a: number = new LinkedList().maxLength; } + { const a: number = new LinkedList().length; } + { const a: boolean = new LinkedList().autoresize; } + } + + namespace resize { + { const a: boolean = new LinkedList().resize(100).full; } + } + + namespace push { + const a = new LinkedList().push(10); + a.next; + a.prev; + const b: number = a.value; + } + + namespace pop { + const a: number | undefined = new LinkedList().pop(); + } + + namespace shift { + const a: number | undefined = new LinkedList().shift(); + } + + namespace unshift { + const a = new LinkedList().unshift("hello"); + a.next; + a.prev; + const b: string = a.value; + } + + namespace pushNode { + const a = new LinkedList(); + const node = a.push("1230"); + a.pushNode(node); + } + + namespace unshiftNode { + const a = new LinkedList(); + const node = a.push(10); + a.unshiftNode(node); + } + + namespace removeNode { + const a = new LinkedList(); + const node = a.unshift("10"); + a.removeNode(node); + } + + namespace clear { + new LinkedList().clear(); + new LinkedList().clear(true); + } + + namespace toArray { + const a = new LinkedList(); + const b: number[] = a.toArray(); + } + + namespace front { + const a = new LinkedList(); + const b: number = a.front; + } + + namespace back { + const a = new LinkedList(); + const b: number = a.back; + } + + namespace iterating { + const a = new LinkedList(); + for (const b of a) { + const i: string = b; + } + const c = new LinkedList(); + for (const b of c) { + const i: number = b; + } + } + + namespace nextNode { + const a = new LinkedList(); + const n1 = a.push("h"); + const n2 = a.nextNode(n1); + n1.next; + n1.prev; + const t: string = n1.value; + } + + namespace map { + const a = new LinkedList(); + const f = (a: number, idx: number) => `${a}${idx}`; + const b = a.map(f); + const c: string = b.front; + } + + namespace forEach { + const a = new LinkedList(); + + a.forEach((a: number, b: number) => { + const c = a + b; + }); + } + + namespace static { + const a: number = LinkedList.DEFAULT_LENGTH; + } + } + + namespace ByteArrayTests { + const { ByteArray } = collection; + + new ByteArray(); + new ByteArray(10); + new ByteArray(10, true); + + const buffer = new ByteArray(); + + namespace readBitSet { + const a: boolean[] = buffer.readBitSet(); + const b: boolean[] = buffer.readBitSet(10); + } + + namespace read { + const a: adone.collection.ByteArray = buffer.read(1); + const b: adone.collection.ByteArray = buffer.read(1, 10); + } + + namespace readInt8 { + const a: number = buffer.readInt8(); + const b: number = buffer.readInt8(10); + } + + namespace readUInt8 { + const a: number = buffer.readUInt8(); + const b: number = buffer.readUInt8(10); + } + + namespace readInt16LE { + const a: number = buffer.readInt16LE(); + const b: number = buffer.readInt16LE(10); + } + + namespace readUInt16LE { + const a: number = buffer.readUInt16LE(); + const b: number = buffer.readUInt16LE(10); + } + + namespace readInt16BE { + const a: number = buffer.readInt16BE(); + const b: number = buffer.readInt16BE(10); + } + + namespace readUInt16BE { + const a: number = buffer.readUInt16BE(); + const b: number = buffer.readUInt16BE(10); + } + + namespace readInt32LE { + const a: number = buffer.readInt32LE(); + const b: number = buffer.readInt32LE(10); + } + + namespace readUInt32LE { + const a: number = buffer.readUInt32LE(); + const b: number = buffer.readUInt32LE(10); + } + + namespace readInt32BE { + const a: number = buffer.readInt32BE(); + const b: number = buffer.readInt32BE(10); + } + + namespace readUInt32BE { + const a: number = buffer.readUInt32BE(); + const b: number = buffer.readUInt32BE(10); + } + + namespace readInt64LE { + const a: adone.math.Long = buffer.readInt64LE(); + const b: adone.math.Long = buffer.readInt64LE(10); + } + + namespace readUInt64LE { + const a: adone.math.Long = buffer.readUInt64LE(); + const b: adone.math.Long = buffer.readUInt64LE(10); + } + + namespace readInt64BE { + const a: adone.math.Long = buffer.readInt64BE(); + const b: adone.math.Long = buffer.readInt64BE(10); + } + + namespace readUInt64BE { + const a: adone.math.Long = buffer.readUInt64BE(); + const b: adone.math.Long = buffer.readUInt64BE(10); + } + + namespace readFloatLE { + const a: number = buffer.readFloatLE(); + const b: number = buffer.readFloatLE(10); + } + + namespace readFloatBE { + const a: number = buffer.readFloatBE(); + const b: number = buffer.readFloatBE(10); + } + + namespace readDoubleLE { + const a: number = buffer.readDoubleLE(); + const b: number = buffer.readDoubleLE(10); + } + + namespace readDoubleBE { + const a: number = buffer.readDoubleBE(); + const b: number = buffer.readDoubleBE(10); + } + + namespace write { + const a: adone.collection.ByteArray = buffer.write("1"); + const b: adone.collection.ByteArray = buffer.write(new ByteArray()); + const c: adone.collection.ByteArray = buffer.write(Buffer.alloc(10)); + const d: adone.collection.ByteArray = buffer.write(new Uint8Array([1, 2, 3])); + const e: adone.collection.ByteArray = buffer.write(new ArrayBuffer(10)); + const f: adone.collection.ByteArray = buffer.write("1", 10); + const g: adone.collection.ByteArray = buffer.write("1", 10, 10); + const h: adone.collection.ByteArray = buffer.write("1", 10, 10, "utf8"); + } + + namespace writeBitSet { + const a: adone.collection.ByteArray = buffer.writeBitSet([1, 2, 3]); + const b: number = buffer.writeBitSet([1, 2, 3], 10); + } + + namespace writeInt8 { + const a: adone.collection.ByteArray = buffer.writeInt8(10); + const b: adone.collection.ByteArray = buffer.writeInt8(10, 10); + } + + namespace writeUInt8 { + const a: adone.collection.ByteArray = buffer.writeUInt8(10); + const b: adone.collection.ByteArray = buffer.writeUInt8(10, 10); + } + + namespace writeInt16LE { + const a: adone.collection.ByteArray = buffer.writeInt16LE(10); + const b: adone.collection.ByteArray = buffer.writeInt16LE(10, 10); + } + + namespace writeInt16BE { + const a: adone.collection.ByteArray = buffer.writeInt16BE(10); + const b: adone.collection.ByteArray = buffer.writeInt16BE(10, 10); + } + + namespace writeUInt16LE { + const a: adone.collection.ByteArray = buffer.writeUInt16LE(10); + const b: adone.collection.ByteArray = buffer.writeUInt16LE(10, 10); + } + + namespace writeUInt16BE { + const a: adone.collection.ByteArray = buffer.writeUInt16BE(10); + const b: adone.collection.ByteArray = buffer.writeUInt16BE(10, 10); + } + + namespace writeInt32LE { + const a: adone.collection.ByteArray = buffer.writeInt32LE(10); + const b: adone.collection.ByteArray = buffer.writeInt32LE(10, 10); + } + + namespace writeInt32BE { + const a: adone.collection.ByteArray = buffer.writeInt32BE(10); + const b: adone.collection.ByteArray = buffer.writeInt32BE(10, 10); + } + + namespace writeUInt32LE { + const a: adone.collection.ByteArray = buffer.writeUInt32LE(10); + const b: adone.collection.ByteArray = buffer.writeUInt32LE(10, 10); + } + + namespace writeUInt32BE { + const a: adone.collection.ByteArray = buffer.writeUInt32BE(10); + const b: adone.collection.ByteArray = buffer.writeUInt32BE(10, 10); + } + + namespace writeInt64LE { + const a: adone.collection.ByteArray = buffer.writeInt64LE(10); + const b: adone.collection.ByteArray = buffer.writeInt64LE(10, 10); + } + + namespace writeInt64BE { + const a: adone.collection.ByteArray = buffer.writeInt64BE(10); + const b: adone.collection.ByteArray = buffer.writeInt64BE(10, 10); + } + + namespace writeUInt64LE { + const a: adone.collection.ByteArray = buffer.writeUInt64LE(10); + const b: adone.collection.ByteArray = buffer.writeUInt64LE(10, 10); + } + + namespace writeUInt64BE { + const a: adone.collection.ByteArray = buffer.writeUInt64BE(10); + const b: adone.collection.ByteArray = buffer.writeUInt64BE(10, 10); + } + + namespace writeFloatLE { + const a: adone.collection.ByteArray = buffer.writeFloatLE(10); + const b: adone.collection.ByteArray = buffer.writeFloatLE(10, 10); + } + + namespace writeFloatBE { + const a: adone.collection.ByteArray = buffer.writeFloatBE(10); + const b: adone.collection.ByteArray = buffer.writeFloatBE(10, 10); + } + + namespace writeDoubleLE { + const a: adone.collection.ByteArray = buffer.writeDoubleLE(10); + const b: adone.collection.ByteArray = buffer.writeDoubleLE(10, 10); + } + + namespace writeDoubleBE { + const a: adone.collection.ByteArray = buffer.writeDoubleBE(10); + const b: adone.collection.ByteArray = buffer.writeDoubleBE(10, 10); + } + + namespace writeVarInt32 { + const a: adone.collection.ByteArray = buffer.writeVarint32(10); + const b: number = buffer.writeVarint32(10, 10); + } + + namespace writeVarInt32ZigZag { + const a: adone.collection.ByteArray = buffer.writeVarint32ZigZag(10); + const b: number = buffer.writeVarint32ZigZag(10, 10); + } + + namespace readVarint32 { + const a: number = buffer.readVarint32(); + const b: { value: number, length: number } = buffer.readVarint32(10); + } + + namespace readVarint32ZigZag { + const a: number = buffer.readVarint32ZigZag(); + const b: { value: number, length: number } = buffer.readVarint32ZigZag(10); + } + + namespace writeVarint64 { + const a: adone.collection.ByteArray = buffer.writeVarint64(10); + const b: number = buffer.writeVarint64(10, 10); + } + + namespace writeVarint64ZigZag { + const a: adone.collection.ByteArray = buffer.writeVarint64ZigZag(10); + const b: number = buffer.writeVarint64ZigZag(10, 10); + } + + namespace readVarint64 { + const a: adone.math.Long = buffer.readVarint64(); + const b: { value: adone.math.Long, length: number } = buffer.readVarint64(10); + } + + namespace readVarint64ZigZag { + const a: adone.math.Long = buffer.readVarint64ZigZag(); + const b: { value: adone.math.Long, length: number } = buffer.readVarint64ZigZag(10); + } + + namespace writeCString { + const a: adone.collection.ByteArray = buffer.writeCString("asd"); + const b: number = buffer.writeCString("123", 10); + } + + namespace readCString { + const a: string = buffer.readCString(); + const b: { string: string, length: number } = buffer.readCString(10); + } + + namespace writeString { + const a: adone.collection.ByteArray = buffer.writeString("abc"); + const b: number = buffer.writeString("abc", 10); + } + + namespace readString { + const a: string = buffer.readString(10); + const b: string = buffer.readString(10, "b"); + const c: string = buffer.readString(10, "c"); + const d: { string: string, length: number } = buffer.readString(10, "c", 10); + } + + namespace writeVString { + const a: adone.collection.ByteArray = buffer.writeVString("abc"); + const b: number = buffer.writeVString("abc", 10); + } + + namespace readVString { + const a: string = buffer.readVString(); + const b: { string: string, length: number } = buffer.readVString(10); + } + + namespace appendTo { + const a: adone.collection.ByteArray = buffer.appendTo(new ByteArray()); + const b: adone.collection.ByteArray = buffer.appendTo(new ByteArray(), 10); + } + + namespace assert { + const a: adone.collection.ByteArray = buffer.assert(); + const b: adone.collection.ByteArray = buffer.assert(true); + } + + namespace capacity { + const a: number = buffer.capacity(); + } + + namespace clear { + const a: adone.collection.ByteArray = buffer.clear(); + } + + namespace copy { + const a: adone.collection.ByteArray = buffer.clone(); + const c: adone.collection.ByteArray = buffer.clone(true); + } + + namespace compact { + const a: adone.collection.ByteArray = buffer.compact(); + const b: adone.collection.ByteArray = buffer.compact(1); + const c: adone.collection.ByteArray = buffer.compact(1, 10); + } + + namespace copyTo { + const a: adone.collection.ByteArray = buffer.copyTo(new ByteArray()); + const b: adone.collection.ByteArray = buffer.copyTo(new ByteArray(), 0); + const c: adone.collection.ByteArray = buffer.copyTo(new ByteArray(), 0, 0); + const d: adone.collection.ByteArray = buffer.copyTo(new ByteArray(), 0, 0, 10); + } + + namespace ensureCapacity { + const a: adone.collection.ByteArray = buffer.ensureCapacity(10); + } + + namespace fill { + const a: adone.collection.ByteArray = buffer.fill("0"); + const b: adone.collection.ByteArray = buffer.fill(0); + const c: adone.collection.ByteArray = buffer.fill(0, 0); + const d: adone.collection.ByteArray = buffer.fill(0, 0, 10); + } + + namespace flip { + const a: adone.collection.ByteArray = buffer.flip(); + } + + namespace mark { + const a: adone.collection.ByteArray = buffer.mark(); + const b: adone.collection.ByteArray = buffer.mark(10); + } + + namespace prepend { + const a: adone.collection.ByteArray = buffer.prepend(""); + const b: adone.collection.ByteArray = buffer.prepend(new ByteArray()); + const c: adone.collection.ByteArray = buffer.prepend(Buffer.alloc(10)); + const d: adone.collection.ByteArray = buffer.prepend(new Uint8Array([1, 2, 3])); + const e: adone.collection.ByteArray = buffer.prepend(new ArrayBuffer(10)); + const f: adone.collection.ByteArray = buffer.prepend("", "utf8"); + const g: adone.collection.ByteArray = buffer.prepend("", "utf8", 10); + const h: adone.collection.ByteArray = buffer.prepend("", 10); + } + + namespace prependTo { + const a: adone.collection.ByteArray = buffer.prependTo(new ByteArray()); + const b: adone.collection.ByteArray = buffer.prependTo(new ByteArray(), 10); + } + + namespace remaining { + const a: number = buffer.remaining(); + } + + namespace reset { + const a: adone.collection.ByteArray = buffer.reset(); + } + + namespace resize { + const a: adone.collection.ByteArray = buffer.resize(10); + } + + namespace reverse { + const a: adone.collection.ByteArray = buffer.reverse(); + const b: adone.collection.ByteArray = buffer.reverse(1); + const c: adone.collection.ByteArray = buffer.reverse(1, 10); + } + + namespace skip { + const a: adone.collection.ByteArray = buffer.skip(10); + } + + namespace slice { + const a: adone.collection.ByteArray = buffer.slice(); + const b: adone.collection.ByteArray = buffer.slice(1); + const c: adone.collection.ByteArray = buffer.slice(1, 10); + } + + namespace toBuffer { + const a: Buffer = buffer.toBuffer(); + const b: Buffer = buffer.toBuffer(true); + const c: Buffer = buffer.toBuffer(true, 0); + const d: Buffer = buffer.toBuffer(true, 0, 10); + } + + namespace toArrayBuffer { + const a: ArrayBuffer = buffer.toArrayBuffer(); + } + + namespace toString { + const a: string = buffer.toString(); + const b: string = buffer.toString("utf8"); + const c: string = buffer.toString("utf8", 0); + const d: string = buffer.toString("utf8", 0, 10); + } + + namespace toBase64 { + const a: string = buffer.toBase64(); + const b: string = buffer.toBase64(0); + const c: string = buffer.toBase64(0, 10); + } + + namespace toBinary { + const a: string = buffer.toBinary(); + const b: string = buffer.toBinary(0); + const c: string = buffer.toBinary(0, 10); + } + + namespace toDebug { + const a: string = buffer.toDebug(); + const b: string = buffer.toDebug(true); + } + + namespace toUTF8 { + const a: string = buffer.toUTF8(); + const b: string = buffer.toUTF8(0); + const c: string = buffer.toUTF8(0, 10); + } + + namespace static { + namespace accessor { + const a: typeof Buffer = ByteArray.accessor(); + } + + namespace allocate { + const a: adone.collection.ByteArray = ByteArray.allocate(); + const b: adone.collection.ByteArray = ByteArray.allocate(10); + const c: adone.collection.ByteArray = ByteArray.allocate(10, true); + } + + namespace concat { + const a: adone.collection.ByteArray = ByteArray.concat([ + new ByteArray(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ]); + const b: adone.collection.ByteArray = ByteArray.concat([ + new ByteArray(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ], "utf8"); + const c: adone.collection.ByteArray = ByteArray.concat([ + new ByteArray(), + Buffer.alloc(10), + new Uint8Array([1, 2, 3]), + new ArrayBuffer(10) + ], "utf8", true); + } + + namespace type { + const a: typeof Buffer = ByteArray.type(); + } + + namespace wrap { + const a: adone.collection.ByteArray = ByteArray.wrap(""); + const b: adone.collection.ByteArray = ByteArray.wrap(new ByteArray()); + const c: adone.collection.ByteArray = ByteArray.wrap(Buffer.alloc(10)); + const d: adone.collection.ByteArray = ByteArray.wrap(new Uint8Array([1, 2, 3])); + const e: adone.collection.ByteArray = ByteArray.wrap(new ArrayBuffer(10)); + const f: adone.collection.ByteArray = ByteArray.wrap("", "utf8"); + const g: adone.collection.ByteArray = ByteArray.wrap("", "utf8", true); + } + + namespace calculateVarint32 { + const a: number = ByteArray.calculateVarint32(10); + } + + namespace zigZagEncode32 { + const a: number = ByteArray.zigZagEncode32(10); + } + + namespace zigZagDecode32 { + const a: number = ByteArray.zigZagDecode32(10); + } + + namespace calculateVarint64 { + const a: number = ByteArray.calculateVarint64(10); + const b: number = ByteArray.calculateVarint64("10"); + } + + namespace zigZagEncode64 { + const a: adone.math.Long = ByteArray.zigZagEncode64(10); + const b: adone.math.Long = ByteArray.zigZagEncode64("10"); + const c: adone.math.Long = ByteArray.zigZagEncode64(adone.math.Long.fromValue(10)); + } + + namespace zigZagDecode64 { + const a: adone.math.Long = ByteArray.zigZagDecode64(10); + const b: adone.math.Long = ByteArray.zigZagDecode64("10"); + const c: adone.math.Long = ByteArray.zigZagDecode64(adone.math.Long.fromValue(10)); + } + + namespace calculateUTF8Chars { + const a: number = ByteArray.calculateUTF8Chars("123"); + } + + namespace calculateString { + const a: number = ByteArray.calculateString("123"); + } + + namespace fromBase64 { + const a: adone.collection.ByteArray = ByteArray.fromBase64("123"); + } + + namespace btoa { + const a: string = ByteArray.btoa("123"); + } + + namespace atob { + const a: string = ByteArray.atob("123"); + } + + namespace fromBinary { + const a: adone.collection.ByteArray = ByteArray.fromBinary("123"); + } + + namespace fromDebug { + const a: adone.collection.ByteArray = ByteArray.fromDebug("12"); + const b: adone.collection.ByteArray = ByteArray.fromDebug("12", true); + } + + namespace fromHex { + const a: adone.collection.ByteArray = ByteArray.fromHex("192"); + const b: adone.collection.ByteArray = ByteArray.fromHex("192", true); + } + + namespace fromUTF8 { + const a: adone.collection.ByteArray = ByteArray.fromUTF8("123"); + const b: adone.collection.ByteArray = ByteArray.fromUTF8("123", true); + } + + namespace constants { + const a: number = ByteArray.DEFAULT_CAPACITY; + const b: boolean = ByteArray.DEFAULT_NOASSERT; + const c: number = ByteArray.MAX_VARINT32_BYTES; + const d: number = ByteArray.MAX_VARINT64_BYTES; + const e: string = ByteArray.METRICS_CHARS; + const f: string = ByteArray.METRICS_BYTES; + } + } + } + + namespace queueTests { + const { Queue } = collection; + type Queue = adone.collection.Queue; + + new Queue(); + { const a: Queue = new Queue().push(123).push(123); } + { const a: number | undefined = new Queue().push(123).pop(); } + { const a: string | undefined = new Queue().push(123).pop(); } + { const a: boolean = new Queue().full; } + { const a: number = new Queue().length; } + { const a: boolean = new Queue().empty; } + } + + namespace asyncQueueTests { + const { AsyncQueue } = collection; + type AsyncQueue = adone.collection.AsyncQueue; + + { const a: AsyncQueue = new AsyncQueue().push(123); } + { const a: Promise = new AsyncQueue().push(123).pop(); } + } + + namespace priorityQueueTests { + const { PriorityQueue } = collection; + type PriorityQueue = adone.collection.PriorityQueue; + + { const a: boolean = new PriorityQueue().empty; } + { const a: number = new PriorityQueue().length; } + new PriorityQueue(); + new PriorityQueue({}); + new PriorityQueue({ + compare(a: number, b: number) { + return a - b; + } + }); + new PriorityQueue({ + priority(a: string, b: string) { + return a.length - b.length; + } + }); + { const a: PriorityQueue = new PriorityQueue().clone(); } + { const a: PriorityQueue = new PriorityQueue().push("123"); } + { const a: string | undefined = new PriorityQueue().pop(); } + { const a: PriorityQueue = new PriorityQueue().delete("123"); } + { const a: PriorityQueue = new PriorityQueue().delete("123"); } + { const a: string = new PriorityQueue().replace("123"); } + { const a: string = new PriorityQueue().pushpop("123"); } + { const a: string[] = new PriorityQueue().toArray(); } + { const a: PriorityQueue = PriorityQueue.from(["1"]); } + { const a: PriorityQueue = PriorityQueue.from(["1"], {}); } + { const a: PriorityQueue = PriorityQueue.from(["1"], { compare: (a: string, b: string) => a.length - b.length }); } + { const a: PriorityQueue = PriorityQueue.from(["1"], { priority: (a: string, b: string) => a.length - b.length }); } + } + + namespace fastlruTests { + const { FastLRU } = collection; + + new FastLRU(); + new FastLRU(100); + new FastLRU(100, { dispose: (key: string, value: number) => null }); + { const a: number = new FastLRU().size; } + { const a: number | undefined = new FastLRU().get("key"); } + new FastLRU().set("key", 123); + { const a: boolean = new FastLRU().delete("key"); } + { const a: boolean = new FastLRU().has("key"); } + { const a: string[] = [...new FastLRU().keys()]; } + { const a: number[] = [...new FastLRU().values()]; } + { const a: number[] = [...new FastLRU().values()]; } + { const a: Array<[string, number]> = [...new FastLRU().entries()]; } + new FastLRU().clear(); + } + + namespace stackTests { + const { Stack } = collection; + type Stack = adone.collection.Stack; + + { const a: boolean = new Stack().empty; } + { const a: number = new Stack().top; } + { const a: Stack = new Stack().push(123); } + { const a: number | undefined = new Stack().pop(); } + { const a: number[] = [...new Stack()]; } + { const a: Stack = Stack.from([1, 2, 3]); } + } + + namespace binarySearchTreeTests { + const { BinarySearchTree } = collection; + type BinarySearchTree = adone.collection.BinarySearchTree; + + new BinarySearchTree(); + new BinarySearchTree({}); + new BinarySearchTree({ checkValueEquality: (a: number, b: number) => a === b }); + new BinarySearchTree({ compareKeys: (a: string, b: string) => a.length - b.length }); + new BinarySearchTree({ parent: new BinarySearchTree() }); + new BinarySearchTree({ unique: true }); + new BinarySearchTree({ value: 123 }); + { const a: BinarySearchTree = new BinarySearchTree().getMaxKeyDescendant(); } + { const a: string = new BinarySearchTree().getMaxKey(); } + { const a: BinarySearchTree = new BinarySearchTree().getMinKeyDescendant(); } + { const a: string = new BinarySearchTree().getMinKey(); } + new BinarySearchTree().checkAllNodesFullfillCondition((key: string, value: number) => null); + new BinarySearchTree().checkIsBST(); + { const a: number = new BinarySearchTree().getNumberOfKeys(); } + new BinarySearchTree().insert("asd", 123); + { const a: number[] = new BinarySearchTree().search("asd"); } + { const a: number[] = new BinarySearchTree().betweenBounds({ $gt: "" }); } + { const a: number[] = new BinarySearchTree().betweenBounds({ $lt: "" }); } + { const a: number[] = new BinarySearchTree().betweenBounds({ $lte: "" }); } + { const a: number[] = new BinarySearchTree().betweenBounds({ $gte: "" }); } + new BinarySearchTree().delete("key"); + new BinarySearchTree().delete("key", 123); + new BinarySearchTree().executeOnEveryNode((tree: BinarySearchTree) => null); + new BinarySearchTree().prettyPrint(); + new BinarySearchTree().prettyPrint(true); + new BinarySearchTree().prettyPrint(true, " "); + } + + namespace avlTreeTests { + const { AVLTree } = collection; + type AVLTree = adone.collection.AVLTree; + + new AVLTree(); + new AVLTree({ checkValueEquality: (a: number, b: number) => a === b }); + new AVLTree({ compareKeys: (a: string, b: string) => a.length - b.length }); + new AVLTree({ parent: new AVLTree() }); + new AVLTree({ unique: false }); + new AVLTree({ value: 123 }); + new AVLTree().checkIsAVLT(); + new AVLTree().insert("123", 123); + new AVLTree().delete("123"); + new AVLTree().delete("123", 123); + { const a: number = new AVLTree().getNumberOFKeys(); } + { const a: number[] = new AVLTree().search("key"); } + { const a: number[] = new AVLTree().betweenBounds({}); } + { const a: number[] = new AVLTree().betweenBounds({ $gt: "ads" }); } + { const a: number[] = new AVLTree().betweenBounds({ $lt: "ads" }); } + { const a: number[] = new AVLTree().betweenBounds({ $gte: "ads" }); } + { const a: number[] = new AVLTree().betweenBounds({ $lte: "ads" }); } + new AVLTree().executeOnEveryNode((tree: AVLTree) => null); + } + + namespace redBlackTreeTests { + const { RedBlackTree } = collection; + type RedBlackTree = adone.collection.RedBlackTree; + type RedBlackTreeIterator = adone.collection.I.RedBlackTree.Iterator; + type RedBlackTreeNode = adone.collection.I.RedBlackTree.Node; + + new RedBlackTree(); + new RedBlackTree((a: string, b: string) => a.length - b.length); + new RedBlackTree(undefined, new RedBlackTree()); + { const a: string[] = new RedBlackTree().keys; } + { const a: number[] = new RedBlackTree().values; } + { const a: number = new RedBlackTree().length; } + { + const a: RedBlackTreeIterator = new RedBlackTree().begin; + { const b: boolean = a.valid; } + { const b: RedBlackTreeNode | null = a.node; } + { const b: string | undefined = a.key; } + { const b: number | undefined = a.value; } + { const b: number = a.index; } + { const b: boolean = a.hasNext; } + { const b: boolean = a.hasPrev; } + { const b: RedBlackTree = a.tree; } + { const b: RedBlackTreeIterator = a.clone(); } + { const b: RedBlackTree = a.remove(); } + a.next(); + { const b: RedBlackTree = a.update(333); } + a.prev(); + } + { const a: RedBlackTreeIterator = new RedBlackTree().end; } + { const a: RedBlackTree = new RedBlackTree().insert("123", 456); } + { const a: number = new RedBlackTree().forEach((key: string, value: number) => value); } + { const a: number = new RedBlackTree().forEach((key: string, value: number) => value, "1"); } + { const a: number = new RedBlackTree().forEach((key: string, value: number) => value, "1", "2"); } + { const a: RedBlackTreeIterator = new RedBlackTree().at(1); } + { const a: RedBlackTreeIterator = new RedBlackTree().ge("1"); } + { const a: RedBlackTreeIterator = new RedBlackTree().gt("1"); } + { const a: RedBlackTreeIterator = new RedBlackTree().lt("1"); } + { const a: RedBlackTreeIterator = new RedBlackTree().le("1"); } + { const a: RedBlackTreeIterator | null = new RedBlackTree().find("1"); } + { const a: RedBlackTree = new RedBlackTree().remove("1"); } + { const a: RedBlackTree = new RedBlackTree().remove("1"); } + { const a: number | undefined = new RedBlackTree().get("1"); } + } + + namespace arraySetTests { + const { ArraySet } = collection; + type ArraySet = adone.collection.ArraySet; + + new ArraySet(); + { const a: number = new ArraySet().length; } + { const a: ArraySet = new ArraySet().add("hello"); } + { const a: ArraySet = new ArraySet().add("hello", true); } + { const a: boolean = new ArraySet().has("string"); } + { const a: number = new ArraySet().indexOf("hello"); } + { const a: string[] = new ArraySet().toArray(); } + { const a: ArraySet = ArraySet.from([1]); } + { const a: ArraySet = ArraySet.from([1], true); } + } + + namespace bufferListTests { + const { BufferList } = collection; + type BufferList = adone.collection.BufferList; + + new BufferList(); + new BufferList(Buffer.from("123")); + new BufferList("123"); + new BufferList(123); + new BufferList([Buffer.from("123"), "123", 123]); + new BufferList((err: any, data: Buffer) => null); + new BufferList().append(Buffer.from("123")); + new BufferList().append("123"); + new BufferList().append(123); + new BufferList().append([Buffer.from("123"), "123", 123]); + new BufferList().end(Buffer.from("123")); + new BufferList().end(); + { const a: number = new BufferList().get(123); } + { const a: Buffer = new BufferList().slice(); } + { const a: Buffer = new BufferList().slice(1); } + { const a: Buffer = new BufferList().slice(1, 2); } + { const a: Buffer = new BufferList().copy(Buffer.alloc(100)); } + { const a: Buffer = new BufferList().copy(Buffer.alloc(100), 0); } + { const a: Buffer = new BufferList().copy(Buffer.alloc(100), 0, 1); } + { const a: Buffer = new BufferList().copy(Buffer.alloc(100), 0, 1, 2); } + { const a: BufferList = new BufferList().shallowSlice(); } + { const a: BufferList = new BufferList().shallowSlice(1); } + { const a: BufferList = new BufferList().shallowSlice(1, 2); } + { const a: string = new BufferList().toString(); } + { const a: string = new BufferList().toString("utf8"); } + { const a: string = new BufferList().toString("utf8", 1); } + { const a: string = new BufferList().toString("utf8", 1, 2); } + { const a: BufferList = new BufferList().consume(10); } + { const a: BufferList = new BufferList().duplicate(); } + new BufferList().destroy(); + new BufferList().then((x: Buffer) => null); + new BufferList().catch((err: any) => null); + } + + namespace defaultMapTests { + const { DefaultMap } = collection; + type DefaultMap = adone.collection.DefaultMap; + + new DefaultMap(); + { const a: DefaultMap = new DefaultMap(undefined, [["1", 2]]); } + { const a: DefaultMap = new DefaultMap((key: string) => 123); } + { const a: DefaultMap = new DefaultMap({ a: 123 }); } + } + + namespace lruTests { + const { LRU } = collection; + type LRU = adone.collection.LRU; + + new LRU(); + new LRU(100); + new LRU({}); + new LRU({ max: 100 }); + new LRU({ dispose: (key: string, value: number) => null }); + new LRU({ maxAge: 100 }); + new LRU({ noDisposeOnSet: false }); + new LRU({ stale: true }); + { const a: number = new LRU().max; } + { new LRU().max = 100; } + { const a: boolean = new LRU().allowStale; } + { new LRU().allowStale = false; } + { const a: number = new LRU().maxAge; } + { new LRU().maxAge = 100; } + { const a: (v: number, k: string) => number = new LRU().lengthCalculator; } + { new LRU().lengthCalculator = () => 123; } + { const a: number = new LRU().length; } + { const a: number = new LRU().itemCount; } + new LRU().rforEach((value: number, key: string) => null); + new LRU().rforEach(function (value: number, key: string) { + const b: number = this.a; + }, { a: 1 }); + new LRU().forEach((value: number, key: string) => null); + new LRU().forEach(function (value: number, key: string) { + const b: number = this.a; + }, { a: 1 }); + { const a: string[] = new LRU().keys(); } + { const a: number[] = new LRU().values(); } + new LRU().reset(); + { + const a: Array> = new LRU().dump(); + const [b] = a; + { const c: number = b.e; } + { const c: string = b.key; } + { const c: number = b.value; } + } + { + const a: adone.collection.LinkedList> = new LRU().dumpLru(); + const b = a.shift(); + if (b !== undefined) { + { const a: string = b.key; } + { const a: number = b.value; } + { const a: number = b.now; } + { const a: number = b.maxAge; } + } + } + { const a: string = new LRU().inspect(); } + { const a: string = new LRU().inspect({}); } + { const a: boolean = new LRU().set("asd", 13); } + { const a: boolean = new LRU().set("asd", 13, 100500); } + { const a: boolean = new LRU().has("asd"); } + { const a: number | undefined = new LRU().get("asd"); } + { const a: number | undefined = new LRU().peek("asd"); } + { const a: adone.collection.I.LRU.Entry = new LRU().pop(); } + new LRU().del("asd"); + new LRU().load(new LRU().dump()); + new LRU().prune(); + } + + namespace timedoutMapTests { + const { TimedoutMap } = collection; + type TimedoutMap = adone.collection.TimedoutMap; + + new TimedoutMap(); + new TimedoutMap(1000); + new TimedoutMap(1000, (key: string) => null); + { + const a: TimedoutMap = new TimedoutMap().forEach((value: number, key: string) => null); + } + { + const a: TimedoutMap = new TimedoutMap().forEach(function (value: number, key: string) { + const a: number = this.a; + }, { a: 1 }); + } + { const a: boolean = new TimedoutMap().delete("123"); } + } +} diff --git a/types/adone/test/glosses/common.ts b/types/adone/test/glosses/common.ts deleted file mode 100644 index c66f6a5410..0000000000 --- a/types/adone/test/glosses/common.ts +++ /dev/null @@ -1,808 +0,0 @@ -namespace commonTests { - namespace is { - { const a: boolean = adone.is.null({}); } - { const a: boolean = adone.is.undefined({}); } - { const a: boolean = adone.is.exist({}); } - { const a: boolean = adone.is.nil({}); } - { const a: boolean = adone.is.number({}); } - { const a: boolean = adone.is.numeral({}); } - { const a: boolean = adone.is.infinite({}); } - { const a: boolean = adone.is.odd({}); } - { const a: boolean = adone.is.even({}); } - { const a: boolean = adone.is.float({}); } - { const a: boolean = adone.is.negativeZero({}); } - { const a: boolean = adone.is.string({}); } - { const a: boolean = adone.is.emptyString({}); } - { const a: boolean = adone.is.substring("abc", "abcdef"); } - { const a: boolean = adone.is.substring("abc", "abcdef", 0); } - { const a: boolean = adone.is.prefix("abc", "abcdef"); } - { const a: boolean = adone.is.suffix("def", "abbdef"); } - { const a: boolean = adone.is.boolean({}); } - { const a: boolean = adone.is.json({}); } - { const a: boolean = adone.is.object({}); } - { const a: boolean = adone.is.plainObject({}); } - { const a: boolean = adone.is.class({}); } - { const a: boolean = adone.is.emptyObject({}); } - { const a: boolean = adone.is.propertyOwned({}, "a"); } - { const a: boolean = adone.is.propertyDefined({}, "a"); } - { const a: boolean = adone.is.conforms({}, {}); } - { const a: boolean = adone.is.conforms({}, {}, true); } - { const a: boolean = adone.is.arrayLikeObject({}); } - { const a: boolean = adone.is.inArray(1, [1, 2, 3]); } - { const a: boolean = adone.is.inArray(1, [1, 2, 3], 0); } - { const a: boolean = adone.is.inArray(1, [1, 2, 3], 0, (a, b) => a === b); } - { const a: boolean = adone.is.sameType({}, {}); } - { const a: boolean = adone.is.primitive({}); } - { const a: boolean = adone.is.equalArrays([], []); } - { const a: boolean = adone.is.deepEqual({}, {}); } - { const a: boolean = adone.is.shallowEqual({}, {}); } - { const a: boolean = adone.is.stream({}); } - { const a: boolean = adone.is.writableStream({}); } - { const a: boolean = adone.is.readableStream({}); } - { const a: boolean = adone.is.duplexStream({}); } - { const a: boolean = adone.is.transformStream({}); } - { const a: boolean = adone.is.utf8(Buffer.alloc(10)); } - { const a: boolean = adone.is.win32PathAbsolute("abc"); } - { const a: boolean = adone.is.posixPathAbsolute("abc"); } - { const a: boolean = adone.is.pathAbsolute("abc"); } - { const a: boolean = adone.is.glob("abc"); } - { const a: boolean = adone.is.dotfile("abc"); } - { const a: boolean = adone.is.function(() => { }); } - { const a: boolean = adone.is.asyncFunction(async () => { }); } - { const a: boolean = adone.is.promise({}); } - { const a: boolean = adone.is.validDate("07.08.2017"); } - { const a: boolean = adone.is.buffer({}); } - { const a: boolean = adone.is.callback({}); } - { const a: boolean = adone.is.generator({}); } - { const a: boolean = adone.is.nan({}); } - { const a: boolean = adone.is.finite({}); } - { const a: boolean = adone.is.integer({}); } - { const a: boolean = adone.is.safeInteger({}); } - { const a: boolean = adone.is.array({}); } - { const a: boolean = adone.is.uint8Array({}); } - { const a: boolean = adone.is.configuration({}); } - { const a: boolean = adone.is.long({}); } - { const a: boolean = adone.is.bigNumber({}); } - { const a: boolean = adone.is.exbuffer({}); } - { const a: boolean = adone.is.exdate({}); } - { const a: boolean = adone.is.transform({}); } - { const a: boolean = adone.is.subsystem({}); } - { const a: boolean = adone.is.application({}); } - { const a: boolean = adone.is.logger({}); } - { const a: boolean = adone.is.coreStream({}); } - { const a: boolean = adone.is.fastStream({}); } - { const a: boolean = adone.is.fastFSStream({}); } - { const a: boolean = adone.is.fastFSMapStream({}); } - { const a: boolean = adone.is.genesisNetron({}); } - { const a: boolean = adone.is.genesisPeer({}); } - { const a: boolean = adone.is.netronAdapter({}); } - { const a: boolean = adone.is.netron({}); } - { const a: boolean = adone.is.netronPeer({}); } - { const a: boolean = adone.is.netronDefinition({}); } - { const a: boolean = adone.is.netronDefinitions({}); } - { const a: boolean = adone.is.netronReference({}); } - { const a: boolean = adone.is.netronInterface({}); } - { const a: boolean = adone.is.netronContext({}); } - { const a: boolean = adone.is.netronIMethod({}, "hello"); } - { const a: boolean = adone.is.netronIProperty({}, "hello"); } - { const a: boolean = adone.is.netronStub({}); } - { const a: boolean = adone.is.netronRemoteStub({}); } - { const a: boolean = adone.is.netronStream({}); } - { const a: boolean = adone.is.iterable({}); } - { const a: boolean = adone.is.windows; } - { const a: boolean = adone.is.linux; } - { const a: boolean = adone.is.freebsd; } - { const a: boolean = adone.is.darwin; } - { const a: boolean = adone.is.sunos; } - { const a: boolean = adone.is.uppercase("abc"); } - { const a: boolean = adone.is.lowercase("abc"); } - { const a: boolean = adone.is.digits("012"); } - { const a: boolean = adone.is.identifier("someMethod"); } - { const a: boolean = adone.is.binaryExtension("mp3"); } - { const a: boolean = adone.is.binaryPath("a.mp3"); } - { const a: boolean = adone.is.ip4("192.168.1.1"); } - { const a: boolean = adone.is.ip6("::192.168.1.1"); } - { const a: boolean = adone.is.arrayBuffer({}); } - { const a: boolean = adone.is.arrayBufferView({}); } - { const a: boolean = adone.is.date({}); } - { const a: boolean = adone.is.error({}); } - { const a: boolean = adone.is.map({}); } - { const a: boolean = adone.is.regexp({}); } - { const a: boolean = adone.is.set({}); } - { const a: boolean = adone.is.symbol({}); } - { const a: boolean = adone.is.validUTF8({}); } - } - - namespace x { - { const a: Error = new adone.x.Exception(); } - { const a: Error = new adone.x.Exception("message"); } - { const a: Error = new adone.x.Exception(new Error()); } - { const a: Error = new adone.x.Exception(new Error(), true); } - { const a: adone.x.Exception = new adone.x.Runtime(); } - { const a: adone.x.Exception = new adone.x.IncompleteBufferError(); } - { const a: adone.x.Exception = new adone.x.NotImplemented(); } - { const a: adone.x.Exception = new adone.x.IllegalState(); } - { const a: adone.x.Exception = new adone.x.NotValid(); } - { const a: adone.x.Exception = new adone.x.Unknown(); } - { const a: adone.x.Exception = new adone.x.NotExists(); } - { const a: adone.x.Exception = new adone.x.Exists(); } - { const a: adone.x.Exception = new adone.x.Empty(); } - { const a: adone.x.Exception = new adone.x.InvalidAccess(); } - { const a: adone.x.Exception = new adone.x.NotSupported(); } - { const a: adone.x.Exception = new adone.x.InvalidArgument(); } - { const a: adone.x.Exception = new adone.x.InvalidNumberOfArguments(); } - { const a: adone.x.Exception = new adone.x.NotFound(); } - { const a: adone.x.Exception = new adone.x.Timeout(); } - { const a: adone.x.Exception = new adone.x.Incorrect(); } - { const a: adone.x.Exception = new adone.x.NotAllowed(); } - { const a: adone.x.Exception = new adone.x.LimitExceeded(); } - { const a: adone.x.Exception = new adone.x.Encoding(); } - { const a: adone.x.Exception = new adone.x.Network(); } - { const a: adone.x.Exception = new adone.x.Bind(); } - { const a: adone.x.Exception = new adone.x.Connect(); } - { const a: adone.x.Exception = new adone.x.Database(); } - { const a: adone.x.Exception = new adone.x.DatabaseInitialization(); } - { const a: adone.x.Exception = new adone.x.DatabaseOpen(); } - { const a: adone.x.Exception = new adone.x.DatabaseRead(); } - { const a: adone.x.Exception = new adone.x.DatabaseWrite(); } - { const a: adone.x.Exception = new adone.x.NetronIllegalState(); } - { const a: adone.x.Exception = new adone.x.NetronPeerDisconnected(); } - { const a: adone.x.Exception = new adone.x.NetronTimeout(); } - } - - namespace EventEmitter { - namespace static { - const a: number = adone.EventEmitter.listenerCount(new adone.EventEmitter(), "event"); - const b: number = adone.EventEmitter.defaultMaxListeners; - } - - namespace addListener { - const a: adone.EventEmitter = new adone.EventEmitter().addListener("event", () => { }); - const b: adone.EventEmitter = new adone.EventEmitter().addListener(Symbol("event"), () => { }); - } - - namespace on { - const a: adone.EventEmitter = new adone.EventEmitter().on("event", () => { }); - const b: adone.EventEmitter = new adone.EventEmitter().on(Symbol("event"), () => { }); - } - - namespace once { - const a: adone.EventEmitter = new adone.EventEmitter().once("event", () => { }); - const b: adone.EventEmitter = new adone.EventEmitter().once(Symbol("event"), () => { }); - } - - namespace prependListener { - const a: adone.EventEmitter = new adone.EventEmitter().prependListener("event", () => { }); - const b: adone.EventEmitter = new adone.EventEmitter().prependListener(Symbol("event"), () => { }); - } - - namespace prependOnceListener { - const a: adone.EventEmitter = new adone.EventEmitter().prependOnceListener("event", () => { }); - const b: adone.EventEmitter = new adone.EventEmitter().prependOnceListener(Symbol("event"), () => { }); - } - - namespace prependOnceListener { - const a: adone.EventEmitter = new adone.EventEmitter().prependOnceListener("event", () => { }); - const b: adone.EventEmitter = new adone.EventEmitter().prependOnceListener(Symbol("event"), () => { }); - } - - namespace removeListener { - const a: adone.EventEmitter = new adone.EventEmitter().removeListener("event", () => { }); - const b: adone.EventEmitter = new adone.EventEmitter().removeListener(Symbol("event"), () => { }); - } - - namespace removeAllListeners { - const a: adone.EventEmitter = new adone.EventEmitter().removeAllListeners("event"); - const b: adone.EventEmitter = new adone.EventEmitter().removeAllListeners(Symbol("event")); - } - - namespace setMaxListeners { - const a: adone.EventEmitter = new adone.EventEmitter().setMaxListeners(10); - } - - namespace getMaxListeners { - const a: number = new adone.EventEmitter().getMaxListeners(); - } - - namespace listeners { - const a: Array<(...args: any[]) => any> = new adone.EventEmitter().listeners("event"); - const b: Array<(...args: any[]) => any> = new adone.EventEmitter().listeners(Symbol("event")); - } - - namespace emit { - const a: boolean = new adone.EventEmitter().emit("event", 1, 2, 3); - const b: boolean = new adone.EventEmitter().emit(Symbol("event"), 1, 2, 3); - } - - namespace eventNames { - const a: Array = new adone.EventEmitter().eventNames(); - const b: Array = new adone.EventEmitter().eventNames(); - } - - namespace listenerCount { - const a: number = new adone.EventEmitter().listenerCount("event"); - const b: number = new adone.EventEmitter().listenerCount(Symbol("event")); - } - } - - namespace AsyncEmitter { - const a: adone.EventEmitter = new adone.AsyncEmitter(); - new adone.AsyncEmitter(10); - - namespace setConcurrency { - const a: adone.AsyncEmitter = new adone.AsyncEmitter().setConcurrency(); - const b: adone.AsyncEmitter = new adone.AsyncEmitter().setConcurrency(10); - } - - namespace emitParallel { - const a: Promise = new adone.AsyncEmitter().emitParallel("even"); - const b: Promise = new adone.AsyncEmitter().emitParallel("even", 1, 2, 3); - } - - namespace emitSerial { - const a: Promise = new adone.AsyncEmitter().emitSerial("even"); - const b: Promise = new adone.AsyncEmitter().emitSerial("even", 1, 2, 3); - } - - namespace emitReduce { - const a: Promise = new adone.AsyncEmitter().emitReduce("even"); - const b: Promise = new adone.AsyncEmitter().emitReduce("even", 1, 2, 3); - } - - namespace emitReduceRight { - const a: Promise = new adone.AsyncEmitter().emitReduceRight("even"); - const b: Promise = new adone.AsyncEmitter().emitReduceRight("even", 1, 2, 3); - } - - namespace subscribe { - const a: () => void = new adone.AsyncEmitter().subscribe("event", () => { }); - const b: () => void = new adone.AsyncEmitter().subscribe("event", () => { }, true); - } - } - - namespace ExBuffer { - new adone.ExBuffer(); - new adone.ExBuffer(10); - new adone.ExBuffer(10, true); - - const buffer = new adone.ExBuffer(); - - namespace readBitSet { - const a: number[] = buffer.readBitSet(); - const b: number[] = buffer.readBitSet(10); - } - - namespace read { - const a: adone.ExBuffer = buffer.read(1); - const b: adone.ExBuffer = buffer.read(1, 10); - } - - namespace readInt8 { - const a: number = buffer.readInt8(); - const b: number = buffer.readInt8(10); - } - - namespace readUInt8 { - const a: number = buffer.readUInt8(); - const b: number = buffer.readUInt8(10); - } - - namespace readInt16LE { - const a: number = buffer.readInt16LE(); - const b: number = buffer.readInt16LE(10); - } - - namespace readUInt16LE { - const a: number = buffer.readUInt16LE(); - const b: number = buffer.readUInt16LE(10); - } - - namespace readInt16BE { - const a: number = buffer.readInt16BE(); - const b: number = buffer.readInt16BE(10); - } - - namespace readUInt16BE { - const a: number = buffer.readUInt16BE(); - const b: number = buffer.readUInt16BE(10); - } - - namespace readInt32LE { - const a: number = buffer.readInt32LE(); - const b: number = buffer.readInt32LE(10); - } - - namespace readUInt32LE { - const a: number = buffer.readUInt32LE(); - const b: number = buffer.readUInt32LE(10); - } - - namespace readInt32BE { - const a: number = buffer.readInt32BE(); - const b: number = buffer.readInt32BE(10); - } - - namespace readUInt32BE { - const a: number = buffer.readUInt32BE(); - const b: number = buffer.readUInt32BE(10); - } - - namespace readInt64LE { - const a: adone.math.Long = buffer.readInt64LE(); - const b: adone.math.Long = buffer.readInt64LE(10); - } - - namespace readUInt64LE { - const a: adone.math.Long = buffer.readUInt64LE(); - const b: adone.math.Long = buffer.readUInt64LE(10); - } - - namespace readInt64BE { - const a: adone.math.Long = buffer.readInt64BE(); - const b: adone.math.Long = buffer.readInt64BE(10); - } - - namespace readUInt64BE { - const a: adone.math.Long = buffer.readUInt64BE(); - const b: adone.math.Long = buffer.readUInt64BE(10); - } - - namespace readFloatLE { - const a: number = buffer.readFloatLE(); - const b: number = buffer.readFloatLE(10); - } - - namespace readFloatBE { - const a: number = buffer.readFloatBE(); - const b: number = buffer.readFloatBE(10); - } - - namespace readDoubleLE { - const a: number = buffer.readDoubleLE(); - const b: number = buffer.readDoubleLE(10); - } - - namespace readDoubleBE { - const a: number = buffer.readDoubleBE(); - const b: number = buffer.readDoubleBE(10); - } - - namespace write { - const a: adone.ExBuffer = buffer.write("1"); - const b: adone.ExBuffer = buffer.write(new adone.ExBuffer()); - const c: adone.ExBuffer = buffer.write(Buffer.alloc(10)); - const d: adone.ExBuffer = buffer.write(new Uint8Array([1, 2, 3])); - const e: adone.ExBuffer = buffer.write(new ArrayBuffer(10)); - const f: adone.ExBuffer = buffer.write("1", 10); - const g: adone.ExBuffer = buffer.write("1", 10, 10); - const h: adone.ExBuffer = buffer.write("1", 10, 10, "utf8"); - } - - namespace writeBitSet { - const a: adone.ExBuffer = buffer.writeBitSet([1, 2, 3]); - const b: number = buffer.writeBitSet([1, 2, 3], 10); - } - - namespace writeInt8 { - const a: adone.ExBuffer = buffer.writeInt8(10); - const b: adone.ExBuffer = buffer.writeInt8(10, 10); - } - - namespace writeUInt8 { - const a: adone.ExBuffer = buffer.writeUInt8(10); - const b: adone.ExBuffer = buffer.writeUInt8(10, 10); - } - - namespace writeInt16LE { - const a: adone.ExBuffer = buffer.writeInt16LE(10); - const b: adone.ExBuffer = buffer.writeInt16LE(10, 10); - } - - namespace writeInt16BE { - const a: adone.ExBuffer = buffer.writeInt16BE(10); - const b: adone.ExBuffer = buffer.writeInt16BE(10, 10); - } - - namespace writeUInt16LE { - const a: adone.ExBuffer = buffer.writeUInt16LE(10); - const b: adone.ExBuffer = buffer.writeUInt16LE(10, 10); - } - - namespace writeUInt16BE { - const a: adone.ExBuffer = buffer.writeUInt16BE(10); - const b: adone.ExBuffer = buffer.writeUInt16BE(10, 10); - } - - namespace writeInt32LE { - const a: adone.ExBuffer = buffer.writeInt32LE(10); - const b: adone.ExBuffer = buffer.writeInt32LE(10, 10); - } - - namespace writeInt32BE { - const a: adone.ExBuffer = buffer.writeInt32BE(10); - const b: adone.ExBuffer = buffer.writeInt32BE(10, 10); - } - - namespace writeUInt32LE { - const a: adone.ExBuffer = buffer.writeUInt32LE(10); - const b: adone.ExBuffer = buffer.writeUInt32LE(10, 10); - } - - namespace writeUInt32BE { - const a: adone.ExBuffer = buffer.writeUInt32BE(10); - const b: adone.ExBuffer = buffer.writeUInt32BE(10, 10); - } - - namespace writeInt64LE { - const a: adone.ExBuffer = buffer.writeInt64LE(10); - const b: adone.ExBuffer = buffer.writeInt64LE(10, 10); - } - - namespace writeInt64BE { - const a: adone.ExBuffer = buffer.writeInt64BE(10); - const b: adone.ExBuffer = buffer.writeInt64BE(10, 10); - } - - namespace writeUInt64LE { - const a: adone.ExBuffer = buffer.writeUInt64LE(10); - const b: adone.ExBuffer = buffer.writeUInt64LE(10, 10); - } - - namespace writeUInt64BE { - const a: adone.ExBuffer = buffer.writeUInt64BE(10); - const b: adone.ExBuffer = buffer.writeUInt64BE(10, 10); - } - - namespace writeFloatLE { - const a: adone.ExBuffer = buffer.writeFloatLE(10); - const b: adone.ExBuffer = buffer.writeFloatLE(10, 10); - } - - namespace writeFloatBE { - const a: adone.ExBuffer = buffer.writeFloatBE(10); - const b: adone.ExBuffer = buffer.writeFloatBE(10, 10); - } - - namespace writeDoubleLE { - const a: adone.ExBuffer = buffer.writeDoubleLE(10); - const b: adone.ExBuffer = buffer.writeDoubleLE(10, 10); - } - - namespace writeDoubleBE { - const a: adone.ExBuffer = buffer.writeDoubleBE(10); - const b: adone.ExBuffer = buffer.writeDoubleBE(10, 10); - } - - namespace writeVarInt32 { - const a: adone.ExBuffer = buffer.writeVarint32(10); - const b: number = buffer.writeVarint32(10, 10); - } - - namespace writeVarInt32ZigZag { - const a: adone.ExBuffer = buffer.writeVarint32ZigZag(10); - const b: number = buffer.writeVarint32ZigZag(10, 10); - } - - namespace readVarint32 { - const a: number = buffer.readVarint32(); - const b: { value: number, length: number } = buffer.readVarint32(10); - } - - namespace readVarint32ZigZag { - const a: number = buffer.readVarint32ZigZag(); - const b: { value: number, length: number } = buffer.readVarint32ZigZag(10); - } - - namespace writeVarint64 { - const a: adone.ExBuffer = buffer.writeVarint64(10); - const b: number = buffer.writeVarint64(10, 10); - } - - namespace writeVarint64ZigZag { - const a: adone.ExBuffer = buffer.writeVarint64ZigZag(10); - const b: number = buffer.writeVarint64ZigZag(10, 10); - } - - namespace readVarint64 { - const a: adone.math.Long = buffer.readVarint64(); - const b: { value: adone.math.Long, length: number } = buffer.readVarint64(10); - } - - namespace readVarint64ZigZag { - const a: adone.math.Long = buffer.readVarint64ZigZag(); - const b: { value: adone.math.Long, length: number } = buffer.readVarint64ZigZag(10); - } - - namespace writeCString { - const a: adone.ExBuffer = buffer.writeCString("asd"); - const b: number = buffer.writeCString("123", 10); - } - - namespace readCString { - const a: string = buffer.readCString(); - const b: { string: string, length: number } = buffer.readCString(10); - } - - namespace writeString { - const a: adone.ExBuffer = buffer.writeString("abc"); - const b: number = buffer.writeString("abc", 10); - } - - namespace readString { - const a: string = buffer.readString(10); - const b: string = buffer.readString(10, "b"); - const c: string = buffer.readString(10, "c"); - const d: { string: string, length: number } = buffer.readString(10, "c", 10); - } - - namespace writeVString { - const a: adone.ExBuffer = buffer.writeVString("abc"); - const b: number = buffer.writeVString("abc", 10); - } - - namespace readVString { - const a: string = buffer.readVString(); - const b: { string: string, length: number } = buffer.readVString(10); - } - - namespace appendTo { - const a: adone.ExBuffer = buffer.appendTo(new adone.ExBuffer()); - const b: adone.ExBuffer = buffer.appendTo(new adone.ExBuffer(), 10); - } - - namespace assert { - const a: adone.ExBuffer = buffer.assert(); - const b: adone.ExBuffer = buffer.assert(true); - } - - namespace capacity { - const a: number = buffer.capacity(); - } - - namespace clear { - const a: adone.ExBuffer = buffer.clear(); - } - - namespace compact { - const a: adone.ExBuffer = buffer.compact(); - const b: adone.ExBuffer = buffer.compact(1); - const c: adone.ExBuffer = buffer.compact(1, 10); - } - - namespace copyTo { - const a: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer()); - const b: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0); - const c: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0, 0); - const d: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0, 0, 10); - } - - namespace ensureCapacity { - const a: adone.ExBuffer = buffer.ensureCapacity(10); - } - - namespace fill { - const a: adone.ExBuffer = buffer.fill("0"); - const b: adone.ExBuffer = buffer.fill(0); - const c: adone.ExBuffer = buffer.fill(0, 0); - const d: adone.ExBuffer = buffer.fill(0, 0, 10); - } - - namespace flip { - const a: adone.ExBuffer = buffer.flip(); - } - - namespace mark { - const a: adone.ExBuffer = buffer.mark(); - const b: adone.ExBuffer = buffer.mark(10); - } - - namespace prepend { - const a: adone.ExBuffer = buffer.prepend(""); - const b: adone.ExBuffer = buffer.prepend(new adone.ExBuffer()); - const c: adone.ExBuffer = buffer.prepend(Buffer.alloc(10)); - const d: adone.ExBuffer = buffer.prepend(new Uint8Array([1, 2, 3])); - const e: adone.ExBuffer = buffer.prepend(new ArrayBuffer(10)); - const f: adone.ExBuffer = buffer.prepend("", "utf8"); - const g: adone.ExBuffer = buffer.prepend("", "utf8", 10); - const h: adone.ExBuffer = buffer.prepend("", 10); - } - - namespace prependTo { - const a: adone.ExBuffer = buffer.prependTo(new adone.ExBuffer()); - const b: adone.ExBuffer = buffer.prependTo(new adone.ExBuffer(), 10); - } - - namespace remaining { - const a: number = buffer.remaining(); - } - - namespace reset { - const a: adone.ExBuffer = buffer.reset(); - } - - namespace resize { - const a: adone.ExBuffer = buffer.resize(10); - } - - namespace reverse { - const a: adone.ExBuffer = buffer.reverse(); - const b: adone.ExBuffer = buffer.reverse(1); - const c: adone.ExBuffer = buffer.reverse(1, 10); - } - - namespace skip { - const a: adone.ExBuffer = buffer.skip(10); - } - - namespace slice { - const a: adone.ExBuffer = buffer.slice(); - const b: adone.ExBuffer = buffer.slice(1); - const c: adone.ExBuffer = buffer.slice(1, 10); - } - - namespace toBuffer { - const a: Buffer = buffer.toBuffer(); - const b: Buffer = buffer.toBuffer(true); - const c: Buffer = buffer.toBuffer(true, 0); - const d: Buffer = buffer.toBuffer(true, 0, 10); - } - - namespace toArrayBuffer { - const a: ArrayBuffer = buffer.toArrayBuffer(); - } - - namespace toString { - const a: string = buffer.toString(); - const b: string = buffer.toString("utf8"); - const c: string = buffer.toString("utf8", 0); - const d: string = buffer.toString("utf8", 0, 10); - } - - namespace toBase64 { - const a: string = buffer.toBase64(); - const b: string = buffer.toBase64(0); - const c: string = buffer.toBase64(0, 10); - } - - namespace toBinary { - const a: string = buffer.toBinary(); - const b: string = buffer.toBinary(0); - const c: string = buffer.toBinary(0, 10); - } - - namespace toDebug { - const a: string = buffer.toDebug(); - const b: string = buffer.toDebug(true); - } - - namespace toUTF8 { - const a: string = buffer.toUTF8(); - const b: string = buffer.toUTF8(0); - const c: string = buffer.toUTF8(0, 10); - } - - namespace static { - namespace accessor { - const a: typeof Buffer = adone.ExBuffer.accessor(); - } - - namespace allocate { - const a: adone.ExBuffer = adone.ExBuffer.allocate(); - const b: adone.ExBuffer = adone.ExBuffer.allocate(10); - const c: adone.ExBuffer = adone.ExBuffer.allocate(10, true); - } - - namespace concat { - const a: adone.ExBuffer = adone.ExBuffer.concat([ - new adone.ExBuffer(), - Buffer.alloc(10), - new Uint8Array([1, 2, 3]), - new ArrayBuffer(10) - ]); - const b: adone.ExBuffer = adone.ExBuffer.concat([ - new adone.ExBuffer(), - Buffer.alloc(10), - new Uint8Array([1, 2, 3]), - new ArrayBuffer(10) - ], "utf8"); - const c: adone.ExBuffer = adone.ExBuffer.concat([ - new adone.ExBuffer(), - Buffer.alloc(10), - new Uint8Array([1, 2, 3]), - new ArrayBuffer(10) - ], "utf8", true); - } - - namespace type { - const a: typeof Buffer = adone.ExBuffer.type(); - } - - namespace wrap { - const a: adone.ExBuffer = adone.ExBuffer.wrap(""); - const b: adone.ExBuffer = adone.ExBuffer.wrap(new adone.ExBuffer()); - const c: adone.ExBuffer = adone.ExBuffer.wrap(Buffer.alloc(10)); - const d: adone.ExBuffer = adone.ExBuffer.wrap(new Uint8Array([1, 2, 3])); - const e: adone.ExBuffer = adone.ExBuffer.wrap(new ArrayBuffer(10)); - const f: adone.ExBuffer = adone.ExBuffer.wrap("", "utf8"); - const g: adone.ExBuffer = adone.ExBuffer.wrap("", "utf8", true); - } - - namespace calculateVarint32 { - const a: number = adone.ExBuffer.calculateVarint32(10); - } - - namespace zigZagEncode32 { - const a: number = adone.ExBuffer.zigZagEncode32(10); - } - - namespace zigZagDecode32 { - const a: number = adone.ExBuffer.zigZagDecode32(10); - } - - namespace calculateVarint64 { - const a: number = adone.ExBuffer.calculateVarint64(10); - const b: number = adone.ExBuffer.calculateVarint64("10"); - } - - namespace zigZagEncode64 { - const a: adone.math.Long = adone.ExBuffer.zigZagEncode64(10); - const b: adone.math.Long = adone.ExBuffer.zigZagEncode64("10"); - const c: adone.math.Long = adone.ExBuffer.zigZagEncode64(adone.math.Long.fromValue(10)); - } - - namespace zigZagDecode64 { - const a: adone.math.Long = adone.ExBuffer.zigZagDecode64(10); - const b: adone.math.Long = adone.ExBuffer.zigZagDecode64("10"); - const c: adone.math.Long = adone.ExBuffer.zigZagDecode64(adone.math.Long.fromValue(10)); - } - - namespace calculateUTF8Chars { - const a: number = adone.ExBuffer.calculateUTF8Chars("123"); - } - - namespace calculateString { - const a: number = adone.ExBuffer.calculateString("123"); - } - - namespace fromBase64 { - const a: adone.ExBuffer = adone.ExBuffer.fromBase64("123"); - } - - namespace btoa { - const a: string = adone.ExBuffer.btoa("123"); - } - - namespace atob { - const a: string = adone.ExBuffer.atob("123"); - } - - namespace fromBinary { - const a: adone.ExBuffer = adone.ExBuffer.fromBinary("123"); - } - - namespace fromDebug { - const a: adone.ExBuffer = adone.ExBuffer.fromDebug("12"); - const b: adone.ExBuffer = adone.ExBuffer.fromDebug("12", true); - } - - namespace fromHex { - const a: adone.ExBuffer = adone.ExBuffer.fromHex("192"); - const b: adone.ExBuffer = adone.ExBuffer.fromHex("192", true); - } - - namespace fromUTF8 { - const a: adone.ExBuffer = adone.ExBuffer.fromUTF8("123"); - const b: adone.ExBuffer = adone.ExBuffer.fromUTF8("123", true); - } - - namespace constants { - const a: number = adone.ExBuffer.DEFAULT_CAPACITY; - const b: boolean = adone.ExBuffer.DEFAULT_NOASSERT; - const c: number = adone.ExBuffer.MAX_VARINT32_BYTES; - const d: number = adone.ExBuffer.MAX_VARINT64_BYTES; - const e: string = adone.ExBuffer.METRICS_CHARS; - const f: string = adone.ExBuffer.METRICS_BYTES; - } - } - } -} diff --git a/types/adone/test/glosses/compressors.ts b/types/adone/test/glosses/compressors.ts new file mode 100644 index 0000000000..738dfe9e06 --- /dev/null +++ b/types/adone/test/glosses/compressors.ts @@ -0,0 +1,626 @@ +namespace compressorsTests { + const { compressor } = adone; + + namespace gzTests { + const { gz } = compressor; + + gz.compress("hello").then((x: Buffer) => {}); + gz.compress(Buffer.from("hello")).then((x: Buffer) => {}); + gz.compress(Buffer.from("hello"), {}).then((x: Buffer) => {}); + gz.compress(Buffer.from("hello"), { chunkSize: 4096 }).then((x: Buffer) => {}); + gz.compress(Buffer.from("hello"), { finishFlush: gz.Z_FINISH }).then((x: Buffer) => {}); + gz.compress(Buffer.from("hello"), { flush: gz.Z_NO_FLUSH }).then((x: Buffer) => {}); + gz.compress(Buffer.from("hello"), { info: true }).then((x: { buffer: Buffer, engine: nodestd.zlib.Gzip }) => {}); + gz.compress(Buffer.from("hello"), { level: gz.Z_BEST_COMPRESSION }).then((x: Buffer) => {}); + gz.compress(Buffer.from("hello"), { memLevel: gz.Z_BEST_COMPRESSION }).then((x: Buffer) => {}); + gz.compress(Buffer.from("hello"), { strategy: gz.Z_HUFFMAN_ONLY }).then((x: Buffer) => {}); + gz.compress(Buffer.from("hello"), { windowBits: 10 }).then((x: Buffer) => {}); + + { const a: Buffer = gz.compressSync("hello"); } + { const a: Buffer = gz.compressSync(Buffer.from("hello")); } + { const a: Buffer = gz.compressSync(Buffer.from("hello"), {}); } + { const a: Buffer = gz.compressSync(Buffer.from("hello"), { chunkSize: 4096 }); } + { const a: Buffer = gz.compressSync(Buffer.from("hello"), { finishFlush: gz.Z_FINISH }); } + { const a: Buffer = gz.compressSync(Buffer.from("hello"), { flush: gz.Z_NO_FLUSH }); } + { const a: { buffer: Buffer, engine: nodestd.zlib.Gzip } = gz.compressSync(Buffer.from("hello"), { info: true }); } + { const a: Buffer = gz.compressSync(Buffer.from("hello"), { level: gz.Z_BEST_COMPRESSION }); } + { const a: Buffer = gz.compressSync(Buffer.from("hello"), { memLevel: gz.Z_BEST_COMPRESSION }); } + { const a: Buffer = gz.compressSync(Buffer.from("hello"), { strategy: gz.Z_HUFFMAN_ONLY }); } + { const a: Buffer = gz.compressSync(Buffer.from("hello"), { windowBits: 10 }); } + + gz.decompress("hello").then((x: Buffer) => {}); + gz.decompress(Buffer.from("hello")).then((x: Buffer) => {}); + gz.decompress(Buffer.from("hello"), { chunkSize: 4096 }).then((x: Buffer) => {}); + gz.decompress(Buffer.from("hello"), { finishFlush: gz.Z_FINISH }).then((x: Buffer) => {}); + gz.decompress(Buffer.from("hello"), { flush: gz.Z_NO_FLUSH }).then((x: Buffer) => {}); + gz.decompress(Buffer.from("hello"), { info: true }).then((x: { buffer: Buffer, engine: nodestd.zlib.Gunzip }) => {}); + gz.decompress(Buffer.from("hello"), { windowBits: 9 }).then((x: Buffer) => {}); + + { const a: Buffer = gz.decompressSync("hello"); } + { const a: Buffer = gz.decompressSync(Buffer.from("hello")); } + { const a: Buffer = gz.decompressSync(Buffer.from("hello"), { chunkSize: 4096 }); } + { const a: Buffer = gz.decompressSync(Buffer.from("hello"), { finishFlush: gz.Z_FINISH }); } + { const a: Buffer = gz.decompressSync(Buffer.from("hello"), { flush: gz.Z_NO_FLUSH }); } + { const a: { buffer: Buffer, engine: nodestd.zlib.Gunzip } = gz.decompressSync(Buffer.from("hello"), { info: true }); } + { const a: Buffer = gz.decompressSync(Buffer.from("hello"), { windowBits: 9 }); } + + { const a: nodestd.zlib.Gzip = gz.compressStream(); } + { const a: nodestd.zlib.Gzip = gz.compressStream({}); } + { const a: nodestd.zlib.Gzip = gz.compressStream({ chunkSize: 10 }); } + { const a: nodestd.zlib.Gzip = gz.compressStream({ flush: 10 }); } + { const a: nodestd.zlib.Gzip = gz.compressStream({ level: 9 }); } + { const a: nodestd.zlib.Gzip = gz.compressStream({ memLevel: 9 }); } + { const a: nodestd.zlib.Gzip = gz.compressStream({ strategy: 9 }); } + { const a: nodestd.zlib.Gzip = gz.compressStream({ windowBits: 9 }); } + + { const a: nodestd.zlib.Gunzip = gz.decompressStream(); } + { const a: nodestd.zlib.Gunzip = gz.decompressStream({}); } + { const a: nodestd.zlib.Gunzip = gz.decompressStream({ chunkSize: 4096 }); } + { const a: nodestd.zlib.Gunzip = gz.decompressStream({ flush: 0 }); } + { const a: nodestd.zlib.Gunzip = gz.decompressStream({ windowBits: 0 }); } + + { const a: number = gz.Z_NO_FLUSH; } + { const a: number = gz.Z_PARTIAL_FLUSH; } + { const a: number = gz.Z_SYNC_FLUSH; } + { const a: number = gz.Z_FULL_FLUSH; } + { const a: number = gz.Z_FINISH; } + { const a: number = gz.Z_BLOCK; } + { const a: number = gz.Z_TREES; } + { const a: number = gz.Z_OK; } + { const a: number = gz.Z_STREAM_END; } + { const a: number = gz.Z_NEED_DICT; } + { const a: number = gz.Z_ERRNO; } + { const a: number = gz.Z_STREAM_ERROR; } + { const a: number = gz.Z_DATA_ERROR; } + { const a: number = gz.Z_MEM_ERROR; } + { const a: number = gz.Z_BUF_ERROR; } + { const a: number = gz.Z_VERSION_ERROR; } + { const a: number = gz.Z_NO_COMPRESSION; } + { const a: number = gz.Z_BEST_SPEED; } + { const a: number = gz.Z_BEST_COMPRESSION; } + { const a: number = gz.Z_DEFAULT_COMPRESSION; } + { const a: number = gz.Z_FILTERED; } + { const a: number = gz.Z_HUFFMAN_ONLY; } + { const a: number = gz.Z_RLE; } + { const a: number = gz.Z_FIXED; } + { const a: number = gz.Z_DEFAULT_STRATEGY; } + } + + namespace deflateTests { + const { deflate } = compressor; + + deflate.compress("hello").then((x: Buffer) => {}); + deflate.compress(Buffer.from("hello")).then((x: Buffer) => {}); + deflate.compress(Buffer.from("hello"), {}).then((x: Buffer) => {}); + deflate.compress(Buffer.from("hello"), { chunkSize: 4096 }).then((x: Buffer) => {}); + deflate.compress(Buffer.from("hello"), { dictionary: Buffer.from("123") }).then((x: Buffer) => {}); + deflate.compress(Buffer.from("hello"), { finishFlush: 0 }).then((x: Buffer) => {}); + deflate.compress(Buffer.from("hello"), { flush: 0 }).then((x: Buffer) => {}); + deflate.compress(Buffer.from("hello"), { info: true }).then((x: { buffer: Buffer, engine: nodestd.zlib.Deflate }) => {}); + deflate.compress(Buffer.from("hello"), { level: 0 }).then((x: Buffer) => {}); + deflate.compress(Buffer.from("hello"), { memLevel: 0 }).then((x: Buffer) => {}); + deflate.compress(Buffer.from("hello"), { strategy: 0 }).then((x: Buffer) => {}); + deflate.compress(Buffer.from("hello"), { windowBits: 0 }).then((x: Buffer) => {}); + + { const a: Buffer = deflate.compressSync("hello"); } + { const a: Buffer = deflate.compressSync(Buffer.from("hello")); } + { const a: Buffer = deflate.compressSync(Buffer.from("hello"), {}); } + { const a: Buffer = deflate.compressSync(Buffer.from("hello"), { chunkSize: 4096 }); } + { const a: Buffer = deflate.compressSync(Buffer.from("hello"), { dictionary: Buffer.from("123") }); } + { const a: Buffer = deflate.compressSync(Buffer.from("hello"), { finishFlush: 0 }); } + { const a: Buffer = deflate.compressSync(Buffer.from("hello"), { flush: 0 }); } + { const a: { buffer: Buffer, engine: nodestd.zlib.Deflate } = deflate.compressSync(Buffer.from("hello"), { info: true }); } + { const a: Buffer = deflate.compressSync(Buffer.from("hello"), { level: 0 }); } + { const a: Buffer = deflate.compressSync(Buffer.from("hello"), { memLevel: 0 }); } + { const a: Buffer = deflate.compressSync(Buffer.from("hello"), { strategy: 0 }); } + { const a: Buffer = deflate.compressSync(Buffer.from("hello"), { windowBits: 0 }); } + + deflate.rawCompress("hello").then((x: Buffer) => {}); + deflate.rawCompress(Buffer.from("hello")).then((x: Buffer) => {}); + deflate.rawCompress(Buffer.from("hello"), {}).then((x: Buffer) => {}); + deflate.rawCompress(Buffer.from("hello"), { chunkSize: 4096 }).then((x: Buffer) => {}); + deflate.rawCompress(Buffer.from("hello"), { dictionary: Buffer.from("123") }).then((x: Buffer) => {}); + deflate.rawCompress(Buffer.from("hello"), { finishFlush: 0 }).then((x: Buffer) => {}); + deflate.rawCompress(Buffer.from("hello"), { flush: 0 }).then((x: Buffer) => {}); + deflate.rawCompress(Buffer.from("hello"), { info: true }).then((x: { buffer: Buffer, engine: nodestd.zlib.DeflateRaw }) => {}); + deflate.rawCompress(Buffer.from("hello"), { level: 0 }).then((x: Buffer) => {}); + deflate.rawCompress(Buffer.from("hello"), { memLevel: 0 }).then((x: Buffer) => {}); + deflate.rawCompress(Buffer.from("hello"), { strategy: 0 }).then((x: Buffer) => {}); + deflate.rawCompress(Buffer.from("hello"), { windowBits: 0 }).then((x: Buffer) => {}); + + { const a: Buffer = deflate.rawCompressSync("hello"); } + { const a: Buffer = deflate.rawCompressSync(Buffer.from("hello")); } + { const a: Buffer = deflate.rawCompressSync(Buffer.from("hello"), {}); } + { const a: Buffer = deflate.rawCompressSync(Buffer.from("hello"), { chunkSize: 4096 }); } + { const a: Buffer = deflate.rawCompressSync(Buffer.from("hello"), { dictionary: Buffer.from("123") }); } + { const a: Buffer = deflate.rawCompressSync(Buffer.from("hello"), { finishFlush: 0 }); } + { const a: Buffer = deflate.rawCompressSync(Buffer.from("hello"), { flush: 0 }); } + { const a: { buffer: Buffer, engine: nodestd.zlib.DeflateRaw } = deflate.rawCompressSync(Buffer.from("hello"), { info: true }); } + { const a: Buffer = deflate.rawCompressSync(Buffer.from("hello"), { level: 0 }); } + { const a: Buffer = deflate.rawCompressSync(Buffer.from("hello"), { memLevel: 0 }); } + { const a: Buffer = deflate.rawCompressSync(Buffer.from("hello"), { strategy: 0 }); } + { const a: Buffer = deflate.rawCompressSync(Buffer.from("hello"), { windowBits: 0 }); } + + deflate.decompress("hello").then((x: Buffer) => {}); + deflate.decompress(Buffer.from("hello")).then((x: Buffer) => {}); + deflate.decompress(Buffer.from("hello"), {}).then((x: Buffer) => {}); + deflate.decompress(Buffer.from("hello"), { chunkSize: 4096 }).then((x: Buffer) => {}); + deflate.decompress(Buffer.from("hello"), { dictionary: Buffer.from("123") }).then((x: Buffer) => {}); + deflate.decompress(Buffer.from("hello"), { finishFlush: 0 }).then((x: Buffer) => {}); + deflate.decompress(Buffer.from("hello"), { flush: 0 }).then((x: Buffer) => {}); + deflate.decompress(Buffer.from("hello"), { info: true }).then((x: { buffer: Buffer, engine: nodestd.zlib.Inflate }) => {}); + deflate.decompress(Buffer.from("hello"), { windowBits: 0 }).then((x: Buffer) => {}); + + { const a: Buffer = deflate.decompressSync("hello"); } + { const a: Buffer = deflate.decompressSync(Buffer.from("hello")); } + { const a: Buffer = deflate.decompressSync(Buffer.from("hello"), {}); } + { const a: Buffer = deflate.decompressSync(Buffer.from("hello"), { chunkSize: 4096 }); } + { const a: Buffer = deflate.decompressSync(Buffer.from("hello"), { dictionary: Buffer.from("123") }); } + { const a: Buffer = deflate.decompressSync(Buffer.from("hello"), { finishFlush: 0 }); } + { const a: Buffer = deflate.decompressSync(Buffer.from("hello"), { flush: 0 }); } + { const a: { buffer: Buffer, engine: nodestd.zlib.Inflate } = deflate.decompressSync(Buffer.from("hello"), { info: true }); } + { const a: Buffer = deflate.decompressSync(Buffer.from("hello"), { windowBits: 0 }); } + + deflate.rawDecompress("hello").then((x: Buffer) => {}); + deflate.rawDecompress(Buffer.from("hello")).then((x: Buffer) => {}); + deflate.rawDecompress(Buffer.from("hello"), {}).then((x: Buffer) => {}); + deflate.rawDecompress(Buffer.from("hello"), { chunkSize: 4096 }).then((x: Buffer) => {}); + deflate.rawDecompress(Buffer.from("hello"), { dictionary: Buffer.from("123") }).then((x: Buffer) => {}); + deflate.rawDecompress(Buffer.from("hello"), { finishFlush: 0 }).then((x: Buffer) => {}); + deflate.rawDecompress(Buffer.from("hello"), { flush: 0 }).then((x: Buffer) => {}); + deflate.rawDecompress(Buffer.from("hello"), { info: true }).then((x: { buffer: Buffer, engine: nodestd.zlib.InflateRaw }) => {}); + deflate.rawDecompress(Buffer.from("hello"), { windowBits: 0 }).then((x: Buffer) => {}); + + { const a: Buffer = deflate.rawDecompressSync("hello"); } + { const a: Buffer = deflate.rawDecompressSync(Buffer.from("hello")); } + { const a: Buffer = deflate.rawDecompressSync(Buffer.from("hello"), {}); } + { const a: Buffer = deflate.rawDecompressSync(Buffer.from("hello"), { chunkSize: 4096 }); } + { const a: Buffer = deflate.rawDecompressSync(Buffer.from("hello"), { dictionary: Buffer.from("123") }); } + { const a: Buffer = deflate.rawDecompressSync(Buffer.from("hello"), { finishFlush: 0 }); } + { const a: Buffer = deflate.rawDecompressSync(Buffer.from("hello"), { flush: 0 }); } + { const a: { buffer: Buffer, engine: nodestd.zlib.Inflate } = deflate.rawDecompressSync(Buffer.from("hello"), { info: true }); } + { const a: Buffer = deflate.rawDecompressSync(Buffer.from("hello"), { windowBits: 0 }); } + + { const a: nodestd.zlib.Deflate = deflate.compressStream(); } + { const a: nodestd.zlib.Deflate = deflate.compressStream({}); } + { const a: nodestd.zlib.Deflate = deflate.compressStream({ chunkSize: 0 }); } + { const a: nodestd.zlib.Deflate = deflate.compressStream({ dictionary: Buffer.from("123") }); } + { const a: nodestd.zlib.Deflate = deflate.compressStream({ finishFlush: 0 }); } + { const a: nodestd.zlib.Deflate = deflate.compressStream({ flush: 0 }); } + { const a: nodestd.zlib.Deflate = deflate.compressStream({ level: 0 }); } + { const a: nodestd.zlib.Deflate = deflate.compressStream({ memLevel: 0 }); } + { const a: nodestd.zlib.Deflate = deflate.compressStream({ strategy: 0 }); } + { const a: nodestd.zlib.Deflate = deflate.compressStream({ windowBits: 0 }); } + + { const a: nodestd.zlib.DeflateRaw = deflate.rawCompressStream(); } + { const a: nodestd.zlib.DeflateRaw = deflate.rawCompressStream({}); } + { const a: nodestd.zlib.DeflateRaw = deflate.rawCompressStream({ chunkSize: 0 }); } + { const a: nodestd.zlib.DeflateRaw = deflate.rawCompressStream({ dictionary: Buffer.from("123") }); } + { const a: nodestd.zlib.DeflateRaw = deflate.rawCompressStream({ finishFlush: 0 }); } + { const a: nodestd.zlib.DeflateRaw = deflate.rawCompressStream({ flush: 0 }); } + { const a: nodestd.zlib.DeflateRaw = deflate.rawCompressStream({ level: 0 }); } + { const a: nodestd.zlib.DeflateRaw = deflate.rawCompressStream({ memLevel: 0 }); } + { const a: nodestd.zlib.DeflateRaw = deflate.rawCompressStream({ strategy: 0 }); } + { const a: nodestd.zlib.DeflateRaw = deflate.rawCompressStream({ windowBits: 0 }); } + + { const a: nodestd.zlib.Inflate = deflate.decompressStream(); } + { const a: nodestd.zlib.Inflate = deflate.decompressStream({}); } + { const a: nodestd.zlib.Inflate = deflate.decompressStream({ chunkSize: 0 }); } + { const a: nodestd.zlib.Inflate = deflate.decompressStream({ dictionary: Buffer.from("123") }); } + { const a: nodestd.zlib.Inflate = deflate.decompressStream({ finishFlush: 0 }); } + { const a: nodestd.zlib.Inflate = deflate.decompressStream({ flush: 0 }); } + { const a: nodestd.zlib.Inflate = deflate.decompressStream({ windowBits: 0 }); } + + { const a: nodestd.zlib.InflateRaw = deflate.rawDecompressStream(); } + { const a: nodestd.zlib.InflateRaw = deflate.rawDecompressStream({}); } + { const a: nodestd.zlib.InflateRaw = deflate.rawDecompressStream({ chunkSize: 0 }); } + { const a: nodestd.zlib.InflateRaw = deflate.rawDecompressStream({ dictionary: Buffer.from("123") }); } + { const a: nodestd.zlib.InflateRaw = deflate.rawDecompressStream({ finishFlush: 0 }); } + { const a: nodestd.zlib.InflateRaw = deflate.rawDecompressStream({ flush: 0 }); } + { const a: nodestd.zlib.InflateRaw = deflate.rawDecompressStream({ windowBits: 0 }); } + + { const a: number = deflate.Z_NO_FLUSH; } + { const a: number = deflate.Z_PARTIAL_FLUSH; } + { const a: number = deflate.Z_SYNC_FLUSH; } + { const a: number = deflate.Z_FULL_FLUSH; } + { const a: number = deflate.Z_FINISH; } + { const a: number = deflate.Z_BLOCK; } + { const a: number = deflate.Z_TREES; } + { const a: number = deflate.Z_OK; } + { const a: number = deflate.Z_STREAM_END; } + { const a: number = deflate.Z_NEED_DICT; } + { const a: number = deflate.Z_ERRNO; } + { const a: number = deflate.Z_STREAM_ERROR; } + { const a: number = deflate.Z_DATA_ERROR; } + { const a: number = deflate.Z_MEM_ERROR; } + { const a: number = deflate.Z_BUF_ERROR; } + { const a: number = deflate.Z_VERSION_ERROR; } + { const a: number = deflate.Z_NO_COMPRESSION; } + { const a: number = deflate.Z_BEST_SPEED; } + { const a: number = deflate.Z_BEST_COMPRESSION; } + { const a: number = deflate.Z_DEFAULT_COMPRESSION; } + { const a: number = deflate.Z_FILTERED; } + { const a: number = deflate.Z_HUFFMAN_ONLY; } + { const a: number = deflate.Z_RLE; } + { const a: number = deflate.Z_FIXED; } + { const a: number = deflate.Z_DEFAULT_STRATEGY; } + } + + namespace brotliTests { + const { brotli } = compressor; + + brotli.compress("hello").then((x: Buffer) => {}); + brotli.compress(Buffer.from("hello")).then((x: Buffer) => {}); + brotli.compress(Buffer.from("hello"), {}).then((x: Buffer) => {}); + brotli.compress(Buffer.from("hello"), { dictionary: Buffer.from("123") }).then((x: Buffer) => {}); + brotli.compress(Buffer.from("hello"), { disable_literal_context_modeling: true }).then((x: Buffer) => {}); + brotli.compress(Buffer.from("hello"), { lgblock: 0 }).then((x: Buffer) => {}); + brotli.compress(Buffer.from("hello"), { lgwin: 0 }).then((x: Buffer) => {}); + brotli.compress(Buffer.from("hello"), { mode: 0 }).then((x: Buffer) => {}); + brotli.compress(Buffer.from("hello"), { quality: 0 }).then((x: Buffer) => {}); + brotli.compress(Buffer.from("hello"), { size_hint: 0 }).then((x: Buffer) => {}); + + { const a: Buffer = brotli.compressSync("hello"); } + { const a: Buffer = brotli.compressSync(Buffer.from("hello")); } + { const a: Buffer = brotli.compressSync(Buffer.from("hello"), {}); } + { const a: Buffer = brotli.compressSync(Buffer.from("hello"), { dictionary: Buffer.from("123") }); } + { const a: Buffer = brotli.compressSync(Buffer.from("hello"), { disable_literal_context_modeling: true }); } + { const a: Buffer = brotli.compressSync(Buffer.from("hello"), { lgblock: 0 }); } + { const a: Buffer = brotli.compressSync(Buffer.from("hello"), { lgwin: 0 }); } + { const a: Buffer = brotli.compressSync(Buffer.from("hello"), { mode: 0 }); } + { const a: Buffer = brotli.compressSync(Buffer.from("hello"), { quality: 0 }); } + { const a: Buffer = brotli.compressSync(Buffer.from("hello"), { size_hint: 0 }); } + + brotli.decompress(Buffer.from("hello")).then((x: Buffer) => {}); + brotli.decompress(Buffer.from("hello"), {}).then((x: Buffer) => {}); + brotli.decompress(Buffer.from("hello"), { dictionary: Buffer.from("123") }).then((x: Buffer) => {}); + + { const a: Buffer = brotli.decompressSync(Buffer.from("hello")); } + { const a: Buffer = brotli.decompressSync(Buffer.from("hello"), {}); } + { const a: Buffer = brotli.decompressSync(Buffer.from("hello"), { dictionary: Buffer.from("123") }); } + + { const a: nodestd.stream.Transform = brotli.compressStream(); } + { const a: nodestd.stream.Transform = brotli.compressStream({}); } + { const a: nodestd.stream.Transform = brotli.compressStream({ dictionary: Buffer.from("123") }); } + { const a: nodestd.stream.Transform = brotli.compressStream({ disable_literal_context_modeling: true }); } + { const a: nodestd.stream.Transform = brotli.compressStream({ lgblock: 0 }); } + { const a: nodestd.stream.Transform = brotli.compressStream({ lgwin: 0 }); } + { const a: nodestd.stream.Transform = brotli.compressStream({ mode: 0 }); } + { const a: nodestd.stream.Transform = brotli.compressStream({ quality: 0 }); } + { const a: nodestd.stream.Transform = brotli.compressStream({ size_hint: 0 }); } + + { const a: nodestd.stream.Transform = brotli.decompressStream(); } + { const a: nodestd.stream.Transform = brotli.decompressStream({}); } + { const a: nodestd.stream.Transform = brotli.decompressStream({ dictionary: Buffer.from("123") }); } + } + + namespace snappyTests { + const { snappy } = compressor; + + snappy.compress("hello").then((x: Buffer) => {}); + snappy.compress(Buffer.from("hello")).then((x: Buffer) => {}); + + { const a: Buffer = snappy.compressSync("hello"); } + { const a: Buffer = snappy.compressSync(Buffer.from("hello")); } + + snappy.isValidCompressed(Buffer.from("123")).then((X: boolean) => {}); + { const a: boolean = snappy.isValidCompressedSync(Buffer.from("123")); } + + snappy.decompress(Buffer.from("123")).then((x: Buffer) => {}); + { const a: Buffer = snappy.decompressSync(Buffer.from("123")); } + } + + namespace lzmaTests { + const { lzma } = compressor; + type Stream = adone.compressor.I.lzma.Stream; + + { const a: boolean = lzma.asyncCodeAvailable; } + { const a: number = lzma.versionNumber(); } + { const a: string = lzma.versionString(); } + { const a: boolean = lzma.checkIsSupported(lzma.CHECK_CRC32); } + { const a: number = lzma.checkSize(lzma.CHECK_CRC32); } + { const a: boolean = lzma.filterDecoderIsSupported(lzma.FILTER_ARM); } + { const a: boolean = lzma.filterEncoderIsSupported(lzma.FILTER_ARM); } + { const a: boolean = lzma.mfIsSupported(lzma.MF_BT2); } + { const a: number = lzma.rawEncoderMemusage([{ id: "LZMA_FILTER_DELTA", dist: 1 }]); } + { const a: number = lzma.rawDecoderMemusage([{ id: "LZMA_FILTER_DELTA", dist: 1 }]); } + { const a: number = lzma.easyEncoderMemusage(lzma.PRESET_DEFAULT); } + { const a: number = lzma.easyDecoderMemusage(lzma.PRESET_EXTREME); } + + { + const a: Stream = lzma.createStream("easyEncoder"); + { const b: number = a.bufsize; } + { const b: number = a.totalIn(); } + { const b: number = a.totalOut(); } + a.cleanup(); + a.push("1"); + a.write("1"); + a.end(); + a.destroy(); + } + { const a: Stream = lzma.createStream("easyEncoder", lzma.PRESET_DEFAULT); } + { const a: Stream = lzma.createStream("easyEncoder", {}); } + { const a: Stream = lzma.createStream("easyEncoder", { check: lzma.CHECK_CRC32 }); } + { const a: Stream = lzma.createStream("easyEncoder", { preset: lzma.PRESET_EXTREME }); } + + { const a: Stream = lzma.createStream("autoDecoder"); } + { const a: Stream = lzma.createStream("autoDecoder", {}); } + { const a: Stream = lzma.createStream("autoDecoder", { flags: lzma.LZMA_TELL_NO_CHECK }); } + { const a: Stream = lzma.createStream("autoDecoder", { memlimit: 1000 }); } + + { const a: Stream = lzma.createStream("aloneEncoder"); } + { const a: Stream = lzma.createStream("aloneEncoder", lzma.PRESET_DEFAULT); } + { const a: Stream = lzma.createStream("aloneEncoder", {}); } + { const a: Stream = lzma.createStream("aloneEncoder", { blockSize: 4096 }); } + { const a: Stream = lzma.createStream("aloneEncoder", { bufsize: 100 }); } + { const a: Stream = lzma.createStream("aloneEncoder", { check: 0 }); } + { const a: Stream = lzma.createStream("aloneEncoder", { flags: 0 }); } + { const a: Stream = lzma.createStream("aloneEncoder", { memlimit: 0 }); } + { const a: Stream = lzma.createStream("aloneEncoder", { preset: 1 }); } + { const a: Stream = lzma.createStream("aloneEncoder", { synchronous: true }); } + { const a: Stream = lzma.createStream("aloneEncoder", { threads: 10 }); } + { const a: Stream = lzma.createStream("aloneEncoder", { timeout: 1 }); } + + { const a: Stream = lzma.createStream("aloneDecoder"); } + { const a: Stream = lzma.createStream("aloneDecoder", {}); } + { const a: Stream = lzma.createStream("aloneDecoder", { memlimit: 1000 }); } + + { const a: Stream = lzma.createStream("rawEncoder"); } + { const a: Stream = lzma.createStream("rawEncoder", {}); } + { const a: Stream = lzma.createStream("rawEncoder", { filters: [{ id: "LZMA_FILTER_DELTA" }] }); } + + { const a: Stream = lzma.createStream("rawDecoder"); } + { const a: Stream = lzma.createStream("rawDecoder", {}); } + { const a: Stream = lzma.createStream("rawDecoder", { filters: [{ id: "LZMA_FILTER_DELTA" }] }); } + + { const a: Stream = lzma.createStream("streamEncoder"); } + { const a: Stream = lzma.createStream("streamEncoder", {}); } + { const a: Stream = lzma.createStream("streamEncoder", { check: lzma.CHECK_CRC64 }); } + { const a: Stream = lzma.createStream("streamEncoder", { filters: [{ id: "LZMA_FILTER_DELTA" }] }); } + + { const a: Stream = lzma.createStream("streamDecoder"); } + { const a: Stream = lzma.createStream("streamDecoder", {}); } + { const a: Stream = lzma.createStream("streamDecoder", { flags: lzma.LZMA_CONCATENATED }); } + { const a: Stream = lzma.createStream("streamDecoder", { memlimit: 100 }); } + + lzma.singleStringCoding( + lzma.createStream("streamDecoder"), + "hello" + ).then((x: Buffer) => {}); + + lzma.singleStringCoding( + lzma.createStream("streamDecoder"), + Buffer.from("hello") + ).then((x: Buffer) => {}); + + lzma.singleStringCoding( + lzma.createStream("streamDecoder"), + "hello", + (err: any, data: Buffer) => {} + ).then((x: Buffer) => {}); + + lzma.singleStringCoding( + lzma.createStream("streamDecoder"), + "hello", + (err: any, data: Buffer) => {}, + (x: number) => {} + ).then((x: Buffer) => {}); + + { const a: number = lzma.CHECK_CRC32; } + { const a: number = lzma.CHECK_CRC64; } + { const a: number = lzma.CHECK_NONE; } + { const a: number = lzma.CHECK_SHA256; } + { const a: string = lzma.FILTERS_MAX; } + { const a: string = lzma.FILTER_ARM; } + { const a: string = lzma.FILTER_ARMTHUMB; } + { const a: string = lzma.FILTER_IA64; } + { const a: string = lzma.FILTER_POWERPC; } + { const a: string = lzma.FILTER_SPARC; } + { const a: string = lzma.FILTER_X86; } + { const a: string = lzma.FILTER_DELTA; } + { const a: string = lzma.FILTER_LZMA1; } + { const a: string = lzma.FILTER_LZMA2; } + { const a: number = lzma.PRESET_EXTREME; } + { const a: number = lzma.PRESET_DEFAULT; } + { const a: number = lzma.PRESET_LEVEL_MASK; } + { const a: number = lzma.MF_HC3; } + { const a: number = lzma.MF_HC4; } + { const a: number = lzma.MF_BT2; } + { const a: number = lzma.MF_BT3; } + { const a: number = lzma.MF_BT4; } + { const a: number = lzma.LZMA_TELL_NO_CHECK; } + { const a: number = lzma.LZMA_TELL_UNSUPPORTED_CHECK; } + { const a: number = lzma.LZMA_TELL_ANY_CHECK; } + { const a: number = lzma.LZMA_CONCATENATED; } + { const a: number = lzma.MODE_FAST; } + { const a: number = lzma.MODE_NORMAL; } + { const a: number = lzma.STREAM_HEADER_SIZE; } + + lzma.compress("hello").then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello")).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), lzma.PRESET_DEFAULT).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), {}).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), { blockSize: 4096 }).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), { bufsize: 0 }).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), { check: 0 }).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), { filters: [{ id: "LZMA_FILTER_ARMTHUMB" }] }).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), { flags: 0 }).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), { memlimit: 0 }).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), { preset: 0 }).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), { synchronous: false }).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), { threads: 10 }).then((x: Buffer) => {}); + lzma.compress(Buffer.from("hello"), { timeout: 10 }).then((x: Buffer) => {}); + + { const a: Stream = lzma.compressStream(); } + { const a: Stream = lzma.compressStream(lzma.PRESET_DEFAULT); } + { const a: Stream = lzma.compressStream({}); } + { const a: Stream = lzma.compressStream({ blockSize: 4096 }); } + { const a: Stream = lzma.compressStream({ bufsize: 0 }); } + { const a: Stream = lzma.compressStream({ check: 0 }); } + { const a: Stream = lzma.compressStream({ filters: [{ id: "LZMA_FILTER_ARMTHUMB" }] }); } + { const a: Stream = lzma.compressStream({ flags: 0 }); } + { const a: Stream = lzma.compressStream({ memlimit: 0 }); } + { const a: Stream = lzma.compressStream({ preset: 0 }); } + { const a: Stream = lzma.compressStream({ synchronous: false }); } + { const a: Stream = lzma.compressStream({ threads: 10 }); } + { const a: Stream = lzma.compressStream({ timeout: 10 }); } + + lzma.decompress(Buffer.from("hello")).then((x: Buffer) => {}); + lzma.decompress(Buffer.from("hello"), {}).then((x: Buffer) => {}); + lzma.decompress(Buffer.from("hello"), { memlimit: 100 }).then((x: Buffer) => {}); + + { const a: Stream = lzma.decompressStream(); } + { const a: Stream = lzma.decompressStream({}); } + { const a: Stream = lzma.decompressStream({ memlimit: 100 }); } + } + + namespace xzTests { + const { xz } = compressor; + type Stream = adone.compressor.I.lzma.Stream; + + { const a: boolean = xz.asyncCodeAvailable; } + { const a: number = xz.versionNumber(); } + { const a: string = xz.versionString(); } + { const a: boolean = xz.checkIsSupported(xz.CHECK_CRC32); } + { const a: number = xz.checkSize(xz.CHECK_CRC32); } + { const a: boolean = xz.filterDecoderIsSupported(xz.FILTER_ARM); } + { const a: boolean = xz.filterEncoderIsSupported(xz.FILTER_ARM); } + { const a: boolean = xz.mfIsSupported(xz.MF_BT2); } + { const a: number = xz.rawEncoderMemusage([{ id: "LZMA_FILTER_DELTA", dist: 1 }]); } + { const a: number = xz.rawDecoderMemusage([{ id: "LZMA_FILTER_DELTA", dist: 1 }]); } + { const a: number = xz.easyEncoderMemusage(xz.PRESET_DEFAULT); } + { const a: number = xz.easyDecoderMemusage(xz.PRESET_EXTREME); } + + { + const a: Stream = xz.createStream("easyEncoder"); + { const b: number = a.bufsize; } + { const b: number = a.totalIn(); } + { const b: number = a.totalOut(); } + a.cleanup(); + a.push("1"); + a.write("1"); + a.end(); + a.destroy(); + } + { const a: Stream = xz.createStream("easyEncoder", xz.PRESET_DEFAULT); } + { const a: Stream = xz.createStream("easyEncoder", {}); } + { const a: Stream = xz.createStream("easyEncoder", { check: xz.CHECK_CRC32 }); } + { const a: Stream = xz.createStream("easyEncoder", { preset: xz.PRESET_EXTREME }); } + + { const a: Stream = xz.createStream("autoDecoder"); } + { const a: Stream = xz.createStream("autoDecoder", {}); } + { const a: Stream = xz.createStream("autoDecoder", { flags: xz.LZMA_TELL_NO_CHECK }); } + { const a: Stream = xz.createStream("autoDecoder", { memlimit: 1000 }); } + + { const a: Stream = xz.createStream("aloneEncoder"); } + { const a: Stream = xz.createStream("aloneEncoder", xz.PRESET_DEFAULT); } + { const a: Stream = xz.createStream("aloneEncoder", {}); } + { const a: Stream = xz.createStream("aloneEncoder", { blockSize: 4096 }); } + { const a: Stream = xz.createStream("aloneEncoder", { bufsize: 100 }); } + { const a: Stream = xz.createStream("aloneEncoder", { check: 0 }); } + { const a: Stream = xz.createStream("aloneEncoder", { flags: 0 }); } + { const a: Stream = xz.createStream("aloneEncoder", { memlimit: 0 }); } + { const a: Stream = xz.createStream("aloneEncoder", { preset: 1 }); } + { const a: Stream = xz.createStream("aloneEncoder", { synchronous: true }); } + { const a: Stream = xz.createStream("aloneEncoder", { threads: 10 }); } + { const a: Stream = xz.createStream("aloneEncoder", { timeout: 1 }); } + + { const a: Stream = xz.createStream("aloneDecoder"); } + { const a: Stream = xz.createStream("aloneDecoder", {}); } + { const a: Stream = xz.createStream("aloneDecoder", { memlimit: 1000 }); } + + { const a: Stream = xz.createStream("rawEncoder"); } + { const a: Stream = xz.createStream("rawEncoder", {}); } + { const a: Stream = xz.createStream("rawEncoder", { filters: [{ id: "LZMA_FILTER_DELTA" }] }); } + + { const a: Stream = xz.createStream("rawDecoder"); } + { const a: Stream = xz.createStream("rawDecoder", {}); } + { const a: Stream = xz.createStream("rawDecoder", { filters: [{ id: "LZMA_FILTER_DELTA" }] }); } + + { const a: Stream = xz.createStream("streamEncoder"); } + { const a: Stream = xz.createStream("streamEncoder", {}); } + { const a: Stream = xz.createStream("streamEncoder", { check: xz.CHECK_CRC64 }); } + { const a: Stream = xz.createStream("streamEncoder", { filters: [{ id: "LZMA_FILTER_DELTA" }] }); } + + { const a: Stream = xz.createStream("streamDecoder"); } + { const a: Stream = xz.createStream("streamDecoder", {}); } + { const a: Stream = xz.createStream("streamDecoder", { flags: xz.LZMA_CONCATENATED }); } + { const a: Stream = xz.createStream("streamDecoder", { memlimit: 100 }); } + + xz.singleStringCoding( + xz.createStream("streamDecoder"), + "hello" + ).then((x: Buffer) => {}); + + xz.singleStringCoding( + xz.createStream("streamDecoder"), + Buffer.from("hello") + ).then((x: Buffer) => {}); + + xz.singleStringCoding( + xz.createStream("streamDecoder"), + "hello", + (err: any, data: Buffer) => {} + ).then((x: Buffer) => {}); + + xz.singleStringCoding( + xz.createStream("streamDecoder"), + "hello", + (err: any, data: Buffer) => {}, + (x: number) => {} + ).then((x: Buffer) => {}); + + { const a: number = xz.CHECK_CRC32; } + { const a: number = xz.CHECK_CRC64; } + { const a: number = xz.CHECK_NONE; } + { const a: number = xz.CHECK_SHA256; } + { const a: string = xz.FILTERS_MAX; } + { const a: string = xz.FILTER_ARM; } + { const a: string = xz.FILTER_ARMTHUMB; } + { const a: string = xz.FILTER_IA64; } + { const a: string = xz.FILTER_POWERPC; } + { const a: string = xz.FILTER_SPARC; } + { const a: string = xz.FILTER_X86; } + { const a: string = xz.FILTER_DELTA; } + { const a: string = xz.FILTER_LZMA1; } + { const a: string = xz.FILTER_LZMA2; } + { const a: number = xz.PRESET_EXTREME; } + { const a: number = xz.PRESET_DEFAULT; } + { const a: number = xz.PRESET_LEVEL_MASK; } + { const a: number = xz.MF_HC3; } + { const a: number = xz.MF_HC4; } + { const a: number = xz.MF_BT2; } + { const a: number = xz.MF_BT3; } + { const a: number = xz.MF_BT4; } + { const a: number = xz.LZMA_TELL_NO_CHECK; } + { const a: number = xz.LZMA_TELL_UNSUPPORTED_CHECK; } + { const a: number = xz.LZMA_TELL_ANY_CHECK; } + { const a: number = xz.LZMA_CONCATENATED; } + { const a: number = xz.MODE_FAST; } + { const a: number = xz.MODE_NORMAL; } + { const a: number = xz.STREAM_HEADER_SIZE; } + + xz.compress("hello").then((x: Buffer) => {}); + xz.compress(Buffer.from("hello")).then((x: Buffer) => {}); + xz.compress(Buffer.from("hello"), xz.PRESET_DEFAULT).then((x: Buffer) => {}); + xz.compress(Buffer.from("hello"), {}).then((x: Buffer) => {}); + xz.compress(Buffer.from("hello"), { check: xz.CHECK_CRC32 }).then((x: Buffer) => {}); + xz.compress(Buffer.from("hello"), { preset: xz.PRESET_EXTREME }).then((x: Buffer) => {}); + + { const a: Stream = xz.compressStream(); } + { const a: Stream = xz.compressStream(xz.PRESET_DEFAULT); } + { const a: Stream = xz.compressStream({}); } + { const a: Stream = xz.compressStream({ check: xz.CHECK_CRC64 }); } + { const a: Stream = xz.compressStream({ preset: xz.PRESET_LEVEL_MASK }); } + + xz.decompress(Buffer.from("hello")).then((x: Buffer) => {}); + xz.decompress(Buffer.from("hello"), {}).then((x: Buffer) => {}); + xz.decompress(Buffer.from("hello"), { flags: xz.LZMA_CONCATENATED }).then((x: Buffer) => {}); + xz.decompress(Buffer.from("hello"), { memlimit: 100 }).then((x: Buffer) => {}); + + { const a: Stream = xz.decompressStream(); } + { const a: Stream = xz.decompressStream({}); } + { const a: Stream = xz.decompressStream({ flags: xz.LZMA_TELL_ANY_CHECK }); } + { const a: Stream = xz.decompressStream({ memlimit: 100 }); } + } +} diff --git a/types/adone/test/glosses/data.ts b/types/adone/test/glosses/data.ts new file mode 100644 index 0000000000..e8ccedddcc --- /dev/null +++ b/types/adone/test/glosses/data.ts @@ -0,0 +1,566 @@ +namespace dataTests { + const { data } = adone; + + namespace jsonTests { + const { json } = data; + + { const a: Buffer = json.encode(1); } + { const a: Buffer = json.encode({}); } + { const a: Buffer = json.encode([]); } + { const a: Buffer = json.encode(1, {}); } + { const a: Buffer = json.encode(1, { replacer: ["a", "b", "c"] }); } + { const a: Buffer = json.encode(1, { replacer: (k: string, v: any) => null }); } + { const a: Buffer = json.encode(1, { space: " " }); } + + json.decode("123"); + json.decode(Buffer.from("123")); + + { const a: string = json.encodeStable({ a: 1 }); } + { const a: string = json.encodeStable({ a: 1 }, {}); } + json.encodeStable({ a: 1 }, { + cmp: (a, b) => { + a.key + "1"; + a.value; + b.key + "1"; + a.value; + return 2; + } + }); + json.encodeStable({ a: 1 }, { + cycles: true + }); + json.encodeStable({ a: 1 }, { + replacer: ["a", "b"] + }); + json.encodeStable({ a: 1 }, { + replacer: (key: string, value: any) => null + }); + json.encodeStable({ a: 1 }, { + space: " " + }); + { const a: string = json.encodeSafe({ a: 1 }); } + json.decode("hello"); + } + + namespace mpakTests { + const { mpak } = data; + + { const a: Buffer = mpak.encode({ a: 1 }); } + mpak.decode("hello"); + mpak.decode(adone.collection.ByteArray.wrap("hello")); + mpak.decode(Buffer.from("123")); + mpak.decode(new Uint8Array(10)); + mpak.decode(new ArrayBuffer(10)); + + new mpak.Encoder([]); + new mpak.Encoder([{ + type: 10, + check: () => true, + encode: () => new adone.collection.ByteArray(10) + }]); + { const a: adone.collection.ByteArray = new mpak.Encoder([]).encode("hello"); } + { const a: adone.collection.ByteArray = new mpak.Encoder([]).encode("hello", new adone.collection.ByteArray(10)).flip(); } + + new mpak.Decoder([]); + new mpak.Decoder([{ + type: 10, + decode: (buf: adone.collection.ByteArray) => null + }]); + new mpak.Decoder([]).decode("hello"); + new mpak.Decoder([]).decode(adone.collection.ByteArray.wrap("hello")); + new mpak.Decoder([]).decode(Buffer.from("123")); + new mpak.Decoder([]).decode(new Uint8Array(10)); + new mpak.Decoder([]).decode(new ArrayBuffer(10)); + new mpak.Decoder([]).tryDecode(adone.collection.ByteArray.wrap("hello")); + + { const a: adone.data.mpak.Encoder = new mpak.Serializer().encoder; } + { const a: adone.data.mpak.Decoder = new mpak.Serializer().decoder; } + { const a: adone.data.mpak.Serializer = new mpak.Serializer().registerEncoder(10, (x) => true, (x) => new adone.collection.ByteArray(10)); } + { const a: adone.data.mpak.Serializer = new mpak.Serializer().registerDecoder(10, (buf: adone.collection.ByteArray) => null); } + { const a: adone.data.mpak.Serializer = new mpak.Serializer().register(10, Date, (x: Date) => x, (buf: adone.collection.ByteArray) => null); } + new mpak.Serializer().encode(123); + new mpak.Serializer().encode(123, new adone.collection.ByteArray(10)); + + class ExByteArray extends adone.collection.ByteArray { + fafa() { + return "I am useful!"; + } + } + + new mpak.Serializer().encode(123, new ExByteArray(10)).fafa(); + + new mpak.Serializer().decode("hello"); + new mpak.Serializer().decode(adone.collection.ByteArray.wrap("hello")); + new mpak.Serializer().decode(Buffer.from("123")); + new mpak.Serializer().decode(new Uint8Array(10)); + new mpak.Serializer().decode(new ArrayBuffer(10)); + + { const a: adone.data.mpak.Serializer = mpak.serializer; } + } + + namespace json5Tests { + const { json5 } = data; + + { const a: Buffer = json5.encode(123); } + { const a: Buffer = json5.encode(123, {}); } + { const a: Buffer = json5.encode(123, { replacer: (key: string, value: any) => null }); } + { const a: Buffer = json5.encode(123, { replacer: ["a", "b", "c"] }); } + { const a: Buffer = json5.encode(123, { space: " " }); } + json5.decode("hello"); + json5.decode(Buffer.from("hello")); + json5.decode(Buffer.from("hello"), (holder: object, key: string, value: any) => null); + } + + namespace base64Tests { + const { base64 } = data; + + { const a: Buffer = base64.encode("string"); } + { const a: Buffer = base64.encode(Buffer.from("string")); } + { const a: string = base64.encode("string", { buffer: false }); } + { const a: Buffer = base64.encode("string", { buffer: true }); } + { const a: Buffer = base64.encode("string", {}); } + + { const a: string = base64.decode("string"); } + { const a: string = base64.decode(Buffer.from("string")); } + { const a: string = base64.decode("string", {}); } + { const a: string = base64.decode("string", { buffer: false }); } + { const a: Buffer = base64.decode("string", { buffer: true }); } + + { const a: string = base64.encodeVLQ(123); } + { const a: number = base64.decodeVLQ("H"); } + { const a: number = base64.decodeVLQ("H", 1); } + { const a: number = base64.decodeVLQ("H", 1, false); } + { const a: { value: number, index: number } = base64.decodeVLQ("H", 1, true); } + + { const a: number = base64.decodeCharCode("C"); } + { const a: string = base64.decodeNumber(12); } + } + + namespace yamlTests { + const { yaml } = data; + + namespace loaderTests { + const { loader } = yaml; + + loader.loadAll("hello")[0]; + loader.loadAll(Buffer.from("hello"))[0]; + loader.loadAll("hello", (doc) => 123); + loader.loadAll("hello", undefined, {}); + loader.loadAll("hello", undefined, { filename: "hello" }); + loader.loadAll("hello", undefined, { json: true }); + loader.loadAll("hello", undefined, { onWarning: (warn) => null }); + loader.loadAll("hello", undefined, { schema: yaml.schema.CORE }); + + { const a: any = loader.load("hello"); } + { const a: any = loader.load(Buffer.from("hello")); } + loader.load("hello", {}); + loader.load("hello", { filename: "hello" }); + loader.load("hello", { json: true }); + loader.load("hello", { onWarning: (warn) => null }); + loader.load("hello", { schema: yaml.schema.DEFAULT_FULL }); + + loader.safeLoadAll("hello")[0]; + loader.safeLoadAll(Buffer.from("hello"))[0]; + loader.safeLoadAll(Buffer.from("hello"))[0]; + + loader.safeLoadAll("hello", (doc) => null); + loader.safeLoadAll("hello", undefined, {})[0]; + loader.safeLoadAll("hello", undefined, { filename: "hello" })[0]; + loader.safeLoadAll("hello", undefined, { json: true })[0]; + loader.safeLoadAll("hello", undefined, { onWarning: (warn) => null })[0]; + loader.safeLoadAll("hello", undefined, { schema: yaml.schema.JSON })[0]; + + loader.safeLoad("hello"); + loader.safeLoad(Buffer.from("hello")); + loader.safeLoad("hello", { filename: "hello" }); + loader.safeLoad("hello", { json: true }); + loader.safeLoad("hello", { onWarning: (warn) => null }); + loader.safeLoad("hello", { schema: yaml.schema.DEFAULT_SAFE }); + } + + namespace dumperTests { + const { dumper } = yaml; + { const a: string = dumper.dump("hello"); } + { const a: string = dumper.dump(Buffer.from("hello")); } + { const a: string = dumper.dump("hello", {}); } + { const a: string = dumper.dump("hello", { condenseFlow: true }); } + { const a: string = dumper.dump("hello", { flowLevel: 1 }); } + { const a: string = dumper.dump("hello", { indent: 4 }); } + { const a: string = dumper.dump("hello", { lineWidth: 80 }); } + { const a: string = dumper.dump("hello", { noCompatMode: true }); } + { const a: string = dumper.dump("hello", { noRefs: false }); } + { const a: string = dumper.dump("hello", { schema: yaml.schema.CORE }); } + { const a: string = dumper.dump("hello", { skipInvalid: true }); } + { const a: string = dumper.dump("hello", { sortKeys: true }); } + { const a: string = dumper.dump("hello", { styles: { a: "h" } }); } + { const a: string = dumper.safeDump("hello"); } + { const a: string = dumper.safeDump(Buffer.from("hello")); } + { const a: string = dumper.safeDump("hello", {}); } + { const a: string = dumper.safeDump("hello", { condenseFlow: true }); } + { const a: string = dumper.safeDump("hello", { flowLevel: 1 }); } + { const a: string = dumper.safeDump("hello", { indent: 4 }); } + { const a: string = dumper.safeDump("hello", { lineWidth: 80 }); } + { const a: string = dumper.safeDump("hello", { noCompatMode: true }); } + { const a: string = dumper.safeDump("hello", { noRefs: false }); } + { const a: string = dumper.safeDump("hello", { schema: yaml.schema.CORE }); } + { const a: string = dumper.safeDump("hello", { skipInvalid: true }); } + { const a: string = dumper.safeDump("hello", { sortKeys: true }); } + { const a: string = dumper.safeDump("hello", { styles: { a: "h" } }); } + } + + namespace typeTests { + const { type } = yaml; + + new type.Type("tag", { kind: "scalar" }); + new type.Type("tag", { kind: "sequence" }); + new type.Type("tag", { kind: "mapping" }); + new type.Type("tag", { kind: "scalar", resolve: (a: string) => true }); + new type.Type("tag", { kind: "scalar", construct: (a: string) => null }); + new type.Type("tag", { kind: "scalar", instanceOf: Date }); + new type.Type("tag", { kind: "scalar", predicate: (a) => true }); + new type.Type("tag", { kind: "scalar", represent: (a, s: string) => "asd" }); + new type.Type("tag", { kind: "scalar", represent: { check: (a, s: string) => "asd" } }); + new type.Type("tag", { kind: "scalar", defaultStyle: "asd" }); + new type.Type("tag", { kind: "scalar", styleAliases: {} }); + new type.Type("tag", { kind: "scalar" }).construct("hello") + 1; + !new type.Type("tag", { kind: "scalar" }).resolve("hello"); + new type.Type("tag", { kind: "scalar" }).instanceOf; + new type.Type("tag", { kind: "scalar" }).predicate; + new type.Type("tag", { kind: "scalar" }).represent; + new type.Type("tag", { kind: "scalar" }).defaultStyle; + new type.Type("tag", { kind: "scalar" }).styleAliases; + type.Binary.construct("hello").fill(0); + { const a: boolean = type.Bool.construct("hello"); } + type.Float.construct("hello") + 3.14; + type.Int.construct("hello") + 3; + type.Map.construct("hello"); + type.Merge.construct("hello"); + type.Null.construct("hello") === null; + type.Omap.construct("hello")[0]; + type.Pairs.construct("hello")[0][0].charCodeAt(0); + type.Seq.construct("hello")[0]; + type.Set.construct("hello"); + type.Str.construct("hello").charAt(0); + type.Timestamp.construct("hello").getFullYear(); + type.js.Function.construct("hello").apply(null, [1, 2, 3]); + type.js.RegExp.construct("hello").test("123"); + type.js.Undefined.construct("hello") === undefined; + } + + namespace schemaTests { + const { schema } = yaml; + + new schema.Schema({}); + new schema.Schema({ + include: [ + schema.CORE + ] + }); + new schema.Schema({ + implicit: [ + yaml.type.Int + ] + }); + new schema.Schema({ + explicit: [ + yaml.type.Int + ] + }); + { const a: adone.data.yaml.schema.Schema = new schema.Schema().include[0]; } + { const a: adone.data.yaml.type.Type = new schema.Schema().implicit[0]; } + { const a: adone.data.yaml.type.Type = new schema.Schema().explicit[0]; } + { const a: adone.data.yaml.type.Type = new schema.Schema().compiledImplicit[0]; } + { const a: adone.data.yaml.type.Type = new schema.Schema().compiledExplicit[0]; } + { const a: adone.data.yaml.type.Type = new schema.Schema().compiledTypeMap.scalar.hello; } + { const a: adone.data.yaml.type.Type = new schema.Schema().compiledTypeMap.sequence.hello; } + { const a: adone.data.yaml.type.Type = new schema.Schema().compiledTypeMap.mapping.hello; } + { const a: adone.data.yaml.type.Type = new schema.Schema().compiledTypeMap.fallback.hello; } + + { const a: adone.data.yaml.schema.Schema = schema.create(schema.CORE, yaml.type.Binary); } + { const a: adone.data.yaml.schema.Schema = schema.create([schema.CORE], [yaml.type.Binary]); } + + { const a: adone.data.yaml.schema.Schema = schema.CORE; } + { const a: adone.data.yaml.schema.Schema = schema.DEFAULT_FULL; } + { const a: adone.data.yaml.schema.Schema = schema.DEFAULT_SAFE; } + { const a: adone.data.yaml.schema.Schema = schema.FAILSAFE; } + { const a: adone.data.yaml.schema.Schema = schema.JSON; } + } + + const mark = new yaml.Mark("hello", "hello", 1, 2, 3); + { const a: string = mark.getSnippet(); } + { const a: string = mark.getSnippet(1); } + { const a: string = mark.getSnippet(1, 1); } + { const a: string = mark.toString(); } + { const a: string = mark.toString(true); } + { const a: string = new yaml.Exception("message", mark).reason; } + { const a: adone.data.yaml.Mark = new yaml.Exception("message", mark).mark; } + + { const a: Buffer = yaml.encode("hello"); } + { const a: Buffer = yaml.encode("hello", {}); } + { const a: Buffer = yaml.encode("hello", { condenseFlow: true }); } + { const a: Buffer = yaml.encode("hello", { flowLevel: -1 }); } + { const a: Buffer = yaml.encode("hello", { indent: 3 }); } + { const a: Buffer = yaml.encode("hello", { lineWidth: 80 }); } + { const a: Buffer = yaml.encode("hello", { noCompatMode: true }); } + { const a: Buffer = yaml.encode("hello", { noRefs: true }); } + { const a: Buffer = yaml.encode("hello", { schema: yaml.schema.CORE }); } + { const a: Buffer = yaml.encode("hello", { skipInvalid: true }); } + { const a: Buffer = yaml.encode("hello", { sortKeys: true }); } + { const a: Buffer = yaml.encode("hello", { styles: {} }); } + + yaml.decode("hello"); + yaml.decode(Buffer.from("hello")); + yaml.decode("hello", {}); + yaml.decode("hello", { filename: "hello" }); + yaml.decode("hello", { json: true }); + yaml.decode("hello", { onWarning: (warn) => null }); + yaml.decode("hello", { schema: yaml.schema.CORE }); + + yaml.loadAll("hello")[0]; + yaml.loadAll(Buffer.from("hello"))[0]; + yaml.loadAll("hello", (doc) => 123); + yaml.loadAll("hello", undefined, {}); + yaml.loadAll("hello", undefined, { filename: "hello" }); + yaml.loadAll("hello", undefined, { json: true }); + yaml.loadAll("hello", undefined, { onWarning: (warn) => null }); + yaml.loadAll("hello", undefined, { schema: yaml.schema.CORE }); + + { const a: any = yaml.load("hello"); } + { const a: any = yaml.load(Buffer.from("hello")); } + yaml.load("hello", {}); + yaml.load("hello", { filename: "hello" }); + yaml.load("hello", { json: true }); + yaml.load("hello", { onWarning: (warn) => null }); + yaml.load("hello", { schema: yaml.schema.DEFAULT_FULL }); + + yaml.safeLoadAll("hello")[0]; + yaml.safeLoadAll(Buffer.from("hello"))[0]; + yaml.safeLoadAll(Buffer.from("hello"))[0]; + + yaml.safeLoadAll("hello", (doc) => null); + yaml.safeLoadAll("hello", undefined, {})[0]; + yaml.safeLoadAll("hello", undefined, { filename: "hello" })[0]; + yaml.safeLoadAll("hello", undefined, { json: true })[0]; + yaml.safeLoadAll("hello", undefined, { onWarning: (warn) => null })[0]; + yaml.safeLoadAll("hello", undefined, { schema: yaml.schema.JSON })[0]; + + yaml.safeLoad("hello"); + yaml.safeLoad(Buffer.from("hello")); + yaml.safeLoad("hello", { filename: "hello" }); + yaml.safeLoad("hello", { json: true }); + yaml.safeLoad("hello", { onWarning: (warn) => null }); + yaml.safeLoad("hello", { schema: yaml.schema.DEFAULT_SAFE }); + + { const a: string = yaml.dump("hello"); } + { const a: string = yaml.dump(Buffer.from("hello")); } + { const a: string = yaml.dump("hello", {}); } + { const a: string = yaml.dump("hello", { condenseFlow: true }); } + { const a: string = yaml.dump("hello", { flowLevel: 1 }); } + { const a: string = yaml.dump("hello", { indent: 4 }); } + { const a: string = yaml.dump("hello", { lineWidth: 80 }); } + { const a: string = yaml.dump("hello", { noCompatMode: true }); } + { const a: string = yaml.dump("hello", { noRefs: false }); } + { const a: string = yaml.dump("hello", { schema: yaml.schema.CORE }); } + { const a: string = yaml.dump("hello", { skipInvalid: true }); } + { const a: string = yaml.dump("hello", { sortKeys: true }); } + { const a: string = yaml.dump("hello", { styles: { a: "h" } }); } + { const a: string = yaml.safeDump("hello"); } + { const a: string = yaml.safeDump(Buffer.from("hello")); } + { const a: string = yaml.safeDump("hello", {}); } + { const a: string = yaml.safeDump("hello", { condenseFlow: true }); } + { const a: string = yaml.safeDump("hello", { flowLevel: 1 }); } + { const a: string = yaml.safeDump("hello", { indent: 4 }); } + { const a: string = yaml.safeDump("hello", { lineWidth: 80 }); } + { const a: string = yaml.safeDump("hello", { noCompatMode: true }); } + { const a: string = yaml.safeDump("hello", { noRefs: false }); } + { const a: string = yaml.safeDump("hello", { schema: yaml.schema.CORE }); } + { const a: string = yaml.safeDump("hello", { skipInvalid: true }); } + { const a: string = yaml.safeDump("hello", { sortKeys: true }); } + { const a: string = yaml.safeDump("hello", { styles: { a: "h" } }); } + } + + namespace bsonTests { + const { bson } = data; + + new bson.Binary(10); + { const a: string = new bson.Binary(10)._bsontype; } + new bson.Binary(Buffer.from("hello")); + new bson.Binary(Buffer.from("hello"), 10); + new bson.Binary(10).put(0); + new bson.Binary(10).write("hello"); + new bson.Binary(10).write("hello", 0); + new bson.Binary(10).write(Buffer.from("hello")); + new bson.Binary(10).read(10); + new bson.Binary(10).read(10, 0); + { const a: Buffer = new bson.Binary(10).value(true); } + { const a: string = new bson.Binary(10).value(); } + { const a: number = new bson.Binary(10).length(); } + { const a: string = new bson.Binary(10).toJSON(); } + { const a: string = new bson.Binary(10).toString(); } + { const a: number = bson.Binary.BUFFER_SIZE; } + { const a: number = bson.Binary.SUBTYPE_DEFAULT; } + { const a: number = bson.Binary.SUBTYPE_FUNCTION; } + { const a: number = bson.Binary.SUBTYPE_BYTE_ARRAY; } + { const a: number = bson.Binary.SUBTYPE_UUID_OLD; } + { const a: number = bson.Binary.SUBTYPE_UUID; } + { const a: number = bson.Binary.SUBTYPE_MD5; } + { const a: number = bson.Binary.SUBTYPE_USER_DEFINED; } + + new bson.Code("hello"); + { const a: string = new bson.Code("hello")._bsontype; } + new bson.Code("hello", {}); + { const a: object = new bson.Code("hello").toJSON().scope; } + { const a: string = new bson.Code("hello").toJSON().code; } + + new bson.DBRef("aa", new bson.ObjectId()); + { const a: string = new bson.DBRef("aa", new bson.ObjectId())._bsontype; } + new bson.DBRef("aa", new bson.ObjectId(), "hh"); + { const a: string = new bson.DBRef("aa", new bson.ObjectId()).toJSON().$ref; } + { const a: adone.data.bson.ObjectId = new bson.DBRef("aa", new bson.ObjectId()).toJSON().$id; } + { const a: string = new bson.DBRef("aa", new bson.ObjectId()).toJSON().$db; } + + new bson.Decimal128(Buffer.from("0123456789abcdef")); + { const a: string = new bson.Decimal128(Buffer.from("0123456789abcdef"))._bsontype; } + { const a: string = new bson.Decimal128(Buffer.from("0123456789abcdef")).toString(); } + { const a: string = new bson.Decimal128(Buffer.from("0123456789abcdef")).toJSON().$numberDecimal; } + { const a: adone.data.bson.Decimal128 = bson.Decimal128.fromString("123"); } + + new bson.Double(3.14); + { const a: string = new bson.Double(3.14)._bsontype; } + { const a: number = new bson.Double(3.14).valueOf(); } + { const a: number = new bson.Double(3.14).toJSON(); } + + new bson.Int32(100500); + { const a: string = new bson.Int32(100500)._bsontype; } + { const a: number = new bson.Int32(100500).valueOf(); } + { const a: number = new bson.Int32(100500).toJSON(); } + + new bson.Long(); + { const a: string = new bson.Long()._bsontype; } + { const a: adone.data.bson.Long = bson.Long.MIN_VALUE; } + { const a: adone.data.bson.Long = bson.Long.MAX_UNSIGNED_VALUE; } + { const a: adone.data.bson.Long = bson.Long.ZERO; } + { const a: adone.data.bson.Long = bson.Long.UZERO; } + { const a: adone.data.bson.Long = bson.Long.ONCE; } + { const a: adone.data.bson.Long = bson.Long.UONE; } + { const a: adone.data.bson.Long = bson.Long.ONE; } + { const a: adone.data.bson.Long = bson.Long.NEG_ONE; } + + new bson.MaxKey(); + { const a: string = new bson.MaxKey()._bsontype; } + + new bson.MinKey(); + { const a: string = new bson.MinKey()._bsontype; } + + new bson.ObjectId(); + new bson.ObjectId("he"); + new bson.ObjectId(Buffer.from("asd")); + new bson.ObjectId(new bson.ObjectId()); + new bson.ObjectId({ toHexString: () => "2", id: "he" }); + new bson.ObjectId({ toHexString: () => "2", id: Buffer.from("he") }); + new bson.ObjectId({ toHexString: () => "2", id: new bson.ObjectId() }); + { const a: string = new bson.ObjectId().toHexString(); } + { const a: number = new bson.ObjectId().getInc(); } + { const a: Buffer = new bson.ObjectId().generate(); } + { const a: Buffer = new bson.ObjectId().generate(10050); } + { const a: string = new bson.ObjectId().toString(); } + { const a: string = new bson.ObjectId().toString("utf8"); } + { const a: string = new bson.ObjectId().toJSON(); } + new bson.ObjectId().equals("he"); + new bson.ObjectId().equals(Buffer.from("he")); + new bson.ObjectId().equals(new bson.ObjectId()); + new bson.ObjectId().equals({ toHexString: () => "2" }); + { const a: Date = new bson.ObjectId().getTimestamp(); } + { const a: adone.data.bson.ObjectId = bson.ObjectId.createPk(); } + { const a: adone.data.bson.ObjectId = bson.ObjectId.createFromTime(100500); } + { const a: adone.data.bson.ObjectId = bson.ObjectId.createFromHexString("deadbeef"); } + { const a: boolean = bson.ObjectId.isValid("deadbeef"); } + { const a: number = bson.ObjectId.index; } + + new bson.BSONRegExp("\\d"); + new bson.BSONRegExp("\\d", "mix"); + { const a: string = new bson.BSONRegExp("\\d")._bsontype; } + + new bson.Symbol("he"); + { const a: string = new bson.Symbol("he")._bsontype; } + { const a: string = new bson.Symbol("he").valueOf(); } + { const a: string = new bson.Symbol("he").toString(); } + { const a: string = new bson.Symbol("he").inspect(); } + { const a: string = new bson.Symbol("he").toJSON(); } + + new bson.Timestamp(); + new bson.Timestamp(100, 500); + { const a: string = new bson.Timestamp()._bsontype; } + { const a: adone.data.bson.Timestamp = bson.Timestamp.MIN_VALUE; } + { const a: adone.data.bson.Timestamp = bson.Timestamp.MAX_VALUE; } + { const a: adone.data.bson.Timestamp = bson.Timestamp.MAX_UNSIGNED_VALUE; } + { const a: adone.data.bson.Timestamp = bson.Timestamp.ZERO; } + { const a: adone.data.bson.Timestamp = bson.Timestamp.UZERO; } + { const a: adone.data.bson.Timestamp = bson.Timestamp.ONCE; } + { const a: adone.data.bson.Timestamp = bson.Timestamp.ONE; } + { const a: adone.data.bson.Timestamp = bson.Timestamp.UONE; } + { const a: adone.data.bson.Timestamp = bson.Timestamp.NEG_ONE; } + + new bson.BSON(); + new bson.BSON([bson.Timestamp, bson.Binary]); + { const a: Buffer = new bson.BSON().serialize({ a: 1 }); } + { const a: Buffer = new bson.BSON().serialize({ a: 1 }, {}); } + { const a: Buffer = new bson.BSON().serialize({ a: 1 }, { checkKeys: true }); } + { const a: Buffer = new bson.BSON().serialize({ a: 1 }, { ignoreUndefined: true }); } + { const a: Buffer = new bson.BSON().serialize({ a: 1 }, { serializeFunctions: false }); } + { const a: number = new bson.BSON().serializeWithBufferAndIndex({ a: 1 }, Buffer.alloc(10)); } + { const a: number = new bson.BSON().serializeWithBufferAndIndex({ a: 1 }, Buffer.alloc(10), {}); } + { const a: number = new bson.BSON().serializeWithBufferAndIndex({ a: 1 }, Buffer.alloc(10), { checkKeys: true }); } + { const a: number = new bson.BSON().serializeWithBufferAndIndex({ a: 1 }, Buffer.alloc(10), { ignoreUndefined: true }); } + { const a: number = new bson.BSON().serializeWithBufferAndIndex({ a: 1 }, Buffer.alloc(10), { index: 10 }); } + { const a: number = new bson.BSON().serializeWithBufferAndIndex({ a: 1 }, Buffer.alloc(10), { serializeFunctions: false }); } + { const a: number = new bson.BSON().calculateObjectSize({ a: 1 }); } + { const a: number = new bson.BSON().calculateObjectSize({ a: 1 }, {}); } + { const a: number = new bson.BSON().calculateObjectSize({ a: 1 }, { ignoreUndefined: false }); } + { const a: number = new bson.BSON().calculateObjectSize({ a: 1 }, { serializeFunctions: false }); } + new bson.BSON().deserialize(Buffer.from("aahaha")).a; + new bson.BSON().deserialize(Buffer.from("aahaha"), {}).a; + new bson.BSON().deserialize(Buffer.from("aahaha"), { bsonRegExp: false }).a; + new bson.BSON().deserialize(Buffer.from("aahaha"), { cacheFunctions: false }).a; + new bson.BSON().deserialize(Buffer.from("aahaha"), { cacheFunctonsCrc32: false }).a; + new bson.BSON().deserialize(Buffer.from("aahaha"), { evalFunctions: false }).a; + new bson.BSON().deserialize(Buffer.from("aahaha"), { fieldsAsRaw: ["a"] }).a; + new bson.BSON().deserialize(Buffer.from("aahaha"), { promoteBuffers: false }).a; + new bson.BSON().deserialize(Buffer.from("aahaha"), { promoteLongs: false }).a; + new bson.BSON().deserialize(Buffer.from("aahaha"), { promoteValues: true }).a; + { const a: number = new bson.BSON().deserializeStream(Buffer.from("ahaha"), 1, 2, [], 2); } + { const a: number = new bson.BSON().deserializeStream(Buffer.from("ahaha"), 1, 2, [], 2, {}); } + { const a: number = new bson.BSON().deserializeStream(Buffer.from("ahaha"), 1, 2, [], 2, { bsonRegExp: false }); } + { const a: number = new bson.BSON().deserializeStream(Buffer.from("ahaha"), 1, 2, [], 2, { cacheFunctions: false }); } + { const a: number = new bson.BSON().deserializeStream(Buffer.from("ahaha"), 1, 2, [], 2, { cacheFunctonsCrc32: false }); } + { const a: number = new bson.BSON().deserializeStream(Buffer.from("ahaha"), 1, 2, [], 2, { evalFunctions: false }); } + { const a: number = new bson.BSON().deserializeStream(Buffer.from("ahaha"), 1, 2, [], 2, { fieldsAsRaw: ["b"] }); } + { const a: number = new bson.BSON().deserializeStream(Buffer.from("ahaha"), 1, 2, [], 2, { promoteBuffers: false }); } + { const a: number = new bson.BSON().deserializeStream(Buffer.from("ahaha"), 1, 2, [], 2, { promoteLongs: false }); } + { const a: number = new bson.BSON().deserializeStream(Buffer.from("ahaha"), 1, 2, [], 2, { promoteValues: true }); } + { const a: number = bson.c.BSON_INT32_MAX; } + { const a: number = bson.c.BSON_INT32_MIN; } + { const a: number = bson.c.BSON_INT64_MAX; } + { const a: number = bson.c.BSON_INT64_MIN; } + { const a: number = bson.c.JS_INT_MAX; } + { const a: number = bson.c.JS_INT_MIN; } + { const a: adone.data.bson.BSON = bson.serializer; } + + { const a: Buffer = bson.encode({ a: 1 }); } + { const a: Buffer = bson.encode({ a: 1 }, {}); } + { const a: Buffer = bson.encode({ a: 1 }, { checkKeys: true }); } + { const a: Buffer = bson.encode({ a: 1 }, { ignoreUndefined: false }); } + { const a: Buffer = bson.encode({ a: 1 }, { serializeFunctions: false }); } + + bson.decode(bson.encode({ a: 1 })).a; + bson.decode(bson.encode({ a: 1 }), {}).a; + bson.decode(bson.encode({ a: 1 }), { bsonRegExp: false }).a; + bson.decode(bson.encode({ a: 1 }), { cacheFunctions: false }).a; + bson.decode(bson.encode({ a: 1 }), { cacheFunctonsCrc32: false }).a; + bson.decode(bson.encode({ a: 1 }), { evalFunctions: false }).a; + bson.decode(bson.encode({ a: 1 }), { fieldsAsRaw: ["b"] }).a; + bson.decode(bson.encode({ a: 1 }), { promoteBuffers: false }).a; + bson.decode(bson.encode({ a: 1 }), { promoteLongs: false }).a; + bson.decode(bson.encode({ a: 1 }), { promoteValues: true }).a; + } +} diff --git a/types/adone/test/glosses/datetime.ts b/types/adone/test/glosses/datetime.ts new file mode 100644 index 0000000000..e64737b430 --- /dev/null +++ b/types/adone/test/glosses/datetime.ts @@ -0,0 +1,699 @@ +namespace datetimeTests { + const { datetime } = adone; + + { const a: string = datetime.defaultFormat; } + { const a: string = datetime.defaultFormatUtc; } + { const a: adone.I.datetime.Datetime = datetime(); } + datetime(datetime()); + datetime(new Date()); + datetime("hello"); + datetime(123); + datetime([1, 2, 3]); + datetime(["a"]); + datetime(); + datetime({ + y: 1 + }); + datetime({ + year: 1 + }); + datetime({ + years: 1 + }); + datetime({ + month: 1 + }); + datetime({ + months: 1 + }); + datetime({ + M: 1 + }); + datetime({ + days: 1 + }); + datetime({ + day: 1 + }); + datetime({ + d: 1 + }); + datetime({ + y: 1000 + }); + datetime({ + months: 1 + }); + datetime({ + month: 1 + }); + datetime({ + M: 1 + }); + datetime({ + days: 1 + }); + datetime({ + day: 1 + }); + datetime({ + d: 1 + }); + datetime({ + dates: 1 + }); + datetime({ + date: 1 + }); + datetime({ + D: 1 + }); + datetime({ + hours: 1 + }); + datetime({ + hour: 1 + }); + datetime({ + h: 1 + }); + datetime({ + minutes: 1 + }); + datetime({ + minute: 1 + }); + datetime({ + m: 1 + }); + datetime({ + seconds: 1 + }); + datetime({ + second: 1 + }); + datetime({ + s: 1 + }); + datetime({ + milliseconds: 1 + }); + datetime({ + millisecond: 1 + }); + datetime({ + ms: 1 + }); + datetime(101, "DD MM"); + datetime(101, "DD MM", true); + datetime(101, undefined, true); + datetime(101, undefined, "ru", true); + datetime.utc(datetime()); + datetime.utc(new Date()); + datetime.utc("hello"); + datetime.utc(123); + datetime.utc([1, 2, 3]); + datetime.utc(["a"]); + datetime.utc(); + datetime.utc({ + y: 1 + }); + datetime.utc({ + year: 1 + }); + datetime.utc({ + years: 1 + }); + datetime.utc({ + month: 1 + }); + datetime.utc({ + months: 1 + }); + datetime.utc({ + M: 1 + }); + datetime.utc({ + days: 1 + }); + datetime({ + day: 1 + }); + datetime.utc({ + d: 1 + }); + datetime.utc({ + y: 1000 + }); + datetime.utc({ + months: 1 + }); + datetime({ + month: 1 + }); + datetime.utc({ + M: 1 + }); + datetime.utc({ + days: 1 + }); + datetime.utc({ + day: 1 + }); + datetime.utc({ + d: 1 + }); + datetime.utc({ + dates: 1 + }); + datetime.utc({ + date: 1 + }); + datetime({ + D: 1 + }); + datetime.utc({ + hours: 1 + }); + datetime.utc({ + hour: 1 + }); + datetime.utc({ + h: 1 + }); + datetime.utc({ + minutes: 1 + }); + datetime.utc({ + minute: 1 + }); + datetime.utc({ + m: 1 + }); + datetime.utc({ + seconds: 1 + }); + datetime.utc({ + second: 1 + }); + datetime.utc({ + s: 1 + }); + datetime.utc({ + milliseconds: 1 + }); + datetime.utc({ + millisecond: 1 + }); + datetime.utc({ + ms: 1 + }); + datetime.utc(101, "DD MM"); + datetime.utc(101, "DD MM", true); + datetime.utc(101, undefined, true); + datetime.utc(101, undefined, "ru", true); + datetime.unix(101010).clone(); + + datetime.dos({ time: 100, date: 100 }).clone(); + + datetime.invalid(); + datetime.invalid({ charsLeftOver: 100 }); + datetime.invalid({ empty: true }); + datetime.invalid({ invalidFormat: false }); + datetime.invalid({ invalidMonth: "jan" }); + datetime.invalid({ iso: false }); + datetime.invalid({ meridiem: "am" }); + datetime.invalid({ nullInput: false }); + datetime.invalid({ overflow: 1 }); + datetime.invalid({ parsedDateParts: [1] }); + datetime.invalid({ unusedInput: ["1"] }); + datetime.invalid({ unusedTokens: ["1"] }); + datetime.invalid({ userInvalidated: false }); + datetime.isDuration(12); + { const a: string = datetime.locale(); } + { const a: string = datetime.locale("he"); } + { const a: string = datetime.locale(["he"]); } + { const a: string = datetime.locale("he", {}); } + { const a: string = datetime.locale("he", { calendar: { lastDay: "ha" } }); } + { const a: string = datetime.locale("he", { calendar: { lastWeek: "ha" } }); } + { const a: string = datetime.locale("he", { calendar: { nextDay: "ha" } }); } + { const a: string = datetime.locale("he", { calendar: { nextWeek: "ha" } }); } + { const a: string = datetime.locale("he", { calendar: { sameDay: "ha" } }); } + { const a: string = datetime.locale("he", { calendar: { sameElse: "ha" } }); } + { const a: string = datetime.locale("he", { invalidDate: "ha" }); } + { const a: string = datetime.locale("he", { isPM: (x: string) => true }); } + { + const a: string = datetime.locale("he", { + longDateFormat: { + l: "", ll: "", lll: "", llll: "", + L: "", LL: "", LLL: "", LLLL: "", + LT: "", lt: "", LTS: "", lts: "" + } + }); + } + { const a: string = datetime.locale("he", { meridiem: (hour: number, minute: number, isLower: boolean) => "ba" }); } + { const a: string = datetime.locale("he", { meridiemParse: /ab/ }); } + + { const a: string = datetime.locale("he", { monthsShort: ["a"] }); } + { + const a: string = datetime.locale("he", { + monthsShort: { + format: ["1"], + standalone: ["1"], + isFormat: /a/ + } + }); + } + { + const a: string = datetime.locale("he", { + monthsShort: (d) => d.clone() && "123" + }); + const b: string = datetime.locale("he", { + monthsShort: (d, f?: string) => d.clone() && "123" + }); + } + + { const a: string = datetime.locale("he", { monthsShort: ["a"] }); } + { + const a: string = datetime.locale("he", { + monthsShort: { + format: ["1"], + standalone: ["1"], + isFormat: /a/ + } + }); + } + { + const a: string = datetime.locale("he", { + monthsShort: (d) => d.clone() && "123" + }); + const b: string = datetime.locale("he", { + monthsShort: (d, f?: string) => d.clone() && "123" + }); + } + + { const a: string = datetime.locale("he", { ordinal: (n: number) => "1" }); } + { const a: string = datetime.locale("he", { ordinalParse: /a/ }); } + { + const a: string = datetime.locale("he", { + relativeTime: { + future: "he", + past: "he", + s: "he", + m: "he", + mm: "he", + h: "he", + hh: "he", + d: "he", + dd: "he", + M: "he", + MM: "he", + y: "he", + yy: 'he"' + } + }); + const b: string = datetime.locale("he", { + relativeTime: { + future: (x: string) => "he", + past: (x: string) => "he", + s: (x: number, y: boolean, z: string, a: boolean) => "he", + m: (x: number, y: boolean, z: string, a: boolean) => "he", + mm: (x: number, y: boolean, z: string, a: boolean) => "he", + h: (x: number, y: boolean, z: string, a: boolean) => "he", + hh: (x: number, y: boolean, z: string, a: boolean) => "he", + d: (x: number, y: boolean, z: string, a: boolean) => "he", + dd: (x: number, y: boolean, z: string, a: boolean) => "he", + M: (x: number, y: boolean, z: string, a: boolean) => "he", + MM: (x: number, y: boolean, z: string, a: boolean) => "he", + y: (x: number, y: boolean, z: string, a: boolean) => "he", + yy: (x: number, y: boolean, z: string, a: boolean) => 'he"' + } + }); + } + + { const a: string = datetime.locale("he", { week: { dow: 1, doy: 2 } }); } + + { const a: string = datetime.locale("he", { weekDays: ["a"] }); } + { + const a: string = datetime.locale("he", { + weekDays: { + format: ["1"], + standalone: ["1"], + isFormat: /a/ + } + }); + } + { + const a: string = datetime.locale("he", { + weekDays: (d: adone.I.datetime.Datetime) => d.clone() && "123" + }); + const b: string = datetime.locale("he", { + weekDays: (d: adone.I.datetime.Datetime, f?: string) => d.clone() && "123" + }); + } + + { const a: string = datetime.locale("he", { weekdaysMin: ["a"] }); } + { + const a: string = datetime.locale("he", { + weekdaysMin: { + format: ["1"], + standalone: ["1"], + isFormat: /a/ + } + }); + } + { + const a: string = datetime.locale("he", { + weekdaysMin: (d: adone.I.datetime.Datetime) => d.clone() && "123" + }); + const b: string = datetime.locale("he", { + weekdaysMin: (d: adone.I.datetime.Datetime, f?: string) => d.clone() && "123" + }); + } + + { const a: string = datetime.locale("he", { weekdaysShort: ["a"] }); } + { + const a: string = datetime.locale("he", { + weekdaysShort: { + format: ["1"], + standalone: ["1"], + isFormat: /a/ + } + }); + } + { + const a: string = datetime.locale("he", { + weekdaysShort: (d: adone.I.datetime.Datetime) => d.clone() && "123" + }); + const b: string = datetime.locale("he", { + weekdaysShort: (d: adone.I.datetime.Datetime, f?: string) => d.clone() && "123" + }); + } + + datetime.localeData(); + datetime.localeData("en"); + datetime.localeData(["en"]); + { const a: string = datetime.localeData().calendar(); } + { const a: string = datetime.localeData().calendar("lastDay"); } + { const a: string = datetime.localeData().calendar("lastWeek"); } + { const a: string = datetime.localeData().calendar("nextDay"); } + { const a: string = datetime.localeData().calendar("nextWeek"); } + { const a: string = datetime.localeData().calendar("sameDay"); } + { const a: string = datetime.localeData().calendar("sameElse"); } + { const a: number = datetime.localeData().firstDayOfWeek(); } + { const a: string = datetime.localeData().invalidDate(); } + { const a: boolean = datetime.localeData().isPM("a"); } + { const a: string = datetime.localeData().longDateFormat("LL"); } + { const a: string = datetime.localeData().meridiem(10, 10, true); } + { const a: string[] = datetime.localeData().months(); } + { const a: string = datetime.localeData().months(adone.datetime()); } + { const a: number = datetime.localeData().monthsParse("he", "fa", false); } + { const a: RegExp = datetime.localeData().monthsRegex(false); } + { const a: string[] = datetime.localeData().monthsShort(); } + { const a: string = datetime.localeData().monthsShort(adone.datetime()); } + { const a: RegExp = datetime.localeData().monthsShortRegex(false); } + { const a: number = datetime.localeData().weekdaysParse("he", "fa", true); } + { const a: RegExp = datetime.localeData().weekdaysRegex(true); } + { const a: string[] = datetime.localeData().weekdaysShort(); } + { const a: string = datetime.localeData().weekdaysShort(adone.datetime()); } + { const a: RegExp = datetime.localeData().weekdaysShortRegex(false); } + { const a: adone.I.datetime.Duration = datetime.duration(); } + { const a: adone.I.datetime.Duration = datetime.duration(100, "days"); } + { + const a: adone.I.datetime.Duration = datetime.duration({ + years: 10, + year: 10, + y: 10, + months: 10, + month: 10, + M: 10, + days: 10, + day: 10, + d: 10, + dates: 0, + date: 10, + D: 10, + hours: 10, + hour: 10, + h: 10, + minutes: 10, + minute: 10, + m: 10, + seconds: 10, + second: 10, + s: 10, + milliseconds: 10, + millisecond: 10, + ms: 10, + quarters: 10, + quarter: 10, + Q: 10, + weeks: 10, + week: 10, + w: 10 + }); + { const b: adone.I.datetime.Duration = a.abs(); } + { const b: adone.I.datetime.Duration = a.add(1, "year"); } + { const b: adone.I.datetime.Duration = a.add(1); } + { const b: number = a.as("millisecond"); } + { const b: number = a.asDays(); } + { const b: number = a.asHours(); } + { const b: number = a.asMilliseconds(); } + { const b: number = a.asMinutes(); } + { const b: number = a.asMonths(); } + { const b: number = a.asSeconds(); } + { const b: number = a.asWeeks(); } + { const b: number = a.asYears(); } + { const b: number = a.days(); } + { const b: number = a.get("year"); } + { const b: number = a.hours(); } + { const b: string = a.humanize(); } + { const b: string = a.humanize(false); } + { const b: string = a.locale(); } + { const b: adone.I.datetime.Locale = a.localeData(); } + { const b: number = a.milliseconds(); } + { const b: number = a.minutes(); } + { const b: number = a.months(); } + { const b: number = a.seconds(); } + { const b: adone.I.datetime.Duration = a.subtract(1, "minute"); } + { const b: string = a.toISOString(); } + { const b: string = a.toJSON(); } + { const b: number = a.weeks(); } + { const b: number = a.years(); } + } + + { const a: adone.I.datetime.Datetime = datetime.parseZone(1230, "DD"); } + { const a: adone.I.datetime.Datetime = datetime.parseZone(1230, "DD", false); } + { const a: adone.I.datetime.Datetime = datetime.parseZone(1230, "DD", "en", false); } + + { const a: string[] = datetime.months(); } + { const a: string = datetime.months(1); } + { const a: string = datetime.months("format", 1); } + + { const a: string[] = datetime.monthsShort(); } + { const a: string = datetime.monthsShort(1); } + { const a: string = datetime.monthsShort("format", 1); } + + { const a: string[] = datetime.weekdays(); } + { const a: string = datetime.weekdays(1); } + { const a: string[] = datetime.weekdays("format"); } + { const a: string = datetime.weekdays("format", 1); } + { const a: string[] = datetime.weekdays(true); } + { const a: string = datetime.weekdays(true, 1); } + { const a: string = datetime.weekdays(true, "format", 1); } + + { const a: string[] = datetime.weekdaysShort(); } + { const a: string = datetime.weekdaysShort(1); } + { const a: string[] = datetime.weekdaysShort("format"); } + { const a: string = datetime.weekdaysShort("format", 1); } + { const a: string[] = datetime.weekdaysShort(true); } + { const a: string = datetime.weekdaysShort(true, 1); } + { const a: string = datetime.weekdaysShort(true, "format", 1); } + + { const a: string[] = datetime.weekdaysMin(); } + { const a: string = datetime.weekdaysMin(1); } + { const a: string[] = datetime.weekdaysMin("format"); } + { const a: string = datetime.weekdaysMin("format", 1); } + { const a: string[] = datetime.weekdaysMin(true); } + { const a: string = datetime.weekdaysMin(true, 1); } + { const a: string = datetime.weekdaysMin(true, "format", 1); } + + { const a: adone.I.datetime.Datetime = adone.datetime.min(adone.datetime(), adone.datetime()); } + { const a: adone.I.datetime.Datetime = adone.datetime.max(adone.datetime(), adone.datetime()); } + { const a: number = adone.datetime.now(); } + { + const a: adone.I.datetime.Locale = adone.datetime.defineLocale("he", {}); + const b: adone.I.datetime.Locale = adone.datetime.defineLocale("he", { + calendar: { + lastDay: "" + }, + invalidDate: "h", + isPM: (x: string) => true, + longDateFormat: { + l: "", L: "", LL: "", ll: "", LLL: "", lll: "", LLLL: "", llll: "", + LT: "", lt: "", LTS: "", lts: "" + }, + ordinalParse: /ab/ + }); + } + { + const a: adone.I.datetime.Locale = adone.datetime.updateLocale("he", { + ordinal: (k: number) => "hello" + }); + } + + { const a: string[] = adone.datetime.locales(); } + + { const a: string = adone.datetime.normalizeUnits("y"); } + + { const a: number = adone.datetime.relativeTimeThreshold("y"); } + { const a: boolean = adone.datetime.relativeTimeThreshold("y", 10); } + + { const a: (x: number) => number = adone.datetime.relativeTimeRounding(); } + { const a: boolean = adone.datetime.relativeTimeRounding((x: number) => 123); } + + { const a: string = adone.datetime.calendarFormat(adone.datetime(), adone.datetime()); } + + const d = adone.datetime(); + + { const a: adone.I.datetime.Datetime = d.add(1, "day"); } + { const a: adone.I.datetime.Datetime = d.add(1, "hour"); } + { const a: adone.I.datetime.Datetime = d.add(1); } + + { const a: string = d.calendar("h"); } + { const a: string = d.calendar(1); } + { const a: string = d.calendar(adone.datetime()); } + { const a: string = d.calendar(new Date()); } + { const a: string = d.calendar([1, 2, 3]); } + { const a: string = d.calendar(["1", "2", "3"]); } + + { const a: adone.I.datetime.Datetime = d.clone(); } + { + const a: adone.I.datetime.DatetimeCreationData = d.creationData(); + a.format; + a.input; + a.isUTC; + a.locale; + a.strict; + } + { const a: number = d.date(); } + { const a: number = d.dates(); } + { const a: number = d.day(); } + { const a: number = d.dayOfYear(); } + { const a: number = d.days(); } + { const a: number = d.daysInMonth(); } + { const a: number = d.diff(adone.datetime()); } + { const a: number = d.diff(1001); } + { const a: number = d.diff("asdasd"); } + { const a: number = d.diff(new Date()); } + { const a: number = d.diff(new Date(), "years"); } + { const a: adone.I.datetime.Datetime = d.endOf("year"); } + { const a: string = d.format("YYYY"); } + { const a: string = d.from(100); } + { const a: string = d.from(adone.datetime()); } + { const a: string = d.from(new Date()); } + { const a: string = d.from(100, true); } + { const a: string = d.fromNow(); } + { const a: string = d.fromNow(true); } + { const a: number = d.get("hours"); } + { const a: boolean = d.hasAlignedHourOffset(); } + { const a: boolean = d.hasAlignedHourOffset("123"); } + { const a: boolean = d.hasAlignedHourOffset(new Date()); } + { const a: boolean = d.hasAlignedHourOffset(123); } + { const a: boolean = d.hasAlignedHourOffset(adone.datetime()); } + { const a: number = d.hour(); } + { const a: number = d.hours(); } + { const a: string = d.inspect(); } + { const a: number = d.invalidAt(); } + { const a: boolean = d.isAfter(123123); } + { const a: boolean = d.isAfter(adone.datetime()); } + { const a: boolean = d.isBefore(123123); } + { const a: boolean = d.isBefore(adone.datetime()); } + { const a: boolean = d.isBetween(adone.datetime(), adone.datetime()); } + { const a: boolean = d.isBetween(adone.datetime(), 123); } + { const a: boolean = d.isDST(); } + { const a: boolean = d.isDSTShifted(); } + { const a: boolean = d.isLeapYear(); } + { const a: boolean = d.isLocal(); } + { const a: number = d.isoWeek(); } + { const a: number = d.isoWeekday(); } + { const a: number = d.isoWeeks(); } + { const a: number = d.isoWeeksInYear(); } + { const a: number = d.isoWeekYear(); } + { const a: boolean = d.isSame(13); } + { const a: boolean = d.isSame(adone.datetime()); } + { const a: boolean = d.isSame("23"); } + { const a: boolean = d.isSameOrAfter("123"); } + { const a: boolean = d.isSameOrAfter(123); } + { const a: boolean = d.isSameOrAfter(adone.datetime()); } + { const a: boolean = d.isSameOrBefore("123"); } + { const a: boolean = d.isSameOrBefore(123); } + { const a: boolean = d.isSameOrBefore(adone.datetime()); } + { const a: boolean = d.isUTC(); } + { const a: boolean = d.isUtc(); } + { const a: boolean = d.isUtcOffset(); } + { const a: boolean = d.isValid(); } + { const a: adone.I.datetime.Datetime = d.local(); } + { const a: string = d.locale(); } + { const a: adone.I.datetime.Locale = d.localeData(); } + { const a: number = d.millisecond(); } + { const a: number = d.milliseconds(); } + { const a: number = d.minute(); } + { const a: number = d.minutes(); } + { const a: number = d.months(); } + { const a: adone.I.datetime.Datetime = d.parseZone(); } + { + const a: adone.I.datetime.DatetimeParsingFlags = d.parsingFlags(); + a.charsLeftOver; + a.empty; + a.invalidFormat; + a.invalidMonth; + a.iso; + a.meridiem; + a.nullInput; + a.overflow; + a.parsedDateParts; + a.unusedInput; + a.unusedTokens; + a.userInvalidated; + } + { const a: number = d.quarter(); } + { const a: number = d.quarters(); } + { const a: number = d.second(); } + { const a: number = d.seconds(); } + { const a: adone.I.datetime.Datetime = d.set("year", 2); } + { const a: adone.I.datetime.Datetime = d.startOf("year"); } + { const a: adone.I.datetime.Datetime = d.subtract(1, "day"); } + { const a: adone.I.datetime.Datetime = d.subtract(1); } + { const a: string = d.to(100); } + { const a: string = d.to(adone.datetime()); } + { const a: string = d.to("asdjasd"); } + { const a: number[] = d.toArray(); } + { const a: Date = d.toDate(); } + { const a: string = d.toISOString(); } + { const a: string = d.toJSON(); } + { const b: { date: number, time: number } = d.toDOS(); } + { const a: string = d.toNow(); } + { + const a: adone.I.datetime.DatetimeObjectOutput = d.toObject(); + a.date; + a.hours; + a.milliseconds; + a.minutes; + a.months; + a.seconds; + a.years; + } + { const a: number = d.unix(); } + { const a: adone.I.datetime.Datetime = d.utc(); } + { const a: number = d.utcOffset(); } + { const a: number = d.week(); } + { const a: number = d.weekday(); } + { const a: number = d.weeks(); } + { const a: number = d.weeksInYear(); } + { const a: number = d.weekYear(); } + { const a: number = d.year(); } + { const a: number = d.years(); } + { const a: string = d.zoneAbbr(); } + { const a: string = d.zoneName(); } +} diff --git a/types/adone/test/glosses/events.ts b/types/adone/test/glosses/events.ts new file mode 100644 index 0000000000..7f31089b52 --- /dev/null +++ b/types/adone/test/glosses/events.ts @@ -0,0 +1,106 @@ +namespace eventsTests { + namespace EventEmitter { + namespace static { + const a: number = adone.event.EventEmitter.listenerCount(new adone.event.EventEmitter(), "event"); + const b: number = adone.event.EventEmitter.defaultMaxListeners; + } + + namespace addListener { + const a: adone.event.EventEmitter = new adone.event.EventEmitter().addListener("event", () => { }); + const b: adone.event.EventEmitter = new adone.event.EventEmitter().addListener(Symbol("event"), () => { }); + } + + namespace on { + const a: adone.event.EventEmitter = new adone.event.EventEmitter().on("event", () => { }); + const b: adone.event.EventEmitter = new adone.event.EventEmitter().on(Symbol("event"), () => { }); + } + + namespace once { + const a: adone.event.EventEmitter = new adone.event.EventEmitter().once("event", () => { }); + const b: adone.event.EventEmitter = new adone.event.EventEmitter().once(Symbol("event"), () => { }); + } + + namespace prependListener { + const a: adone.event.EventEmitter = new adone.event.EventEmitter().prependListener("event", () => { }); + const b: adone.event.EventEmitter = new adone.event.EventEmitter().prependListener(Symbol("event"), () => { }); + } + + namespace prependOnceListener { + const a: adone.event.EventEmitter = new adone.event.EventEmitter().prependOnceListener("event", () => { }); + const b: adone.event.EventEmitter = new adone.event.EventEmitter().prependOnceListener(Symbol("event"), () => { }); + } + + namespace removeListener { + const a: adone.event.EventEmitter = new adone.event.EventEmitter().removeListener("event", () => { }); + const b: adone.event.EventEmitter = new adone.event.EventEmitter().removeListener(Symbol("event"), () => { }); + } + + namespace removeAllListeners { + const a: adone.event.EventEmitter = new adone.event.EventEmitter().removeAllListeners("event"); + const b: adone.event.EventEmitter = new adone.event.EventEmitter().removeAllListeners(Symbol("event")); + } + + namespace setMaxListeners { + const a: adone.event.EventEmitter = new adone.event.EventEmitter().setMaxListeners(10); + } + + namespace getMaxListeners { + const a: number = new adone.event.EventEmitter().getMaxListeners(); + } + + namespace listeners { + const a: Array<(...args: any[]) => any> = new adone.event.EventEmitter().listeners("event"); + const b: Array<(...args: any[]) => any> = new adone.event.EventEmitter().listeners(Symbol("event")); + } + + namespace emit { + const a: boolean = new adone.event.EventEmitter().emit("event", 1, 2, 3); + const b: boolean = new adone.event.EventEmitter().emit(Symbol("event"), 1, 2, 3); + } + + namespace eventNames { + const a: Array = new adone.event.EventEmitter().eventNames(); + const b: Array = new adone.event.EventEmitter().eventNames(); + } + + namespace listenerCount { + const a: number = new adone.event.EventEmitter().listenerCount("event"); + const b: number = new adone.event.EventEmitter().listenerCount(Symbol("event")); + } + } + + namespace AsyncEmitter { + const a: adone.event.EventEmitter = new adone.event.AsyncEmitter(); + new adone.event.AsyncEmitter(10); + + namespace setConcurrency { + const a: adone.event.AsyncEmitter = new adone.event.AsyncEmitter().setConcurrency(); + const b: adone.event.AsyncEmitter = new adone.event.AsyncEmitter().setConcurrency(10); + } + + namespace emitParallel { + const a: Promise = new adone.event.AsyncEmitter().emitParallel("even"); + const b: Promise = new adone.event.AsyncEmitter().emitParallel("even", 1, 2, 3); + } + + namespace emitSerial { + const a: Promise = new adone.event.AsyncEmitter().emitSerial("even"); + const b: Promise = new adone.event.AsyncEmitter().emitSerial("even", 1, 2, 3); + } + + namespace emitReduce { + const a: Promise = new adone.event.AsyncEmitter().emitReduce("even"); + const b: Promise = new adone.event.AsyncEmitter().emitReduce("even", 1, 2, 3); + } + + namespace emitReduceRight { + const a: Promise = new adone.event.AsyncEmitter().emitReduceRight("even"); + const b: Promise = new adone.event.AsyncEmitter().emitReduceRight("even", 1, 2, 3); + } + + namespace subscribe { + const a: () => void = new adone.event.AsyncEmitter().subscribe("event", () => { }); + const b: () => void = new adone.event.AsyncEmitter().subscribe("event", () => { }, true); + } + } +} diff --git a/types/adone/test/glosses/exceptions.ts b/types/adone/test/glosses/exceptions.ts new file mode 100644 index 0000000000..e13dc3fff7 --- /dev/null +++ b/types/adone/test/glosses/exceptions.ts @@ -0,0 +1,36 @@ +namespace ExcetpionsTests { + { const a: Error = new adone.x.Exception(); } + { const a: Error = new adone.x.Exception("message"); } + { const a: Error = new adone.x.Exception(new Error()); } + { const a: Error = new adone.x.Exception(new Error(), true); } + { const a: adone.x.Exception = new adone.x.Runtime(); } + { const a: adone.x.Exception = new adone.x.IncompleteBufferError(); } + { const a: adone.x.Exception = new adone.x.NotImplemented(); } + { const a: adone.x.Exception = new adone.x.IllegalState(); } + { const a: adone.x.Exception = new adone.x.NotValid(); } + { const a: adone.x.Exception = new adone.x.Unknown(); } + { const a: adone.x.Exception = new adone.x.NotExists(); } + { const a: adone.x.Exception = new adone.x.Exists(); } + { const a: adone.x.Exception = new adone.x.Empty(); } + { const a: adone.x.Exception = new adone.x.InvalidAccess(); } + { const a: adone.x.Exception = new adone.x.NotSupported(); } + { const a: adone.x.Exception = new adone.x.InvalidArgument(); } + { const a: adone.x.Exception = new adone.x.InvalidNumberOfArguments(); } + { const a: adone.x.Exception = new adone.x.NotFound(); } + { const a: adone.x.Exception = new adone.x.Timeout(); } + { const a: adone.x.Exception = new adone.x.Incorrect(); } + { const a: adone.x.Exception = new adone.x.NotAllowed(); } + { const a: adone.x.Exception = new adone.x.LimitExceeded(); } + { const a: adone.x.Exception = new adone.x.Encoding(); } + { const a: adone.x.Exception = new adone.x.Network(); } + { const a: adone.x.Exception = new adone.x.Bind(); } + { const a: adone.x.Exception = new adone.x.Connect(); } + { const a: adone.x.Exception = new adone.x.Database(); } + { const a: adone.x.Exception = new adone.x.DatabaseInitialization(); } + { const a: adone.x.Exception = new adone.x.DatabaseOpen(); } + { const a: adone.x.Exception = new adone.x.DatabaseRead(); } + { const a: adone.x.Exception = new adone.x.DatabaseWrite(); } + { const a: adone.x.Exception = new adone.x.NetronIllegalState(); } + { const a: adone.x.Exception = new adone.x.NetronPeerDisconnected(); } + { const a: adone.x.Exception = new adone.x.NetronTimeout(); } +} diff --git a/types/adone/test/glosses/fast.ts b/types/adone/test/glosses/fast.ts new file mode 100644 index 0000000000..a0943ffece --- /dev/null +++ b/types/adone/test/glosses/fast.ts @@ -0,0 +1,737 @@ +namespace fastTests { + const { fast } = adone; + + namespace FileTests { + const { File } = fast; + + new File(); + new File({ base: "/" }); + new File({ contents: Buffer.from("hello") }); + new File({ contents: Buffer.from("hello") }).contents.fill(0); + new File({ contents: adone.fs.createReadStream("hello") }).contents.pipe(process.stdout); + new File({ contents: null }).contents === null; + new File({ cwd: "/" }); + new File({ history: ["a", "b"] }); + new File({ path: "/a/b/c" }); + new File({ stat: adone.fs.statSync("hello") }); + new File({ symlink: "/a/b/c" }); + + { + const f = new File(); + f.base === ""; + f.base = "1"; + f.basename === ""; + f.basename = "2"; + f.contents === null; + f.cwd === ""; + f.cwd = "1"; + f.dirname === ""; + f.dirname = "2"; + f.extname === ""; + f.extname = "3"; + f.history[0] === ""; + f.path === ""; + f.path = "2"; + f.relative === ""; + f.relative = "3"; + const s: adone.fs.I.Stats = f.stat; + f.stem = "3"; + f.symlink = "5"; + } + { + const n = new File({ contents: null }); + n.clone({ contents: true }).contents === null; + const b = new File({ contents: Buffer.from("1") }); + b.clone({ contents: true }).contents.fill(0); + // todo stream + } + { + const f = new File(); + const a: boolean = f.isBuffer(); + const b: boolean = f.isDirectory(); + const c: boolean = f.isNull(); + const d: boolean = f.isStream(); + const e: boolean = f.isSymbolic(); + } + } + + namespace srcTests { + const { src } = fast; + + src("hello"); + src(["hello"]); + src("hello").forEach((x) => { + x.isBuffer(); + x.contents.fill(0); + }); + src("hello", { buffer: true }).forEach((x) => { + x.isBuffer(); + x.contents.fill(0); + }); + src("hello", { read: true, buffer: true }).forEach((x) => { + x.isBuffer(); + x.contents.fill(0); + }); + src("hello", { stream: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + src("hello", { read: true, stream: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + src("hello", { read: true, stream: true, buffer: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + src("hello", { read: false }).forEach((x) => { + const a: null = x.contents; + }); + src("hello", { read: false, stream: true }).forEach((x) => { + const a: null = x.contents; + }); + src("hello", { read: false, stream: true, buffer: true }).forEach((x) => { + const a: null = x.contents; + }); + src("hello", { cwd: "/" }).forEach((x) => { + x.contents.fill(0); + }); + + src("hello").dest("hello"); + src("hello").dest("hello", { cwd: "/" }); + src("hello").dest("hello", { flag: "w+" }); + src("hello").dest("hello", { mode: 0o555 }); + src("hello").dest("hello", { originMode: true }); + src("hello").dest("hello", { originOwner: true }); + src("hello").dest("hello", { originTimes: true }); + src("hello").dest("hello", { produceFiles: true }); + src("hello").dest((file) => { + file.contents.fill(0); + return "a"; + }); + src("hello", { stream: true }).dest((file) => { + file.contents.pipe(process.stdout); + return "a"; + }); + } + + namespace watchTests { + const { watch } = fast; + watch("hello").forEach((x) => { + x.contents.fill(0); + }); + watch(["hello"]).forEach((x) => { + x.contents.fill(0); + }); + watch("hello", { read: false }).forEach((x) => { + const a: null = x.contents; + }); + watch("hello", { read: false, stream: true }).forEach((x) => { + const a: null = x.contents; + }); + watch("hello", { read: false, buffer: true }).forEach((x) => { + const a: null = x.contents; + }); + watch("hello", { stream: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + watch("hello", { read: true, stream: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + watch("hello", { read: true, stream: true, buffer: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + watch("hello", { alwaysStat: true }); + watch("hello", { followSymlinks: true }); + } + + namespace mapTests { + const { map } = fast; + + map({ + from: "a", + to: "b" + }).forEach((x) => { + x.contents.fill(0); + }); + map([{ + from: "a", + to: "b" + }]).forEach((x) => { + x.contents.fill(0); + }); + map([]).dest({ cwd: "/" }); + map([]).dest({ flag: "w+" }); + map([]).dest({ mode: 0o677 }); + map([]).dest({ originMode: true }); + map([]).dest({ originOwner: false }); + map([]).dest({ originTimes: true }); + map([]).dest({ produceFiles: true }); + map([], { read: false }).forEach((x) => { + const a: null = x.contents; + }); + map([], { read: false, stream: true }).forEach((x) => { + const a: null = x.contents; + }); + map([], { read: false, stream: true, buffer: true }).forEach((x) => { + const a: null = x.contents; + }); + map([], { stream: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + map([], { stream: true, buffer: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + map([], { read: true, stream: true, buffer: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + map([], { buffer: true }).forEach((x) => { + x.contents.fill(0); + }); + } + + namespace watchMapTests { + const { watchMap } = fast; + + watchMap({ + from: "a", + to: "b" + }).forEach((x) => { + x.contents.fill(0); + }); + watchMap([{ + from: "a", + to: "b" + }]).forEach((x) => { + x.contents.fill(0); + }); + watchMap([], { read: false }).forEach((x) => { + const a: null = x.contents; + }); + watchMap([], { stream: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + watchMap([], { read: true, stream: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + watchMap([], { read: true, stream: true, buffer: true }).forEach((x) => { + x.contents.pipe(process.stdout); + }); + watchMap([], { buffer: true }).forEach((x) => { + x.contents.fill(0); + }); + watchMap([], { read: true, buffer: true }).forEach((x) => { + x.contents.fill(0); + }); + watchMap([], { read: false, stream: true }).forEach((x) => { + const a: null = x.contents; + }); + watchMap([], { read: false, stream: true, buffer: true }).forEach((x) => { + const a: null = x.contents; + }); + } + + namespace pluginsTests { + const { src } = fast; + namespace compressorTests { + src("hello").compress("gz"); + src("hello").compress("brotli"); + src("hello").compress("deflate"); + src("hello").compress("lzma"); + src("hello").compress("snappy"); + src("hello").compress("xz"); + src("hello").compress("gz", {}); + src("hello").compress("gz", { rename: true }); + src("hello").decompress("gz"); + src("hello").decompress("brotli"); + src("hello").decompress("deflate"); + src("hello").decompress("lzma"); + src("hello").decompress("snappy"); + src("hello").decompress("xz"); + src("hello").decompress("gz", {}); + } + + namespace archiveTests { + src("hello").pack("tar"); + src("hello").pack("zip"); + src("hello").pack("tar", {}); + src("hello").unpack("tar"); + src("hello").unpack("zip"); + src("hello").unpack("tar", {}); + } + + namespace transpileTests { + src("hello").transpile({}); // TODO + } + + namespace renameTests { + src("hello").rename("opa"); + src("hello").rename((obj) => { + const a: string = obj.basename; + const b: string = obj.dirname; + const c: string = obj.extname; + return "asd"; + }); + src("hello").rename({ + dirname: "1" + }); + src("hello").rename({ + basename: "1" + }); + src("hello").rename({ + extname: "1" + }); + src("hello").rename({ + prefix: "1" + }); + } + + namespace concatTests { + src("hello").concat("file"); + src("hello").concat({ + path: "file" + }); + src("hello").concat("file", {}); + src("hello").concat("file", { newLine: "\n" }); + } + + namespace sourcemapsTests { + src("hello").sourcemapsInit(); + src("hello").sourcemapsInit({}); + src("hello").sourcemapsInit({ loadMaps: true }); + src("hello").sourcemapsInit({ identityMap: true }); + src("hello").sourcemapsInit({ largeFile: true }); + src("hello").sourcemapsWrite({}); + src("hello").sourcemapsWrite({ addComment: true }); + src("hello").sourcemapsWrite({ charset: "utf8" }); + src("hello").sourcemapsWrite({ clone: { deep: true } }); + src("hello").sourcemapsWrite({ clone: { contents: true } }); + src("hello").sourcemapsWrite({ destPath: "../" }); + src("hello").sourcemapsWrite({ includeContent: true }); + src("hello").sourcemapsWrite({ mapFile: (f) => f.contents.fill(0) && f.path }); + src("hello").sourcemapsWrite({ mapSources: (path: string, file) => file.contents.fill(0) && path }); + src("hello").sourcemapsWrite({ mapSourcesAbsolute: true }); + src("hello").sourcemapsWrite({ sourceMappingURL: (file) => file.contents.fill(0) && file.path }); + src("hello").sourcemapsWrite({ sourceMappingURLPrefix: "haha" }); + src("hello").sourcemapsWrite({ sourceMappingURLPrefix: (file) => file.contents.fill(0) && file.path }); + src("hello").sourcemapsWrite({ sourceRoot: "../" }); + src("hello").sourcemapsWrite("../", {}); + src("hello").sourcemapsWrite("../", { addComment: true }); + src("hello").sourcemapsWrite("../", { charset: "utf8" }); + src("hello").sourcemapsWrite("../", { clone: { deep: true } }); + src("hello").sourcemapsWrite("../", { clone: { contents: true } }); + src("hello").sourcemapsWrite("../", { destPath: "../" }); + src("hello").sourcemapsWrite("../", { includeContent: true }); + src("hello").sourcemapsWrite("../", { mapFile: (f) => f.contents.fill(0) && f.path }); + src("hello").sourcemapsWrite("../", { mapSources: (path: string, file) => file.contents.fill(0) && path }); + src("hello").sourcemapsWrite("../", { mapSourcesAbsolute: true }); + src("hello").sourcemapsWrite("../", { sourceMappingURL: (file) => file.contents.fill(0) && file.path }); + src("hello").sourcemapsWrite("../", { sourceMappingURLPrefix: "haha" }); + src("hello").sourcemapsWrite("../", { sourceMappingURLPrefix: (file) => file.contents.fill(0) && file.path }); + src("hello").sourcemapsWrite("../", { sourceRoot: "../" }); + } + + namespace wrapTests { + src("hello").wrap("template"); + src("hello").wrap({ src: "template path" }); + src("hello").wrap((data) => "123"); + src("hello").wrap("template", (file) => file.contents.fill(0) && { a: 1 }); + src("hello").wrap("template", { a: 1 }); + src("hello").wrap("template", undefined, { escape: /aasd/ }); + src("hello").wrap("template", undefined, { evaluate: /aa/ }); + src("hello").wrap("template", undefined, { imports: {} }); + src("hello").wrap("template", undefined, { interpolate: /a/ }); + src("hello").wrap("template", undefined, { parse: true }); + src("hello").wrap("template", undefined, { sourceURL: ".a" }); + src("hello").wrap("template", undefined, { variable: "a" }); + src("hello").wrap("template", undefined, (file) => (file.contents.fill(0) && { parse: true })); + } + + namespace replaceTests { + src("hello").replace("a", "b"); + src("hello").replace("a", (x: string) => "b"); + src("hello").replace(/a/, "b"); + src("hello").replace([/a/], ["b"]); + src("hello").replace([/a/], ["b"]); + src("hello").replace(["a", /a/], ["b", "e"]); + src("hello").replace(["a", /a/], [(x: string) => "b", "e"]); + } + + namespace revisionHashTests { + src("hello").revisionHash(); + src("hello").revisionHash({ + manifest: {} + }); + src("hello").revisionHash({ + manifest: { + merge: true + } + }); + src("hello").revisionHash({ + manifest: { + path: "a" + } + }); + src("hello").revisionHash({ + manifest: { + transformer: JSON + } + }); + src("hello").revisionHash({ + manifest: { + transformer: { + parse: () => ({}), + stringify: () => "" + } + } + }); + } + + namespace revisionHashReplaceTests { + src("hello").revisionHashReplace({ + canonicalUris: true + }); + src("hello").revisionHashReplace({ + prefix: "hello" + }); + src("hello").revisionHashReplace({ + replaceExtensions: [".js"] + }); + src("hello").revisionHashReplace({ + manifest: src("hello") + }); + (async () => { + src("hello").revisionHashReplace({ + manifest: await src("hello") + }); + })(); + src("hello").revisionHashReplace({ + modifyReved: (p: string) => p + }); + src("hello").revisionHashReplace({ + modifyUnreved: (p: string) => p + }); + } + + namespace chmodTests { + src("hello").chmod(0o777); + src("hello").chmod({ + group: { + read: true + } + }); + src("hello").chmod({ + group: { + write: true + } + }); + src("hello").chmod({ + group: { + execute: true + } + }); + src("hello").chmod({ + owner: { + read: true + } + }); + src("hello").chmod({ + owner: { + write: true + } + }); + src("hello").chmod({ + owner: { + execute: true + } + }); + src("hello").chmod({ + others: { + read: true + } + }); + src("hello").chmod({ + others: { + write: true + } + }); + src("hello").chmod({ + others: { + execute: true + } + }); + src("hello").chmod(undefined, 0o777); + src("hello").chmod(undefined, { + group: { + read: true + } + }); + src("hello").chmod(undefined, { + group: { + write: true + } + }); + src("hello").chmod(undefined, { + group: { + execute: true + } + }); + src("hello").chmod(undefined, { + owner: { + read: true + } + }); + src("hello").chmod(undefined, { + owner: { + write: true + } + }); + src("hello").chmod(undefined, { + owner: { + execute: true + } + }); + src("hello").chmod(undefined, { + others: { + read: true + } + }); + src("hello").chmod(undefined, { + others: { + write: true + } + }); + src("hello").chmod(undefined, { + others: { + execute: true + } + }); + } + + namespace notifyTests { + src("hello").notify("hello"); + src("hello").notify({ + appName: "a" + }); + src("hello").notify({ + console: true + }); + src("hello").notify({ + debounce: { + timeout: 100 + } + }); + src("hello").notify({ + debounce: 100 + }); + src("hello").notify({ + debounce: { + timeout: 100, + leading: true + } + }); + src("hello").notify({ + debounce: { + timeout: 100, + trailing: true + } + }); + src("hello").notify({ + emitError: true + }); + src("hello").notify({ + filter: (file) => file.contents.fill(0) && true + }); + src("hello").notify({ + gui: true + }); + src("hello").notify({ + host: "192.168.1.1" + }); + src("hello").notify({ + message: "hello" + }); + src("hello").notify({ + message: (file) => file.contents.fill(0) && file.path + }); + src("hello").notify({ + notifier: {} // TODO + }); + src("hello").notify({ + onLast: true + }); + src("hello").notify({ + open: (file) => file.contents.fill(0) && file.path + }); + src("hello").notify({ + open: "hello" + }); + src("hello").notify({ + port: 31337 + }); + src("hello").notify({ + subtitle: (file) => file.contents.fill(0) && file.path + }); + src("hello").notify({ + subtitle: "hello" + }); + src("hello").notify({ + templateOptions: {} + }); + src("hello").notify({ + title: "hello" + }); + src("hello").notify({ + title: (file) => file.contents.fill(0) && file.path + }); + src("hello").notifyError("hello"); + src("hello").notifyError({ + appName: "a" + }); + src("hello").notifyError({ + console: true + }); + src("hello").notifyError({ + debounce: { + timeout: 100 + } + }); + src("hello").notifyError({ + debounce: 100 + }); + src("hello").notifyError({ + debounce: { + timeout: 100, + leading: true + } + }); + src("hello").notifyError({ + debounce: { + timeout: 100, + trailing: true + } + }); + src("hello").notifyError({ + emitError: true + }); + src("hello").notifyError({ + filter: (file) => file.contents.fill(0) && true + }); + src("hello").notifyError({ + gui: true + }); + src("hello").notifyError({ + host: "192.168.1.1" + }); + src("hello").notifyError({ + message: "hello" + }); + src("hello").notifyError({ + message: (file) => file.contents.fill(0) && file.path + }); + src("hello").notifyError({ + notifier: {} // TODO + }); + src("hello").notifyError({ + onLast: true + }); + src("hello").notifyError({ + open: (file) => file.contents.fill(0) && file.path + }); + src("hello").notifyError({ + open: "hello" + }); + src("hello").notifyError({ + port: 31337 + }); + src("hello").notifyError({ + subtitle: (file) => file.contents.fill(0) && file.path + }); + src("hello").notifyError({ + subtitle: "hello" + }); + src("hello").notifyError({ + templateOptions: {} + }); + src("hello").notifyError({ + title: "hello" + }); + src("hello").notifyError({ + title: (file) => file.contents.fill(0) && file.path + }); + + fast.plugin.notify.onError("hello"); + fast.plugin.notify.onError({ + appName: "a" + }); + fast.plugin.notify.onError({ + console: true + }); + fast.plugin.notify.onError({ + debounce: { + timeout: 100 + } + }); + fast.plugin.notify.onError({ + debounce: 100 + }); + fast.plugin.notify.onError({ + debounce: { + timeout: 100, + leading: true + } + }); + fast.plugin.notify.onError({ + debounce: { + timeout: 100, + trailing: true + } + }); + fast.plugin.notify.onError({ + emitError: true + }); + fast.plugin.notify.onError({ + filter: (file) => true + }); + fast.plugin.notify.onError({ + gui: true + }); + fast.plugin.notify.onError({ + host: "192.168.1.1" + }); + fast.plugin.notify.onError({ + message: "hello" + }); + fast.plugin.notify.onError({ + message: (file) => file.path + }); + fast.plugin.notify.onError({ + notifier: {} // TODO + }); + fast.plugin.notify.onError({ + onLast: true + }); + fast.plugin.notify.onError({ + open: (file) => file.path + }); + fast.plugin.notify.onError({ + open: "hello" + }); + fast.plugin.notify.onError({ + port: 31337 + }); + fast.plugin.notify.onError({ + subtitle: (file) => file.path + }); + fast.plugin.notify.onError({ + subtitle: "hello" + }); + fast.plugin.notify.onError({ + templateOptions: {} + }); + fast.plugin.notify.onError({ + title: "hello" + }); + fast.plugin.notify.onError({ + title: (file) => file.path + }); + } + } +} diff --git a/types/adone/test/glosses/fs.ts b/types/adone/test/glosses/fs.ts new file mode 100644 index 0000000000..8b7e765c9f --- /dev/null +++ b/types/adone/test/glosses/fs.ts @@ -0,0 +1,793 @@ +namespace fsTests { + const { fs, std: { url: { URL } } } = adone; + + namespace readlinkTests { + fs.readlink("file"); + fs.readlink(Buffer.from("file")); + fs.readlink(new URL("file://file")); + fs.readlink("file", {}).then((x: string) => x); + fs.readlink("file", { encoding: "utf8" }).then((x: string) => x); + fs.readlink("file", { encoding: null }).then((x: Buffer) => x); + fs.readlink("file", null).then((x: Buffer) => x); + fs.readlink("file", "hex").then((x: string) => x); + fs.readlink("file").then((x: string) => x); + } + + namespace unlinkTests { + fs.unlink("file").then(() => {}); + fs.unlink(Buffer.from("file")).then(() => {}); + fs.unlink(new URL("file://file")).then(() => {}); + fs.unlinkSync("file"); + fs.unlinkSync(Buffer.from("file")); + fs.unlinkSync(new URL("file://file")); + } + + namespace chmodTests { + fs.chmod("file", 0o333).then(() => {}); + fs.chmod(Buffer.from("file"), 0o333).then(() => {}); + fs.chmod(new URL("file://file"), 0o333).then(() => {}); + } + + namespace chownTests { + fs.chown("file", 0, 0).then(() => {}); + fs.chown(Buffer.from("file"), 0, 0).then(() => {}); + fs.chown(new URL("file://file"), 0, 0).then(() => {}); + } + + namespace rmdirTests { + fs.rmdir("file").then(() => {}); + fs.rmdir(Buffer.from("file")).then(() => {}); + fs.rmdir(new URL("file://file")).then(() => {}); + } + + namespace readdirTests { + fs.readdir("file"); + fs.readdir(Buffer.from("file")); + fs.readdir(new URL("file://file")); + fs.readdir("file").then((x: string[]) => {}); + fs.readdir("file", null).then((x: Buffer[]) => {}); + fs.readdir("file", {}).then((x: string[]) => {}); + fs.readdir("file", { encoding: "hex" }).then((x: string[]) => {}); + fs.readdir("file", { encoding: null }).then((x: Buffer[]) => {}); + + fs.readdirSync("file"); + fs.readdirSync(Buffer.from("file")); + fs.readdirSync(new URL("file://file")); + const a: string[] = fs.readdirSync("file"); + const b: Buffer[] = fs.readdirSync("file", null); + const c: string[] = fs.readdirSync("file", {}); + const d: string[] = fs.readdirSync("file", { encoding: "hex" }); + const e: Buffer[] = fs.readdirSync("file", { encoding: null }); + } + + namespace lstatTests { + fs.lstat("file").then((x: nodestd.fs.Stats) => {}); + fs.lstat(Buffer.from("file")).then((x: nodestd.fs.Stats) => {}); + fs.lstat(new URL("file://file")).then((x: nodestd.fs.Stats) => {}); + + const a: nodestd.fs.Stats = fs.lstatSync("file"); + const b: nodestd.fs.Stats = fs.lstatSync(Buffer.from("file")); + const c: nodestd.fs.Stats = fs.lstatSync(new URL("file://file")); + } + + namespace statTests { + fs.stat("file").then((x: nodestd.fs.Stats) => {}); + fs.stat(Buffer.from("file")).then((x: nodestd.fs.Stats) => {}); + fs.stat(new URL("file://file")).then((x: nodestd.fs.Stats) => {}); + + const a: nodestd.fs.Stats = fs.statSync("file"); + const b: nodestd.fs.Stats = fs.statSync(Buffer.from("file")); + const c: nodestd.fs.Stats = fs.statSync(new URL("file://file")); + } + + namespace truncateTests { + fs.truncate("file").then(() => {}); + fs.truncate(Buffer.from("file")).then(() => {}); + fs.truncate("file", 100).then(() => {}); + } + + namespace writeFileTests { + fs.writeFile("file", "hello").then(() => {}); + fs.writeFile(Buffer.from("file"), "hello").then(() => {}); + fs.writeFile(10, "hello").then(() => {}); + fs.writeFile("file", Buffer.from("hello")).then(() => {}); + fs.writeFile("file", new Uint8Array(10)).then(() => {}); + fs.writeFile("file", "hello", {}).then(() => {}); + fs.writeFile("file", "hello", { encoding: "utf8" }).then(() => {}); + fs.writeFile("file", "hello", { mode: 0o755 }).then(() => {}); + fs.writeFile("file", "hello", { flag: "w" }).then(() => {}); + } + + namespace writeFileSyncTests { + fs.writeFileSync("file", "hello"); + fs.writeFileSync(Buffer.from("file"), "hello"); + fs.writeFileSync(10, "hello"); + fs.writeFileSync("file", Buffer.from("hello")); + fs.writeFileSync("file", new Uint8Array(10)); + fs.writeFileSync("file", "hello", {}); + fs.writeFileSync("file", "hello", { encoding: "utf8" }); + fs.writeFileSync("file", "hello", { mode: 0o755 }); + fs.writeFileSync("file", "hello", { flag: "w" }); + } + + namespace appendFileTests { + fs.appendFile("file", "hello").then(() => {}); + fs.appendFile(Buffer.from("file"), "hello").then(() => {}); + fs.appendFile(10, "hello").then(() => {}); + fs.appendFile("file", Buffer.from("hello")).then(() => {}); + fs.appendFile("file", "hello", {}).then(() => {}); + fs.appendFile("file", "hello", { encoding: "utf8" }).then(() => {}); + fs.appendFile("file", "hello", { mode: 0o755 }).then(() => {}); + fs.appendFile("file", "hello", { flag: "w" }).then(() => {}); + } + + namespace accessTests { + fs.access("file", fs.constants.F_OK).then(() => {}); + fs.access(Buffer.from("file"), fs.constants.F_OK).then(() => {}); + fs.access(new URL("file://file"), fs.constants.F_OK).then(() => {}); + } + + namespace accessSyncTests { + fs.accessSync("file", fs.constants.F_OK); + fs.accessSync(Buffer.from("file"), fs.constants.F_OK); + fs.accessSync(new URL("file://file"), fs.constants.F_OK); + } + + namespace symlinkTests { + fs.symlink("file", "another_file").then(() => {}); + fs.symlink(Buffer.from("file"), "another_file").then(() => {}); + fs.symlink(new URL("file"), "another_file").then(() => {}); + fs.symlink("file", Buffer.from("another_file")).then(() => {}); + fs.symlink("file", new URL("another_file")).then(() => {}); + fs.symlink("file", "another_file", "dir").then(() => {}); + fs.symlink("file", "another_file", "file").then(() => {}); + fs.symlink("file", "another_file", "junction").then(() => {}); + } + + namespace rmTests { + fs.rm("file").then((x) => {}); + fs.rm("file", {}).then((x) => {}); + fs.rm("file", { glob: true }).then((x) => {}); + fs.rm("file", { maxBusyTries: 3 }).then((x) => {}); + fs.rm("file", { emfileWait: 100 }).then((x) => {}); + fs.rm("file", { cwd: __dirname }).then((x) => {}); + } + + namespace ModeTests { + const stat = fs.statSync("file"); + const mode = new fs.Mode(stat); + { const a: number = mode.valueOf(); } + { const a: boolean = mode.owner.read; } + { const a: boolean = mode.owner.write; } + { const a: boolean = mode.owner.execute; } + { const a: boolean = mode.group.read; } + { const a: boolean = mode.group.write; } + { const a: boolean = mode.group.execute; } + { const a: boolean = mode.others.read; } + { const a: boolean = mode.others.write; } + { const a: boolean = mode.others.execute; } + } + + namespace FileTests { + const { File } = fs; + const f = new File("some", "file"); + f.encoding("utf8").encoding("buffer"); + f.stat().then((x: adone.fs.I.Stats) => {}); + { const a: adone.fs.I.Stats = f.statSync(); } + f.lstat().then((x: adone.fs.I.Stats) => {}); + { const a: adone.fs.I.Stats = f.lstatSync(); } + { const a: adone.fs.Mode = f.mode(); } + { const a: string = f.path(); } + { const a: string = f.normalizedPath(); } + { const a: string = f.dirname(); } + { const a: string = f.filename(); } + { const a: string = f.extname(); } + { const a: string = f.stem(); } + { const a: string = f.relativePath("/tmp"); } + { const a: string = f.relativePath(new fs.Directory("/tmp")); } + f.exists().then((x: boolean) => {}); + f.create().then(() => {}); + f.create({}).then(() => {}); + f.create({ mode: 0o666 }).then(() => {}); + f.write("hello").then(() => {}); + f.write(Buffer.from("hello")).then(() => {}); + f.write("hello", {}).then(() => {}); + f.write("hello", { encoding: "utf8" }).then(() => {}); + f.write("hello", { mode: 0o666 }).then(() => {}); + f.write("hello", { flag: "w" }).then(() => {}); + f.append("hello").then(() => {}); + f.append(Buffer.from("hello")).then(() => {}); + f.append("hello", {}).then(() => {}); + f.append("hello", { encoding: "utf8" }).then(() => {}); + f.append("hello", { mode: 0o666 }).then(() => {}); + f.append("hello", { flag: "w" }).then(() => {}); + f.unlink().then(() => {}); + f.contents("utf16le").then((a: string) => {}); + f.contents("buffer").then((a: Buffer) => {}); + { const a: string = f.contentsSync("utf16le"); } + { const a: Buffer = f.contentsSync("buffer"); } + f.contentsStream("utf8").on("data", (chunk) => {}); + f.chmod(0o755).then(() => {}); + f.chmod(new fs.Mode(f.statSync())).then(() => {}); + { const a: adone.fs.SymbolicLinkFile = f.symbolicLink("another_file"); } + { const a: adone.fs.SymbolicLinkFile = f.symbolicLink(new File("another_file")); } + f.size().then((x: number) => {}); + } + + namespace DirectoryTests { + const { Directory } = fs; + + const d = new Directory("some", "directory"); + { const a: string = d.dirname(); } + { const a: string = d.filename(); } + { const a: string = d.path(); } + { const a: string = d.normalizedPath(); } + { const a: string = d.relativePath("another_dir"); } + { const a: string = d.relativePath(new Directory("another_dir")); } + d.stat().then((x: adone.fs.I.Stats) => {}); + d.lstat().then((x: adone.fs.I.Stats) => {}); + d.exists().then((x: boolean) => {}); + d.create().then(() => {}); + d.create({}).then(() => {}); + d.create({ mode: 0o666 }).then(() => {}); + { const a: string = d.resolve("file", "path"); } + { const a: adone.fs.Directory = d.getDirectory("nested", "directory"); } + { const a: adone.fs.File = d.getFile("nested", "file"); } + { const a: adone.fs.SymbolicLinkFile = d.getSymbolicLinkFile("nested", "filelink"); } + { const a: adone.fs.SymbolicLinkDirectory = d.getSymbolicLinkDirectory("nester", "dirlink"); } + d.addFile("a", "b", "c").then((x: adone.fs.File) => {}); + d.addFile("a", "b", "c", {}).then((x: adone.fs.File) => {}); + d.addFile("a", "b", "c", { contents: "hello" }).then((x: adone.fs.File) => {}); + d.addFile("a", "b", "c", { contents: Buffer.from("hello") }).then((x: adone.fs.File) => {}); + d.addFile("a", "b", "c", { encoding: "utf8" }).then((x: adone.fs.File) => {}); + d.addFile("a", "b", "c", { mode: 0o666 }).then((x: adone.fs.File) => {}); + d.addDirectory("a", "b", "c").then((x: adone.fs.Directory) => {}); + d.files().then((x: Array) => {}); + { const a: Array = d.filesSync(); } + d.clean().then(() => {}); + d.unlink().then(() => {}); + d.unlink({ delay: 100 }).then(() => {}); + d.unlink({ retries: 100 }).then(() => {}); + d.find().then((x: Array) => {}); + d.find({}).then((x: Array) => {}); + d.find({ dirs: true }).then((x: Array) => {}); + d.find({ files: false }).then((x: Array) => {}); + { const a: Array = d.findSync(); } + { const a: Array = d.findSync({}); } + { const a: Array = d.findSync({ dirs: true }); } + { const a: Array = d.findSync({ files: false }); } + d.rename("name").then(() => {}); + d.rename(new Directory("name")).then(() => {}); + d.symbolicLink("another").then((x: adone.fs.SymbolicLinkDirectory) => {}); + d.copyTo("another").then(() => {}); + d.copyTo("another", {}).then(() => {}); + d.copyTo("another", { cwd: "/tmp" }).then(() => {}); + d.copyTo("another", { ignoreExisting: true }).then(() => {}); + d.copyFrom("another", { cwd: "/tmp" }).then(() => {}); + d.copyFrom("another", { ignoreExisting: true }).then(() => {}); + + Directory.create("hello", "world").then((x: adone.fs.Directory) => {}); + Directory.createTmp().then((x: adone.fs.Directory) => {}); + Directory.createTmp({ dir: "/" }).then((x: adone.fs.Directory) => {}); + Directory.createTmp({ ext: ".exe" }).then((x: adone.fs.Directory) => {}); + Directory.createTmp({ name: "hello" }).then((x: adone.fs.Directory) => {}); + Directory.createTmp({ prefix: "/tmp/t-" }).then((x: adone.fs.Directory) => {}); + Directory.createTmp({ template: /XASDX/ }).then((x: adone.fs.Directory) => {}); + Directory.createTmp({ tries: 100500 }).then((x: adone.fs.Directory) => {}); + } + + namespace SymbolicLinkFileTests { + const s = new fs.SymbolicLinkFile("path", "to", "link"); + s.realpath().then((x: string) => {}); + s.contents("utf8").then((x: string) => {}); + s.contents("buffer").then((x: Buffer) => {}); + { const a: string = s.contentsSync("utf8"); } + { const a: Buffer = s.contentsSync("buffer"); } + s.contentsStream("utf8").on("data", (chunk) => {}); + } + + namespace SymbolicLinkDirectoryTests { + const s = new fs.SymbolicLinkDirectory("path", "to", "link"); + s.realpath().then((x: string) => {}); + s.unlink().then(() => {}); + } + + namespace RandomAccessFileTests { + new fs.RandomAccessFile("hello", {}); + new fs.RandomAccessFile("hello", { appendable: true }); + new fs.RandomAccessFile("hello", { readable: true }); + new fs.RandomAccessFile("hello", { writable: true }); + new fs.RandomAccessFile("hello", { cwd: "/tmp" }); + new fs.RandomAccessFile("hello", { mtime: 100500 }); + new fs.RandomAccessFile("hello", { atime: 100500 }); + const raf = new fs.RandomAccessFile("hello"); + raf.read(100).then((x: Buffer) => {}); + raf.read(100, 100).then((x: Buffer) => {}); + raf.write("hello").then((x: number) => {}); + raf.write(Buffer.from("hello")).then((x: number) => {}); + raf.write("hello", 100).then((x: number) => {}); + raf.close().then(() => {}); + raf.end().then(() => {}); + raf.end({}).then(() => {}); + raf.end({ atime: 100500 }).then(() => {}); + raf.end({ mtime: 100500 }).then(() => {}); + raf.truncate(0).then(() => {}); + raf.unlink().then(() => {}); + fs.RandomAccessFile.open("hello").then((x: adone.fs.RandomAccessFile) => {}); + fs.RandomAccessFile.open("hello", {}).then((x: adone.fs.RandomAccessFile) => {}); + fs.RandomAccessFile.open("hello", { appendable: true }).then((x: adone.fs.RandomAccessFile) => {}); + fs.RandomAccessFile.open("hello", { readable: true }).then((x: adone.fs.RandomAccessFile) => {}); + fs.RandomAccessFile.open("hello", { writable: true }).then((x: adone.fs.RandomAccessFile) => {}); + fs.RandomAccessFile.open("hello", { cwd: "/tmp" }).then((x: adone.fs.RandomAccessFile) => {}); + fs.RandomAccessFile.open("hello", { mtime: 100500 }).then((x: adone.fs.RandomAccessFile) => {}); + fs.RandomAccessFile.open("hello", { atime: 100500 }).then((x: adone.fs.RandomAccessFile) => {}); + } + + namespace globTests { + fs.glob("hello").forEach((x: string) => {}); + fs.glob(["hello"]).forEach((x: string) => {}); + fs.glob(["hello"]).forEach((x: string) => {}); + fs.glob(["hello"], { absolute: true }).forEach((x: string) => {}); + fs.glob(["hello"], { cache: new Map() }).forEach((x: string) => {}); + fs.glob(["hello"], { cwd: "/" }).forEach((x: string) => {}); + fs.glob(["hello"], { dot: true }).forEach((x: string) => {}); + fs.glob(["hello"], { follow: true }).forEach((x: string) => {}); + fs.glob(["hello"], { ignore: "a" }).forEach((x: string) => {}); + fs.glob(["hello"], { ignore: ["a"] }).forEach((x: string) => {}); + fs.glob(["hello"], { mark: true }).forEach((x: string) => {}); + fs.glob(["hello"], { matchBase: false }).forEach((x: string) => {}); + fs.glob(["hello"], { nobrace: true }).forEach((x: string) => {}); + fs.glob(["hello"], { nocase: true }).forEach((x: string) => {}); + fs.glob(["hello"], { nodir: true }).forEach((x: string) => {}); + fs.glob(["hello"], { noext: true }).forEach((x: string) => {}); + fs.glob(["hello"], { noglobstar: true }).forEach((x: string) => {}); + fs.glob(["hello"], { nomount: true }).forEach((x: string) => {}); + fs.glob(["hello"], { nonull: true }).forEach((x: string) => {}); + fs.glob(["hello"], { nosort: true }).forEach((x: string) => {}); + fs.glob(["hello"], { nounique: true }).forEach((x: string) => {}); + fs.glob(["hello"], { patternIndex: true }).forEach((x: { patternIndex: number, path: string }) => {}); + fs.glob(["hello"], { realpath: true }).forEach((x: string) => {}); + fs.glob(["hello"], { realpathCache: new Map() }).forEach((x: string) => {}); + fs.glob(["hello"], { root: "/" }).forEach((x: string) => {}); + fs.glob(["hello"], { silent: true }).forEach((x: string) => {}); + fs.glob(["hello"], { stat: true }).forEach((x: { stat: adone.fs.I.Stats, path: string }) => {}); + fs.glob(["hello"], { statCache: new Map() }).forEach((x: string) => {}); + fs.glob(["hello"], { strict: true }).forEach((x: string) => {}); + fs.glob(["hello"], { symlinks: new Map() }).forEach((x: string) => {}); + fs.glob(["hello"], { stat: true, patternIndex: true }).forEach((x: { path: string, patternIndex: number, stat: adone.fs.I.Stats }) => {}); + new fs.glob.Core("hello").forEach((x: string) => {}); + new fs.glob.Core(["hello"]).forEach((x: string) => {}); + new fs.glob.Core(["hello"]).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { absolute: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { cache: new Map() }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { cwd: "/" }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { dot: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { follow: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { ignore: "a" }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { ignore: ["a"] }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { mark: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { matchBase: false }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { nobrace: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { nocase: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { nodir: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { noext: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { noglobstar: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { nomount: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { nonull: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { nosort: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { nounique: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { patternIndex: true }).forEach((x: { patternIndex: number, path: string }) => {}); + new fs.glob.Core(["hello"], { realpath: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { realpathCache: new Map() }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { root: "/" }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { silent: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { stat: true }).forEach((x: { stat: adone.fs.I.Stats, path: string }) => {}); + new fs.glob.Core(["hello"], { statCache: new Map() }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { strict: true }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { symlinks: new Map() }).forEach((x: string) => {}); + new fs.glob.Core(["hello"], { stat: true, patternIndex: true }).forEach((x: { path: string, patternIndex: number, stat: adone.fs.I.Stats }) => {}); + new fs.glob.Glob("hello").on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello").on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { absolute: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { cache: new Map() }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { cwd: "/" }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { dot: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { follow: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { ignore: "a" }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { ignore: ["a"] }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { mark: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { matchBase: false }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { nobrace: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { nocase: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { nodir: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { noext: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { noglobstar: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { nomount: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { nonull: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { nosort: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { nounique: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { realpath: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { realpathCache: new Map() }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { root: "/" }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { silent: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { stat: true }).on("match", (path: string, stat: adone.fs.I.Stats) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { statCache: new Map() }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { strict: true }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", { symlinks: new Map() }).on("match", (path: string) => {}).on("end", (cb: string[]) => {}); + new fs.glob.Glob("hello", {}, (err: any, matches: string[]) => {}).on("end", () => {}); + new fs.glob.Glob("hello", (err: any, matches: string[]) => {}).on("end", () => {}); + new fs.glob.Glob("hello").pause(); + new fs.glob.Glob("hello").resume(); + new fs.glob.Glob("hello").abort(); + } + + namespace WatcherTests { + new fs.Watcher(); + new fs.Watcher({}); + new fs.Watcher({ alwaysStat: true }); + new fs.Watcher({ atomic: true }); + new fs.Watcher({ awaitWriteFinish: true }); + new fs.Watcher({ awaitWriteFinish: { pollInterval: 100 } }); + new fs.Watcher({ awaitWriteFinish: { stabilityThreshold: 100 } }); + new fs.Watcher({ binaryInterval: 100 }); + new fs.Watcher({ cwd: "/tmp" }); + new fs.Watcher({ depth: 10 }); + new fs.Watcher({ disableGlobbing: true }); + new fs.Watcher({ followSymlinks: false }); + new fs.Watcher({ ignored: ["hello"] }); + new fs.Watcher({ ignoreInitial: true }); + new fs.Watcher({ ignorePermissionErrors: false }); + new fs.Watcher({ interval: 100 }); + new fs.Watcher({ persistent: false }); + new fs.Watcher({ useFsEvents: false }); + new fs.Watcher({ usePolling: false }); + const w = new fs.Watcher(); + { const a: adone.fs.Watcher = w.add("hello"); } + { const a: adone.fs.Watcher = w.add(["hello"]); } + { + const watched = w.getWatched(); + const a: string[] = watched["/tmp"]; + } + w.on("add", (path: string, stat: adone.fs.I.Stats) => {}); + w.on("addDir", (path: string, stat: adone.fs.I.Stats) => {}); + w.on("all", (event: adone.fs.I.Watcher.Event, path: string, stat: adone.fs.I.Stats) => {}); + w.on("raw", (event: string, path: string, details: object) => {}); + } + + namespace watchTests { + { const a: adone.fs.Watcher = fs.watch("path"); } + { const a: adone.fs.Watcher = fs.watch(["path"]); } + { const a: adone.fs.Watcher = fs.watch("path", {}); } + { const a: adone.fs.Watcher = fs.watch("path", { alwaysStat: true }); } + { const a: adone.fs.Watcher = fs.watch("path", { atomic: true }); } + { const a: adone.fs.Watcher = fs.watch("path", { awaitWriteFinish: true }); } + { const a: adone.fs.Watcher = fs.watch("path", { awaitWriteFinish: {} }); } + { const a: adone.fs.Watcher = fs.watch("path", { awaitWriteFinish: { pollInterval: 100 } }); } + { const a: adone.fs.Watcher = fs.watch("path", { awaitWriteFinish: { stabilityThreshold: 100 } }); } + { const a: adone.fs.Watcher = fs.watch("path", { binaryInterval: 100 }); } + { const a: adone.fs.Watcher = fs.watch("path", { cwd: "/tmp" }); } + { const a: adone.fs.Watcher = fs.watch("path", { depth: 10 }); } + { const a: adone.fs.Watcher = fs.watch("path", { disableGlobbing: true }); } + { const a: adone.fs.Watcher = fs.watch("path", { followSymlinks: false }); } + { const a: adone.fs.Watcher = fs.watch("path", { ignored: ["hello"] }); } + { const a: adone.fs.Watcher = fs.watch("path", { ignoreInitial: false }); } + { const a: adone.fs.Watcher = fs.watch("path", { ignorePermissionErrors: false }); } + { const a: adone.fs.Watcher = fs.watch("path", { interval: 100 }); } + { const a: adone.fs.Watcher = fs.watch("path", { persistent: false }); } + { const a: adone.fs.Watcher = fs.watch("path", { useFsEvents: false }); } + { const a: adone.fs.Watcher = fs.watch("path", { usePolling: false }); } + } + + namespace isTests { + const { is } = fs; + is.file("hello").then((x: boolean) => {}); + { const a: boolean = is.fileSync("hello"); } + is.directory("hello").then((x: boolean) => {}); + { const a: boolean = is.directorySync("hello"); } + is.executable("hello").then((x: boolean) => {}); + { const a: boolean = is.executableSync("hello"); } + } + + namespace whichTests { + const { which } = fs; + + which("hello").then((x: string) => {}); + which("hello", { nothrow: true }).then((x: string | null) => {}); + which("hello", { all: true }).then((x: string[]) => {}); + which("hello", { all: true, nothrow: true }).then((x: string[] | null) => {}); + which("hello", { colon: ":" }).then((x: string) => {}); + which("hello", { path: "/" }).then((x: string) => {}); + which("hello", { pathExt: "asd" }).then((x: string) => {}); + } + + namespace whichSyncTests { + const { whichSync } = fs; + + { const a: string = whichSync("hello"); } + { const a: string | null = whichSync("hello", { nothrow: true }); } + { const a: string[] = whichSync("hello", { all: true }); } + { const a: string[] | null = whichSync("hello", { all: true, nothrow: true }); } + { const a: string = whichSync("hello", { colon: ":" }); } + { const a: string = whichSync("hello", { path: "/" }); } + { const a: string = whichSync("hello", { pathExt: "asd" }); } + } + + namespace fdTests { + const { fd } = fs; + fd.open("hello", "r+").then((x: number) => {}); + fd.open(Buffer.from("hello"), "r+").then((x: number) => {}); + fd.open(new URL("file://hello"), "r+").then((x: number) => {}); + { const a: number = fd.openSync("hello", "r+"); } + { const a: number = fd.openSync(Buffer.from("hello"), "r+"); } + { const a: number = fd.openSync(new URL("file://hello"), "r+"); } + fd.close(10).then(() => {}); + fd.closeSync(10); + fd.utimes(10, 100500, 100500).then(() => {}); + fd.utimesSync(10, 100500, 100500); + fd.stat(10).then((x: adone.fs.I.Stats) => {}); + { const a: adone.fs.I.Stats = fd.statSync(10); } + fd.truncate(10).then(() => {}); + fd.truncate(10, 10).then(() => {}); + fd.truncateSync(10); + fd.truncateSync(10, 10); + fd.read(10, Buffer.alloc(10), 0, 10, 10).then((x: number) => {}); + { const a: number = fd.readSync(10, Buffer.alloc(10), 0, 10, 10); } + fd.write(10, Buffer.alloc(10), 0, 10, 10).then((x: number) => {}); + { const a: number = fd.writeSync(10, Buffer.alloc(10), 0, 10, 10); } + fd.write(10, "hello", 10, "utf8").then((x: number) => {}); + { const a: number = fd.writeSync(10, "hello", 10, "utf8"); } + fd.sync(10).then(() => {}); + fd.syncSync(10); + fd.chown(10, 0, 0).then(() => {}); + fd.chownSync(10, 0, 0); + fd.chmod(10, 0o755).then(() => {}); + fd.chmodSync(10, 0o755); + fd.seek(10, 100, 0).then((x: number) => {}); + fd.lock(10, "sh").then(() => {}); + } + + namespace constantsTests { + // ? + const a: number = fs.constants.F_OK; + } + + namespace realpathTests { + fs.realpath("hello").then((x: string) => {}); + fs.realpath("hello", "utf8").then((x: string) => {}); + fs.realpath("hello", "buffer").then((x: Buffer) => {}); + fs.realpath("hello", { encoding: "buffer" }).then((x: Buffer) => {}); + fs.realpath("hello", { encoding: "utf8" }).then((x: string) => {}); + fs.realpath("hello", {}).then((x: string) => {}); + fs.realpath(Buffer.from("hello")).then((x: string) => {}); + fs.realpath(new URL("file://hello")).then((x: string) => {}); + } + + namespace realpathSyncTests { + { const a: string = fs.realpathSync("hello"); } + { const a: string = fs.realpathSync("hello", "utf8"); } + { const a: Buffer = fs.realpathSync("hello", "buffer"); } + { const a: Buffer = fs.realpathSync("hello", { encoding: "buffer" }); } + { const a: string = fs.realpathSync("hello", { encoding: "utf8" }); } + { const a: string = fs.realpathSync("hello", {}); } + { const a: string = fs.realpathSync(Buffer.from("hello")); } + { const a: string = fs.realpathSync(new URL("file://hello")); } + } + + namespace readFileTests { + fs.readFile("hello").then((x: Buffer) => {}); + fs.readFile(Buffer.from("hello")).then((x: Buffer) => {}); + fs.readFile(new URL("file://hello")).then((x: Buffer) => {}); + fs.readFile("hello", "utf8").then((x: string) => {}); + fs.readFile("hello", null).then((x: Buffer) => {}); + fs.readFile("hello", {}).then((x: Buffer) => {}); + fs.readFile("hello", { check: true }).then((x: null | Buffer) => {}); + fs.readFile("hello", { check: true, encoding: "utf8" }).then((x: null | string) => {}); + fs.readFile("hello", { encoding: "utf8" }).then((x: string) => {}); + fs.readFile("hello", { encoding: null }).then((x: Buffer) => {}); + fs.readFile("hello", { flags: "r+" }).then((x: Buffer) => {}); + } + + namespace readFileSyncTests { + { const a: Buffer = fs.readFileSync("hello"); } + { const a: Buffer = fs.readFileSync(Buffer.from("hello")); } + { const a: Buffer = fs.readFileSync(new URL("file://hello")); } + { const a: string = fs.readFileSync("hello", "utf8"); } + { const a: Buffer = fs.readFileSync("hello", null); } + { const a: Buffer = fs.readFileSync("hello", {}); } + { const a: null | Buffer = fs.readFileSync("hello", { check: true }); } + { const a: null | string = fs.readFileSync("hello", { check: true, encoding: "utf8" }); } + { const a: string = fs.readFileSync("hello", { encoding: "utf8" }); } + { const a: Buffer = fs.readFileSync("hello", { encoding: null }); } + { const a: Buffer = fs.readFileSync("hello", { flags: "r+" }); } + } + + namespace readLinesTests { + fs.readLines("hello").then((x: string[]) => {}); + fs.readLines(Buffer.from("hello")).then((x: string[]) => {}); + fs.readLines(new URL("file://hello")).then((x: string[]) => {}); + fs.readLines("hello", "utf8").then((x: string[]) => {}); + fs.readLines("hello", null).then((x: string[]) => {}); + fs.readLines("hello", {}).then((x: string[]) => {}); + fs.readLines("hello", { check: true }).then((x: null | string[]) => {}); + fs.readLines("hello", { encoding: "utf8" }).then((x: null | string[]) => {}); + fs.readLines("hello", { encoding: null }).then((x: null | string[]) => {}); + fs.readLines("hello", { flags: "r+" }).then((x: null | string[]) => {}); + } + + namespace readLinesSyncTests { + { const a: string[] = fs.readLinesSync("hello"); } + { const a: string[] = fs.readLinesSync(Buffer.from("hello")); } + { const a: string[] = fs.readLinesSync(new URL("file://hello")); } + { const a: string[] = fs.readLinesSync("hello", "utf8"); } + { const a: string[] = fs.readLinesSync("hello", null); } + { const a: string[] = fs.readLinesSync("hello", {}); } + { const a: null | string[] = fs.readLinesSync("hello", { check: true }); } + { const a: string[] = fs.readLinesSync("hello", { encoding: "utf8" }); } + { const a: string[] = fs.readLinesSync("hello", { encoding: null }); } + { const a: string[] = fs.readLinesSync("hello", { flags: "r+" }); } + } + + namespace readWordsTests { + fs.readWords("hello").then((x: string[]) => {}); + fs.readWords(Buffer.from("hello")).then((x: string[]) => {}); + fs.readWords(new URL("file://hello")).then((x: string[]) => {}); + fs.readWords("hello", "utf8").then((x: string[]) => {}); + fs.readWords("hello", null).then((x: string[]) => {}); + fs.readWords("hello", {}).then((x: string[]) => {}); + fs.readWords("hello", { check: true }).then((x: null | string[]) => {}); + fs.readWords("hello", { encoding: "utf8" }).then((x: null | string[]) => {}); + fs.readWords("hello", { encoding: null }).then((x: null | string[]) => {}); + fs.readWords("hello", { flags: "r+" }).then((x: null | string[]) => {}); + } + + namespace readWordsSyncTests { + { const a: string[] = fs.readWordsSync("hello"); } + { const a: string[] = fs.readWordsSync(Buffer.from("hello")); } + { const a: string[] = fs.readWordsSync(new URL("file://hello")); } + { const a: string[] = fs.readWordsSync("hello", "utf8"); } + { const a: string[] = fs.readWordsSync("hello", null); } + { const a: string[] = fs.readWordsSync("hello", {}); } + { const a: null | string[] = fs.readWordsSync("hello", { check: true }); } + { const a: string[] = fs.readWordsSync("hello", { encoding: "utf8" }); } + { const a: string[] = fs.readWordsSync("hello", { encoding: null }); } + { const a: string[] = fs.readWordsSync("hello", { flags: "r+" }); } + } + + namespace existsTests { + fs.exists("hello").then((x: boolean) => {}); + fs.exists(Buffer.from("hello")).then((x: boolean) => {}); + fs.exists(new URL("file://hello")).then((x: boolean) => {}); + } + + namespace existsSyncTests { + { const a: boolean = fs.existsSync("hello"); } + { const a: boolean = fs.existsSync(Buffer.from("hello")); } + { const a: boolean = fs.existsSync(new URL("file://hello")); } + } + + namespace mkdirTests { + fs.mkdir("/path/to/some/dir").then(() => {}); + fs.mkdir("/path/to/some/dir", 0o755).then(() => {}); + } + + namespace copyTests { + fs.copy("a", "b").then(() => {}); + fs.copy("a", "b", {}).then(() => {}); + fs.copy("a", "b", { cwd: "/tmp" }).then(() => {}); + fs.copy("a", "b", { ignoreExisting: true }).then(() => {}); + } + + namespace renameTests { + fs.rename("a", "b").then(() => {}); + fs.rename("a", "b", {}).then(() => {}); + fs.rename("a", "b", { delay: 100 }).then(() => {}); + fs.rename("a", "b", { retries: 100 }).then(() => {}); + } + + namespace tailTests { + fs.tail("file", 10).then((x: Buffer[]) => {}); + fs.tail("file", 10, {}).then((x: Buffer[]) => {}); + fs.tail("file", 10, { separator: "\n" }).then((x: Buffer[]) => {}); + fs.tail("file", 10, { chunkLength: 4096 }).then((x: Buffer[]) => {}); + } + + namespace statVFSTests { + fs.statVFS("/tmp").then((x) => { + { const a: number = x.f_namemax; } + { const a: number = x.f_bsize; } + { const a: number = x.f_frsize; } + { const a: number = x.f_blocks; } + { const a: number = x.f_bavail; } + { const a: number = x.f_bfree; } + { const a: number = x.f_files; } + { const a: number = x.f_favail; } + { const a: number = x.f_ffree; } + }); + } + + namespace createReadStreamTests { + fs.createReadStream("file").on("data", (chunk) => {}); + fs.createReadStream(Buffer.from("file")).on("data", (chunk) => {}); + fs.createReadStream(new URL("file://file")).on("data", (chunk) => {}); + fs.createReadStream("file", null).on("data", (chunk) => {}); + fs.createReadStream("file", "utf8").on("data", (chunk) => {}); + fs.createReadStream("file", { encoding: "usc2" }).on("data", (chunk) => {}); + fs.createReadStream("file", { encoding: null }).on("data", (chunk) => {}); + fs.createReadStream("file", { flags: "r+" }).on("data", (chunk) => {}); + fs.createReadStream(null, { fd: 10, autoClose: false }).on("data", (chunk) => {}); + fs.createReadStream(undefined, { fd: 10 }).on("data", (chunk) => {}); + fs.createReadStream(null, { fd: 10 }).on("data", (chunk) => {}); + fs.createReadStream("file", { mode: 0o666 }).on("data", (chunk) => {}); + fs.createReadStream("file", { start: 100 }).on("data", (chunk) => {}); + fs.createReadStream("file", { end: 110 }).on("data", (chunk) => {}); + } + + namespace createWriteStreamTests { + fs.createWriteStream("file").on("data", (chunk) => {}); + fs.createWriteStream(Buffer.from("file")).on("data", (chunk) => {}); + fs.createWriteStream(new URL("file://file")).on("data", (chunk) => {}); + fs.createWriteStream("file", null).on("data", (chunk) => {}); + fs.createWriteStream("file", "utf8").on("data", (chunk) => {}); + fs.createWriteStream("file", { defaultEncoding: "usc2" }).on("data", (chunk) => {}); + fs.createWriteStream("file", { defaultEncoding: null }).on("data", (chunk) => {}); + fs.createWriteStream("file", { flags: "r+" }).on("data", (chunk) => {}); + fs.createWriteStream(null, { fd: 10, autoClose: false }).on("data", (chunk) => {}); + fs.createWriteStream(undefined, { fd: 10 }).on("data", (chunk) => {}); + fs.createWriteStream(null, { fd: 10 }).on("data", (chunk) => {}); + fs.createWriteStream("file", { mode: 0o666 }).on("data", (chunk) => {}); + fs.createWriteStream("file", { start: 100 }).on("data", (chunk) => {}); + } + + namespace tmpNameTests { + fs.tmpName().then((x: string) => {}); + fs.tmpName({}).then((x: string) => {}); + fs.tmpName({ dir: "/" }).then((x: string) => {}); + fs.tmpName({ ext: ".exe" }).then((x: string) => {}); + fs.tmpName({ name: "ad" }).then((x: string) => {}); + fs.tmpName({ prefix: "/tmp/tmp-" }).then((x: string) => {}); + fs.tmpName({ template: /XXX/ }).then((x: string) => {}); + fs.tmpName({ tries: 100 }).then((x: string) => {}); + } + + namespace homeDirTests { + const a: string = fs.homeDir(); + } + + namespace lookupTests { + // TODO + } + + namespace chownrTests { + fs.chownr("hello", 1000, 1000).then(() => {}); + } + + namespace TailWatcherTests { + new fs.TailWatcher("file"); + new fs.TailWatcher("file", {}); + new fs.TailWatcher("file", { encoding: "utf8" }); + new fs.TailWatcher("file", { follow: true }); + new fs.TailWatcher("file", { fromBeginning: true }); + new fs.TailWatcher("file", { fsWatchOptions: {} }); + new fs.TailWatcher("file", { pos: 100 }); + new fs.TailWatcher("file", { separator: "\n" }); + new fs.TailWatcher("file", { separator: /\n/ }); + new fs.TailWatcher("file", { useWatchFile: true }); + const tw = new fs.TailWatcher("file"); + tw.unwatch(); + tw.on("line", (line: string) => { + }); + } + + namespace watchTailTests { + const tw: adone.fs.TailWatcher = fs.watchTail("file"); + fs.watchTail("file", {}); + fs.watchTail("file", { encoding: "utf8" }); + fs.watchTail("file", { follow: true }); + fs.watchTail("file", { fromBeginning: true }); + fs.watchTail("file", { fsWatchOptions: {} }); + fs.watchTail("file", { pos: 100 }); + fs.watchTail("file", { separator: "\n" }); + fs.watchTail("file", { separator: /\n/ }); + fs.watchTail("file", { useWatchFile: true }); + } +} diff --git a/types/adone/test/glosses/is.ts b/types/adone/test/glosses/is.ts new file mode 100644 index 0000000000..2734824822 --- /dev/null +++ b/types/adone/test/glosses/is.ts @@ -0,0 +1,115 @@ +namespace isTests { + { const a: boolean = adone.is.null({}); } + { const a: boolean = adone.is.undefined({}); } + { const a: boolean = adone.is.exist({}); } + { const a: boolean = adone.is.nil({}); } + { const a: boolean = adone.is.number({}); } + { const a: boolean = adone.is.numeral({}); } + { const a: boolean = adone.is.infinite({}); } + { const a: boolean = adone.is.odd({}); } + { const a: boolean = adone.is.even({}); } + { const a: boolean = adone.is.float({}); } + { const a: boolean = adone.is.negativeZero({}); } + { const a: boolean = adone.is.string({}); } + { const a: boolean = adone.is.emptyString({}); } + { const a: boolean = adone.is.substring("abc", "abcdef"); } + { const a: boolean = adone.is.substring("abc", "abcdef", 0); } + { const a: boolean = adone.is.prefix("abc", "abcdef"); } + { const a: boolean = adone.is.suffix("def", "abbdef"); } + { const a: boolean = adone.is.boolean({}); } + { const a: boolean = adone.is.json({}); } + { const a: boolean = adone.is.object({}); } + { const a: boolean = adone.is.plainObject({}); } + { const a: boolean = adone.is.class({}); } + { const a: boolean = adone.is.emptyObject({}); } + { const a: boolean = adone.is.propertyOwned({}, "a"); } + { const a: boolean = adone.is.propertyDefined({}, "a"); } + { const a: boolean = adone.is.conforms({}, {}); } + { const a: boolean = adone.is.conforms({}, {}, true); } + { const a: boolean = adone.is.arrayLikeObject({}); } + { const a: boolean = adone.is.inArray(1, [1, 2, 3]); } + { const a: boolean = adone.is.inArray(1, [1, 2, 3], 0); } + { const a: boolean = adone.is.inArray(1, [1, 2, 3], 0, (a, b) => a === b); } + { const a: boolean = adone.is.sameType({}, {}); } + { const a: boolean = adone.is.primitive({}); } + { const a: boolean = adone.is.equalArrays([], []); } + { const a: boolean = adone.is.deepEqual({}, {}); } + { const a: boolean = adone.is.shallowEqual({}, {}); } + { const a: boolean = adone.is.stream({}); } + { const a: boolean = adone.is.writableStream({}); } + { const a: boolean = adone.is.readableStream({}); } + { const a: boolean = adone.is.duplexStream({}); } + { const a: boolean = adone.is.transformStream({}); } + { const a: boolean = adone.is.utf8(Buffer.alloc(10)); } + { const a: boolean = adone.is.win32PathAbsolute("abc"); } + { const a: boolean = adone.is.posixPathAbsolute("abc"); } + { const a: boolean = adone.is.pathAbsolute("abc"); } + { const a: boolean = adone.is.glob("abc"); } + { const a: boolean = adone.is.dotfile("abc"); } + { const a: boolean = adone.is.function(() => { }); } + { const a: boolean = adone.is.asyncFunction(async () => { }); } + { const a: boolean = adone.is.promise({}); } + { const a: boolean = adone.is.validDate("07.08.2017"); } + { const a: boolean = adone.is.buffer({}); } + { const a: boolean = adone.is.callback({}); } + { const a: boolean = adone.is.generator({}); } + { const a: boolean = adone.is.nan({}); } + { const a: boolean = adone.is.finite({}); } + { const a: boolean = adone.is.integer({}); } + { const a: boolean = adone.is.safeInteger({}); } + { const a: boolean = adone.is.array({}); } + { const a: boolean = adone.is.uint8Array({}); } + { const a: boolean = adone.is.configuration({}); } + { const a: boolean = adone.is.long({}); } + { const a: boolean = adone.is.bigNumber({}); } + { const a: boolean = adone.is.byteArray({}); } + { const a: boolean = adone.is.datetime({}); } + { const a: boolean = adone.is.transform({}); } + { const a: boolean = adone.is.subsystem({}); } + { const a: boolean = adone.is.application({}); } + { const a: boolean = adone.is.logger({}); } + { const a: boolean = adone.is.coreStream({}); } + { const a: boolean = adone.is.fastStream({}); } + { const a: boolean = adone.is.fastLocalStream({}); } + { const a: boolean = adone.is.fastLocalMapStream({}); } + { const a: boolean = adone.is.genesisNetron({}); } + { const a: boolean = adone.is.genesisPeer({}); } + { const a: boolean = adone.is.netronAdapter({}); } + { const a: boolean = adone.is.netron({}); } + { const a: boolean = adone.is.netronPeer({}); } + { const a: boolean = adone.is.netronDefinition({}); } + { const a: boolean = adone.is.netronDefinitions({}); } + { const a: boolean = adone.is.netronReference({}); } + { const a: boolean = adone.is.netronInterface({}); } + { const a: boolean = adone.is.netronContext({}); } + { const a: boolean = adone.is.netronIMethod({}, "hello"); } + { const a: boolean = adone.is.netronIProperty({}, "hello"); } + { const a: boolean = adone.is.netronStub({}); } + { const a: boolean = adone.is.netronRemoteStub({}); } + { const a: boolean = adone.is.netronStream({}); } + { const a: boolean = adone.is.iterable({}); } + { const a: boolean = adone.is.windows; } + { const a: boolean = adone.is.linux; } + { const a: boolean = adone.is.freebsd; } + { const a: boolean = adone.is.darwin; } + { const a: boolean = adone.is.sunos; } + { const a: boolean = adone.is.uppercase("abc"); } + { const a: boolean = adone.is.lowercase("abc"); } + { const a: boolean = adone.is.digits("012"); } + { const a: boolean = adone.is.identifier("someMethod"); } + { const a: boolean = adone.is.binaryExtension("mp3"); } + { const a: boolean = adone.is.binaryPath("a.mp3"); } + { const a: boolean = adone.is.ip4("192.168.1.1"); } + { const a: boolean = adone.is.ip6("::192.168.1.1"); } + { const a: boolean = adone.is.arrayBuffer({}); } + { const a: boolean = adone.is.arrayBufferView({}); } + { const a: boolean = adone.is.date({}); } + { const a: boolean = adone.is.error({}); } + { const a: boolean = adone.is.map({}); } + { const a: boolean = adone.is.regexp({}); } + { const a: boolean = adone.is.set({}); } + { const a: boolean = adone.is.symbol({}); } + { const a: boolean = adone.is.validUTF8(Buffer.from("hello")); } + { const a: boolean = adone.is.vaultValuable({}); } + { const a: boolean = adone.is.task({}); } +} diff --git a/types/adone/test/glosses/math.ts b/types/adone/test/glosses/math.ts deleted file mode 100644 index 8a9e9bc1cf..0000000000 --- a/types/adone/test/glosses/math.ts +++ /dev/null @@ -1,259 +0,0 @@ -const { math } = adone; - -namespace mathTests { - namespace Long { - new math.Long(); - new math.Long(0); - new math.Long(0, 0); - new math.Long(0, 0, true); - - namespace toInt { - const a: number = new math.Long().toInt(); - } - - namespace toNumber { - const a: number = new math.Long().toNumber(); - } - - namespace toString { - const a: string = new math.Long().toString(); - const b: string = new math.Long().toString(16); - } - - namespace getHighBits { - const a: number = new math.Long().getHighBits(); - } - - namespace getLowBits { - const a: number = new math.Long().getLowBits(); - } - - namespace getLowBitsUnsigned { - const a: number = new math.Long().getLowBitsUnsigned(); - } - - namespace getHighBitsUnsigned { - const a: number = new math.Long().getHighBitsUnsigned(); - } - - namespace getNumBitsAbs { - const a: number = new math.Long().getNumBitsAbs(); - } - - namespace isZero { - const a: boolean = new math.Long().isZero(); - } - - namespace isNegative { - const a: boolean = new math.Long().isNegative(); - } - - namespace isPositive { - const a: boolean = new math.Long().isPositive(); - } - - namespace isOdd { - const a: boolean = new math.Long().isOdd(); - } - - namespace isEven { - const a: boolean = new math.Long().isEven(); - } - - namespace equals { - const a = new math.Long(); - const b: boolean = a.equals(new math.Long()); - const c: boolean = a.equals(1); - const d: boolean = a.equals("1"); - const e: boolean = a.equals({ low: 0, high: 0 }); - } - - namespace lessThan { - const a = new math.Long(); - const b: boolean = a.lessThan(new math.Long()); - const c: boolean = a.lessThan(1); - const d: boolean = a.lessThan("1"); - const e: boolean = a.lessThan({ low: 0, high: 0 }); - } - - namespace lessThanOrEqual { - const a = new math.Long(); - const b: boolean = a.lessThanOrEqual(new math.Long()); - const c: boolean = a.lessThanOrEqual(1); - const d: boolean = a.lessThanOrEqual("1"); - const e: boolean = a.lessThanOrEqual({ low: 0, high: 0 }); - } - - namespace greaterThan { - const a = new math.Long(); - const b: boolean = a.greaterThan(new math.Long()); - const c: boolean = a.greaterThan(1); - const d: boolean = a.greaterThan("1"); - const e: boolean = a.greaterThan({ low: 0, high: 0 }); - } - - namespace greaterThanOrEqual { - const a = new math.Long(); - const b: boolean = a.greaterThanOrEqual(new math.Long()); - const c: boolean = a.greaterThanOrEqual(1); - const d: boolean = a.greaterThanOrEqual("1"); - const e: boolean = a.greaterThanOrEqual({ low: 0, high: 0 }); - } - - namespace greaterThanOrEqual { - const a = new math.Long(); - const b: number = a.compare(new math.Long()); - const c: number = a.compare(1); - const d: number = a.compare("1"); - const e: number = a.compare({ low: 0, high: 0 }); - } - - namespace negate { - const a: adone.math.Long = new math.Long().negate(); - } - - namespace add { - const a = new math.Long(); - const b: adone.math.Long = a.add(new math.Long()); - const c: adone.math.Long = a.add(1); - const d: adone.math.Long = a.add("1"); - const e: adone.math.Long = a.add({ low: 0, high: 0 }); - } - - namespace sub { - const a = new math.Long(); - const b: adone.math.Long = a.sub(new math.Long()); - const c: adone.math.Long = a.sub(1); - const d: adone.math.Long = a.sub("1"); - const e: adone.math.Long = a.sub({ low: 0, high: 0 }); - } - - namespace mul { - const a = new math.Long(); - const b: adone.math.Long = a.mul(new math.Long()); - const c: adone.math.Long = a.mul(1); - const d: adone.math.Long = a.mul("1"); - const e: adone.math.Long = a.mul({ low: 0, high: 0 }); - } - - namespace div { - const a = new math.Long(); - const b: adone.math.Long = a.div(new math.Long()); - const c: adone.math.Long = a.div(1); - const d: adone.math.Long = a.div("1"); - const e: adone.math.Long = a.div({ low: 0, high: 0 }); - } - - namespace mod { - const a = new math.Long(); - const b: adone.math.Long = a.mod(new math.Long()); - const c: adone.math.Long = a.mod(1); - const d: adone.math.Long = a.mod("1"); - const e: adone.math.Long = a.mod({ low: 0, high: 0 }); - } - - namespace not { - const a: adone.math.Long = new math.Long().not(); - } - - namespace and { - const a = new math.Long(); - const b: adone.math.Long = a.and(new math.Long()); - const c: adone.math.Long = a.and(1); - const d: adone.math.Long = a.and("1"); - const e: adone.math.Long = a.and({ low: 0, high: 0 }); - } - - namespace or { - const a = new math.Long(); - const b: adone.math.Long = a.or(new math.Long()); - const c: adone.math.Long = a.or(1); - const d: adone.math.Long = a.or("1"); - const e: adone.math.Long = a.or({ low: 0, high: 0 }); - } - - namespace xor { - const a = new math.Long(); - const b: adone.math.Long = a.xor(new math.Long()); - const c: adone.math.Long = a.xor(1); - const d: adone.math.Long = a.xor("1"); - const e: adone.math.Long = a.xor({ low: 0, high: 0 }); - } - - namespace shl { - const a = new math.Long(); - const b: adone.math.Long = a.shl(new math.Long()); - const c: adone.math.Long = a.shl(1); - } - - namespace shr { - const a = new math.Long(); - const b: adone.math.Long = a.shr(new math.Long()); - const c: adone.math.Long = a.shr(1); - } - - namespace shru { - const a = new math.Long(); - const b: adone.math.Long = a.shr(new math.Long()); - const c: adone.math.Long = a.shr(1); - } - - namespace toSigned { - const a: adone.math.Long = new math.Long().toSigned(); - } - - namespace toUnsigned { - const a: adone.math.Long = new math.Long().toUnsigned(); - } - - namespace toBytes { - const a: number[] = new math.Long().toBytes(); - } - - namespace toBytesLE { - const a: number[] = new math.Long().toBytesLE(); - } - - namespace static { - namespace fromInt { - const a: adone.math.Long = math.Long.fromInt(123); - const b: adone.math.Long = math.Long.fromInt(123, true); - } - - namespace fromNumber { - const a: adone.math.Long = math.Long.fromNumber(123); - const b: adone.math.Long = math.Long.fromNumber(123, true); - } - - namespace fromBits { - const a: adone.math.Long = math.Long.fromBits(0, 0); - const b: adone.math.Long = math.Long.fromBits(123, 0, true); - } - - namespace fromString { - const a: adone.math.Long = math.Long.fromString("123"); - const b: adone.math.Long = math.Long.fromString("123", true); - const c: adone.math.Long = math.Long.fromString("123", 16); - const d: adone.math.Long = math.Long.fromString("123", true, 16); - } - - namespace fromValue { - const a: adone.math.Long = math.Long.fromValue(new math.Long()); - const b: adone.math.Long = math.Long.fromValue(1); - const c: adone.math.Long = math.Long.fromValue("1"); - const e: adone.math.Long = math.Long.fromValue({ low: 0, high: 0 }); - } - - namespace constants { - const a: adone.math.Long = math.Long.MIN_VALUE; - const b: adone.math.Long = math.Long.MAX_VALUE; - const c: adone.math.Long = math.Long.MAX_UNSIGNED_VALUE; - const d: adone.math.Long = math.Long.ZERO; - const e: adone.math.Long = math.Long.UZERO; - const f: adone.math.Long = math.Long.ONE; - const g: adone.math.Long = math.Long.UONE; - const h: adone.math.Long = math.Long.NEG_ONE; - } - } - } -} diff --git a/types/adone/test/glosses/math/index.ts b/types/adone/test/glosses/math/index.ts new file mode 100644 index 0000000000..928977fad9 --- /dev/null +++ b/types/adone/test/glosses/math/index.ts @@ -0,0 +1,474 @@ +namespace mathTests { + const { math } = adone; + + namespace LongTests { + new math.Long(); + new math.Long(0); + new math.Long(0, 0); + new math.Long(0, 0, true); + + namespace toInt { + const a: number = new math.Long().toInt(); + } + + namespace toNumber { + const a: number = new math.Long().toNumber(); + } + + namespace toString { + const a: string = new math.Long().toString(); + const b: string = new math.Long().toString(16); + } + + namespace getHighBits { + const a: number = new math.Long().getHighBits(); + } + + namespace getLowBits { + const a: number = new math.Long().getLowBits(); + } + + namespace getLowBitsUnsigned { + const a: number = new math.Long().getLowBitsUnsigned(); + } + + namespace getHighBitsUnsigned { + const a: number = new math.Long().getHighBitsUnsigned(); + } + + namespace getNumBitsAbs { + const a: number = new math.Long().getNumBitsAbs(); + } + + namespace isZero { + const a: boolean = new math.Long().isZero(); + } + + namespace isNegative { + const a: boolean = new math.Long().isNegative(); + } + + namespace isPositive { + const a: boolean = new math.Long().isPositive(); + } + + namespace isOdd { + const a: boolean = new math.Long().isOdd(); + } + + namespace isEven { + const a: boolean = new math.Long().isEven(); + } + + namespace equals { + const a = new math.Long(); + const b: boolean = a.equals(new math.Long()); + const c: boolean = a.equals(1); + const d: boolean = a.equals("1"); + const e: boolean = a.equals({ low: 0, high: 0 }); + } + + namespace lessThan { + const a = new math.Long(); + const b: boolean = a.lessThan(new math.Long()); + const c: boolean = a.lessThan(1); + const d: boolean = a.lessThan("1"); + const e: boolean = a.lessThan({ low: 0, high: 0 }); + } + + namespace lessThanOrEqual { + const a = new math.Long(); + const b: boolean = a.lessThanOrEqual(new math.Long()); + const c: boolean = a.lessThanOrEqual(1); + const d: boolean = a.lessThanOrEqual("1"); + const e: boolean = a.lessThanOrEqual({ low: 0, high: 0 }); + } + + namespace greaterThan { + const a = new math.Long(); + const b: boolean = a.greaterThan(new math.Long()); + const c: boolean = a.greaterThan(1); + const d: boolean = a.greaterThan("1"); + const e: boolean = a.greaterThan({ low: 0, high: 0 }); + } + + namespace greaterThanOrEqual { + const a = new math.Long(); + const b: boolean = a.greaterThanOrEqual(new math.Long()); + const c: boolean = a.greaterThanOrEqual(1); + const d: boolean = a.greaterThanOrEqual("1"); + const e: boolean = a.greaterThanOrEqual({ low: 0, high: 0 }); + } + + namespace compareTests { + const a = new math.Long(); + const b: number = a.compare(new math.Long()); + const c: number = a.compare(1); + const d: number = a.compare("1"); + const e: number = a.compare({ low: 0, high: 0 }); + } + + namespace negate { + const a: adone.math.Long = new math.Long().negate(); + } + + namespace add { + const a = new math.Long(); + const b: adone.math.Long = a.add(new math.Long()); + const c: adone.math.Long = a.add(1); + const d: adone.math.Long = a.add("1"); + const e: adone.math.Long = a.add({ low: 0, high: 0 }); + } + + namespace sub { + const a = new math.Long(); + const b: adone.math.Long = a.sub(new math.Long()); + const c: adone.math.Long = a.sub(1); + const d: adone.math.Long = a.sub("1"); + const e: adone.math.Long = a.sub({ low: 0, high: 0 }); + } + + namespace mul { + const a = new math.Long(); + const b: adone.math.Long = a.mul(new math.Long()); + const c: adone.math.Long = a.mul(1); + const d: adone.math.Long = a.mul("1"); + const e: adone.math.Long = a.mul({ low: 0, high: 0 }); + } + + namespace div { + const a = new math.Long(); + const b: adone.math.Long = a.div(new math.Long()); + const c: adone.math.Long = a.div(1); + const d: adone.math.Long = a.div("1"); + const e: adone.math.Long = a.div({ low: 0, high: 0 }); + } + + namespace mod { + const a = new math.Long(); + const b: adone.math.Long = a.mod(new math.Long()); + const c: adone.math.Long = a.mod(1); + const d: adone.math.Long = a.mod("1"); + const e: adone.math.Long = a.mod({ low: 0, high: 0 }); + } + + namespace not { + const a: adone.math.Long = new math.Long().not(); + } + + namespace and { + const a = new math.Long(); + const b: adone.math.Long = a.and(new math.Long()); + const c: adone.math.Long = a.and(1); + const d: adone.math.Long = a.and("1"); + const e: adone.math.Long = a.and({ low: 0, high: 0 }); + } + + namespace or { + const a = new math.Long(); + const b: adone.math.Long = a.or(new math.Long()); + const c: adone.math.Long = a.or(1); + const d: adone.math.Long = a.or("1"); + const e: adone.math.Long = a.or({ low: 0, high: 0 }); + } + + namespace xor { + const a = new math.Long(); + const b: adone.math.Long = a.xor(new math.Long()); + const c: adone.math.Long = a.xor(1); + const d: adone.math.Long = a.xor("1"); + const e: adone.math.Long = a.xor({ low: 0, high: 0 }); + } + + namespace shl { + const a = new math.Long(); + const b: adone.math.Long = a.shl(new math.Long()); + const c: adone.math.Long = a.shl(1); + } + + namespace shr { + const a = new math.Long(); + const b: adone.math.Long = a.shr(new math.Long()); + const c: adone.math.Long = a.shr(1); + } + + namespace shru { + const a = new math.Long(); + const b: adone.math.Long = a.shr(new math.Long()); + const c: adone.math.Long = a.shr(1); + } + + namespace toSigned { + const a: adone.math.Long = new math.Long().toSigned(); + } + + namespace toUnsigned { + const a: adone.math.Long = new math.Long().toUnsigned(); + } + + namespace toBytes { + const a: number[] = new math.Long().toBytes(); + } + + namespace toBytesLE { + const a: number[] = new math.Long().toBytesLE(); + } + + namespace static { + namespace fromInt { + const a: adone.math.Long = math.Long.fromInt(123); + const b: adone.math.Long = math.Long.fromInt(123, true); + } + + namespace fromNumber { + const a: adone.math.Long = math.Long.fromNumber(123); + const b: adone.math.Long = math.Long.fromNumber(123, true); + } + + namespace fromBits { + const a: adone.math.Long = math.Long.fromBits(0, 0); + const b: adone.math.Long = math.Long.fromBits(123, 0, true); + } + + namespace fromString { + const a: adone.math.Long = math.Long.fromString("123"); + const b: adone.math.Long = math.Long.fromString("123", true); + const c: adone.math.Long = math.Long.fromString("123", 16); + const d: adone.math.Long = math.Long.fromString("123", true, 16); + } + + namespace fromValue { + const a: adone.math.Long = math.Long.fromValue(new math.Long()); + const b: adone.math.Long = math.Long.fromValue(1); + const c: adone.math.Long = math.Long.fromValue("1"); + const e: adone.math.Long = math.Long.fromValue({ low: 0, high: 0 }); + } + + namespace constants { + const a: adone.math.Long = math.Long.MIN_VALUE; + const b: adone.math.Long = math.Long.MAX_VALUE; + const c: adone.math.Long = math.Long.MAX_UNSIGNED_VALUE; + const d: adone.math.Long = math.Long.ZERO; + const e: adone.math.Long = math.Long.UZERO; + const f: adone.math.Long = math.Long.ONE; + const g: adone.math.Long = math.Long.UONE; + const h: adone.math.Long = math.Long.NEG_ONE; + } + } + } + + namespace BigNumberTests { + const { BigNumber } = math; + type BigNumber = adone.math.BigNumber; + + new BigNumber(10); + new BigNumber("10"); + new BigNumber(new BigNumber(10)); + new BigNumber("10", 2); + + { const a: string = new BigNumber(1).toString(); } + { const a: string = new BigNumber(1).toString(2); } + + { const a: number = new BigNumber(1).toNumber(); } + + { const a: Buffer = new BigNumber(1).toBuffer(); } + { const a: Buffer = new BigNumber(1).toBuffer({}); } + { const a: Buffer = new BigNumber(1).toBuffer({ endian: 1 }); } + { const a: Buffer = new BigNumber(1).toBuffer({ endian: -1 }); } + { const a: Buffer = new BigNumber(1).toBuffer({ endian: "big" }); } + { const a: Buffer = new BigNumber(1).toBuffer({ endian: "little" }); } + { const a: Buffer = new BigNumber(1).toBuffer({ size: 1 }); } + { const a: Buffer = new BigNumber(1).toBuffer({ size: "auto" }); } + + { const a: BigNumber = new BigNumber(10).add(1); } + { const a: BigNumber = new BigNumber(10).add("1"); } + { const a: BigNumber = new BigNumber(10).add(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).sub(1); } + { const a: BigNumber = new BigNumber(10).sub("1"); } + { const a: BigNumber = new BigNumber(10).sub(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).mul(1); } + { const a: BigNumber = new BigNumber(10).mul("1"); } + { const a: BigNumber = new BigNumber(10).mul(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).div(1); } + { const a: BigNumber = new BigNumber(10).div("1"); } + { const a: BigNumber = new BigNumber(10).div(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).abs(); } + + { const a: BigNumber = new BigNumber(10).neg(); } + + { const a: number = new BigNumber(10).cmp(1); } + { const a: number = new BigNumber(10).cmp("1"); } + { const a: number = new BigNumber(10).cmp(new BigNumber(1)); } + + { const a: boolean = new BigNumber(10).gt(1); } + { const a: boolean = new BigNumber(10).gt("1"); } + { const a: boolean = new BigNumber(10).gt(new BigNumber(10)); } + + { const a: boolean = new BigNumber(10).ge(1); } + { const a: boolean = new BigNumber(10).ge("1"); } + { const a: boolean = new BigNumber(10).ge(new BigNumber(10)); } + + { const a: boolean = new BigNumber(10).eq(1); } + { const a: boolean = new BigNumber(10).eq("1"); } + { const a: boolean = new BigNumber(10).eq(new BigNumber(10)); } + + { const a: boolean = new BigNumber(10).lt(1); } + { const a: boolean = new BigNumber(10).lt("1"); } + { const a: boolean = new BigNumber(10).lt(new BigNumber(10)); } + + { const a: boolean = new BigNumber(10).le(1); } + { const a: boolean = new BigNumber(10).le("1"); } + { const a: boolean = new BigNumber(10).le(new BigNumber(10)); } + + { const a: BigNumber = new BigNumber(10).and(1); } + { const a: BigNumber = new BigNumber(10).and("1"); } + { const a: BigNumber = new BigNumber(10).and(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).or(1); } + { const a: BigNumber = new BigNumber(10).or("1"); } + { const a: BigNumber = new BigNumber(10).or(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).xor(1); } + { const a: BigNumber = new BigNumber(10).xor("1"); } + { const a: BigNumber = new BigNumber(10).xor(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).mod(1); } + { const a: BigNumber = new BigNumber(10).mod("1"); } + { const a: BigNumber = new BigNumber(10).mod(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).pow(1); } + { const a: BigNumber = new BigNumber(10).pow("1"); } + { const a: BigNumber = new BigNumber(10).pow(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).powm(1, 1); } + { const a: BigNumber = new BigNumber(10).powm("1", 1); } + { const a: BigNumber = new BigNumber(10).powm(new BigNumber(1), 1); } + { const a: BigNumber = new BigNumber(10).powm(1, "1"); } + { const a: BigNumber = new BigNumber(10).powm("1", "1"); } + { const a: BigNumber = new BigNumber(10).powm(new BigNumber(1), "1"); } + { const a: BigNumber = new BigNumber(10).powm(1, new BigNumber(1)); } + { const a: BigNumber = new BigNumber(10).powm("1", new BigNumber(1)); } + { const a: BigNumber = new BigNumber(10).powm(new BigNumber(1), new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).invertm(1); } + { const a: BigNumber = new BigNumber(10).invertm("1"); } + { const a: BigNumber = new BigNumber(10).invertm(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).rand(); } + { const a: BigNumber = new BigNumber(10).rand(1); } + { const a: BigNumber = new BigNumber(10).rand("1"); } + { const a: BigNumber = new BigNumber(10).rand(new BigNumber(1)); } + + { const a: boolean | "maybe" = new BigNumber(10).probPrime(); } + + { const a: BigNumber = new BigNumber(10).nextPrime(); } + + { const a: BigNumber = new BigNumber(10).sqrt(); } + + { const a: BigNumber = new BigNumber(10).root(1); } + { const a: BigNumber = new BigNumber(10).root("1"); } + { const a: BigNumber = new BigNumber(10).root(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).shiftLeft(1); } + { const a: BigNumber = new BigNumber(10).shiftLeft("1"); } + { const a: BigNumber = new BigNumber(10).shiftLeft(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).shiftRight(1); } + { const a: BigNumber = new BigNumber(10).shiftRight("1"); } + { const a: BigNumber = new BigNumber(10).shiftRight(new BigNumber(1)); } + + { const a: BigNumber = new BigNumber(10).gcd(1); } + { const a: BigNumber = new BigNumber(10).gcd("1"); } + { const a: BigNumber = new BigNumber(10).gcd(new BigNumber(1)); } + + { const a: number = new BigNumber(10).jacobi(1); } + { const a: number = new BigNumber(10).jacobi("1"); } + { const a: number = new BigNumber(10).jacobi(new BigNumber(1)); } + + { const a: number = new BigNumber(10).bitLength(); } + + { const a: boolean = new BigNumber(10).isBitSet(10); } + + { const a: BigNumber = BigNumber.prime(10); } + { const a: BigNumber = BigNumber.prime(10, true); } + + { const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10)); } + { const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: "little" }); } + { const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: -1 }); } + { const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: 1 }); } + { const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { endian: "big" }); } + { const a: BigNumber = BigNumber.fromBuffer(Buffer.alloc(10), { size: "auto" }); } + + { const a: BigNumber = BigNumber.ONE; } + { const a: BigNumber = BigNumber.ZERO; } + } + + namespace bitSetTests { + const { BitSet } = math; + type BitSet = adone.math.BitSet; + + new BitSet(10); + new BitSet(new BitSet(10).dehydrate()); + + { const a: boolean = new BitSet(10).get(0); } + { const a: boolean = new BitSet(10).set(0); } + { const a: boolean = new BitSet(10).setRange(0, 10); } + { const a: boolean = new BitSet(10).unset(0); } + { const a: boolean = new BitSet(10).unsetRange(0, 10); } + { const a: boolean = new BitSet(10).toggle(0); } + { const a: boolean = new BitSet(10).toggleRange(0, 10); } + { const a: boolean = new BitSet(10).clear(); } + { const a: BitSet = new BitSet(10).clone(); } + { const a: string = new BitSet(10).dehydrate(); } + + { const a: BitSet = new BitSet(10).and(1); } + { const a: BitSet = new BitSet(10).and(new BitSet(10)); } + + { const a: BitSet = new BitSet(10).or(1); } + { const a: BitSet = new BitSet(10).or(new BitSet(10)); } + + { const a: BitSet = new BitSet(10).xor(1); } + { const a: BitSet = new BitSet(10).xor(new BitSet(10)); } + + new BitSet(10).forEach((x: number) => {}); + new BitSet(10).forEach((x: number) => false); + + { const a: BitSet = new BitSet(10).circularShift(10); } + { const a: number = new BitSet(10).getCardinality(); } + { const a: number[] = new BitSet(10).getIndices(); } + { const a: boolean = new BitSet(10).isSubsetOf(new BitSet(10)); } + { const a: boolean = new BitSet(10).isEmpty(); } + { const a: boolean = new BitSet(10).isEqual(new BitSet(10)); } + { const a: string = new BitSet(10).toString(); } + { const a: number = new BitSet(10).ffs(); } + { const a: number = new BitSet(10).ffs(1); } + { const a: number = new BitSet(10).ffz(); } + { const a: number = new BitSet(10).ffz(1); } + { const a: number = new BitSet(10).fls(); } + { const a: number = new BitSet(10).fls(1); } + { const a: number = new BitSet(10).flz(); } + { const a: number = new BitSet(10).flz(1); } + { const a: number = new BitSet(10).nextSetBit(1); } + { const a: number = new BitSet(10).nextUnsetBit(1); } + { const a: number = new BitSet(10).previousSetBit(1); } + { const a: number = new BitSet(10).previousUnsetBit(1); } + { const a: number = new BitSet(10).readUInt(); } + { const a: number = new BitSet(10).readUInt(1); } + { const a: number = new BitSet(10).readUInt(1, 2); } + { new BitSet(10).writeUInt(1); } + { new BitSet(10).writeUInt(1, 2); } + { new BitSet(10).writeUInt(1, 2, 3); } + { const a: BitSet = BitSet.fromLong(new adone.math.Long(10, 20)); } + } + + namespace randomTests { + const { random } = math; + random(); + random(100); + random(0, 10); + } +} diff --git a/types/adone/test/glosses/math/matrix.ts b/types/adone/test/glosses/math/matrix.ts new file mode 100644 index 0000000000..81d2f28da9 --- /dev/null +++ b/types/adone/test/glosses/math/matrix.ts @@ -0,0 +1,368 @@ +namespace mathTests.matrixTests { + const { + vec2, vec3, vec4, + mat2, mat2d, mat3, mat4, + quat + } = adone.math.matrix; + type mat2 = adone.math.matrix.I.mat2; + type mat2d = adone.math.matrix.I.mat2d; + type mat3 = adone.math.matrix.I.mat3; + type mat4 = adone.math.matrix.I.mat4; + + let outVal: number; + let outBool: boolean; + let outStr: string; + + let vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + + const vec2A = vec2.fromValues(1, 2); + const vec2B = vec2.fromValues(3, 4); + const vec3A = vec3.fromValues(1, 2, 3); + const vec3B = vec3.fromValues(3, 4, 5); + const vec4A = vec4.fromValues(1, 2, 3, 4); + const vec4B = vec4.fromValues(3, 4, 5, 6); + const mat2A = mat2.fromValues(1, 2, 3, 4); + const mat2B = mat2.fromValues(1, 2, 3, 4); + const mat2dA = mat2d.fromValues(1, 2, 3, 4, 5, 6); + const mat2dB = mat2d.fromValues(1, 2, 3, 4, 5, 6); + const mat3A = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); + const mat3B = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); + const mat4A = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + const mat4B = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + const quatA = quat.fromValues(1, 2, 3, 4); + const quatB = quat.fromValues(5, 6, 7, 8); + + let outVec2 = vec2.create(); + let outVec3 = vec3.create(); + let outVec4 = vec4.create(); + let outMat2 = mat2.create(); + let outMat2d = mat2d.create(); + let outMat3 = mat3.create(); + let outMat4 = mat4.create(); + let outQuat = quat.create(); + + let outMat2Null: mat2 | null; + let outMat2dNull: mat2d | null; + let outMat3Null: mat3 | null; + let outMat4Null: mat4 | null; + + { + outVec2 = vec2.create(); + outVec2 = vec2.clone(vec2A); + outVec2 = vec2.fromValues(1, 2); + outVec2 = vec2.copy(outVec2, vec2A); + outVec2 = vec2.set(outVec2, 1, 2); + outVec2 = vec2.add(outVec2, vec2A, vec2B); + outVec2 = vec2.subtract(outVec2, vec2A, vec2B); + outVec2 = vec2.sub(outVec2, vec2A, vec2B); + outVec2 = vec2.multiply(outVec2, vec2A, vec2B); + outVec2 = vec2.mul(outVec2, vec2A, vec2B); + outVec2 = vec2.divide(outVec2, vec2A, vec2B); + outVec2 = vec2.div(outVec2, vec2A, vec2B); + outVec2 = vec2.ceil(outVec2, vec2A); + outVec2 = vec2.floor(outVec2, vec2A); + outVec2 = vec2.min(outVec2, vec2A, vec2B); + outVec2 = vec2.max(outVec2, vec2A, vec2B); + outVec2 = vec2.round(outVec2, vec2A); + outVec2 = vec2.scale(outVec2, vec2A, 2); + outVec2 = vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5); + outVal = vec2.distance(vec2A, vec2B); + outVal = vec2.dist(vec2A, vec2B); + outVal = vec2.squaredDistance(vec2A, vec2B); + outVal = vec2.sqrDist(vec2A, vec2B); + outVal = vec2.length(vec2A); + outVal = vec2.len(vec2A); + outVal = vec2.squaredLength(vec2A); + outVal = vec2.sqrLen(vec2A); + outVec2 = vec2.negate(outVec2, vec2A); + outVec2 = vec2.inverse(outVec2, vec2A); + outVec2 = vec2.normalize(outVec2, vec2A); + outVal = vec2.dot(vec2A, vec2B); + outVec2 = vec2.cross(outVec2, vec2A, vec2B); + outVec2 = vec2.lerp(outVec2, vec2A, vec2B, 0.5); + outVec2 = vec2.random(outVec2); + outVec2 = vec2.random(outVec2, 5.0); + outVec2 = vec2.transformMat2(outVec2, vec2A, mat2A); + outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA); + outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A); + outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A); + vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); + outStr = vec2.str(vec2A); + outBool = vec2.exactEquals(vec2A, vec2B); + outBool = vec2.equals(vec2A, vec2B); + outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input + } + + { + outVec3 = vec3.create(); + outVec3 = vec3.clone(vec3A); + outVec3 = vec3.fromValues(1, 2, 3); + outVec3 = vec3.copy(outVec3, vec3A); + outVec3 = vec3.set(outVec3, 1, 2, 3); + outVec3 = vec3.add(outVec3, vec3A, vec3B); + outVec3 = vec3.subtract(outVec3, vec3A, vec3B); + outVec3 = vec3.sub(outVec3, vec3A, vec3B); + outVec3 = vec3.multiply(outVec3, vec3A, vec3B); + outVec3 = vec3.mul(outVec3, vec3A, vec3B); + outVec3 = vec3.divide(outVec3, vec3A, vec3B); + outVec3 = vec3.div(outVec3, vec3A, vec3B); + outVec3 = vec3.ceil(outVec3, vec3A); + outVec3 = vec3.floor(outVec3, vec3A); + outVec3 = vec3.min(outVec3, vec3A, vec3B); + outVec3 = vec3.max(outVec3, vec3A, vec3B); + outVec3 = vec3.round(outVec3, vec3A); + outVec3 = vec3.scale(outVec3, vec3A, 2); + outVec3 = vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5); + outVal = vec3.distance(vec3A, vec3B); + outVal = vec3.dist(vec3A, vec3B); + outVal = vec3.squaredDistance(vec3A, vec3B); + outVal = vec3.sqrDist(vec3A, vec3B); + outVal = vec3.length(vec3A); + outVal = vec3.len(vec3A); + outVal = vec3.squaredLength(vec3A); + outVal = vec3.sqrLen(vec3A); + outVec3 = vec3.negate(outVec3, vec3A); + outVec3 = vec3.inverse(outVec3, vec3A); + outVec3 = vec3.normalize(outVec3, vec3A); + outVal = vec3.dot(vec3A, vec3B); + outVec3 = vec3.cross(outVec3, vec3A, vec3B); + outVec3 = vec3.lerp(outVec3, vec3A, vec3B, 0.5); + outVec3 = vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); + outVec3 = vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); + outVec3 = vec3.random(outVec3); + outVec3 = vec3.random(outVec3, 5.0); + outVec3 = vec3.transformMat3(outVec3, vec3A, mat3A); + outVec3 = vec3.transformMat4(outVec3, vec3A, mat4A); + outVec3 = vec3.transformQuat(outVec3, vec3A, quatA); + outVec3 = vec3.rotateX(outVec3, vec3A, vec3B, Math.PI); + outVec3 = vec3.rotateY(outVec3, vec3A, vec3B, Math.PI); + outVec3 = vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI); + vecArray = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); + outVal = vec3.angle(vec3A, vec3B); + outStr = vec3.str(vec3A); + outBool = vec3.exactEquals(vec3A, vec3B); + outBool = vec3.equals(vec3A, vec3B); + outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input + } + + { + outVec4 = vec4.create(); + outVec4 = vec4.clone(vec4A); + outVec4 = vec4.fromValues(1, 2, 3, 4); + outVec4 = vec4.copy(outVec4, vec4A); + outVec4 = vec4.set(outVec4, 1, 2, 3, 4); + outVec4 = vec4.add(outVec4, vec4A, vec4B); + outVec4 = vec4.subtract(outVec4, vec4A, vec4B); + outVec4 = vec4.sub(outVec4, vec4A, vec4B); + outVec4 = vec4.multiply(outVec4, vec4A, vec4B); + outVec4 = vec4.mul(outVec4, vec4A, vec4B); + outVec4 = vec4.divide(outVec4, vec4A, vec4B); + outVec4 = vec4.div(outVec4, vec4A, vec4B); + outVec4 = vec4.ceil(outVec4, vec4A); + outVec4 = vec4.floor(outVec4, vec4A); + outVec4 = vec4.min(outVec4, vec4A, vec4B); + outVec4 = vec4.max(outVec4, vec4A, vec4B); + outVec4 = vec4.scale(outVec4, vec4A, 2); + outVec4 = vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5); + outVal = vec4.distance(vec4A, vec4B); + outVal = vec4.dist(vec4A, vec4B); + outVal = vec4.squaredDistance(vec4A, vec4B); + outVal = vec4.sqrDist(vec4A, vec4B); + outVal = vec4.length(vec4A); + outVal = vec4.len(vec4A); + outVal = vec4.squaredLength(vec4A); + outVal = vec4.sqrLen(vec4A); + outVec4 = vec4.negate(outVec4, vec4A); + outVec4 = vec4.inverse(outVec4, vec4A); + outVec4 = vec4.normalize(outVec4, vec4A); + outVal = vec4.dot(vec4A, vec4B); + outVec4 = vec4.lerp(outVec4, vec4A, vec4B, 0.5); + outVec4 = vec4.random(outVec4); + outVec4 = vec4.random(outVec4, 5.0); + outVec4 = vec4.transformMat4(outVec4, vec4A, mat4A); + outVec4 = vec4.transformQuat(outVec4, vec4A, quatA); + vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); + outStr = vec4.str(vec4A); + outBool = vec4.exactEquals(vec4A, vec4B); + outBool = vec4.equals(vec4A, vec4B); + outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input + } + + { + outMat2 = mat2.create(); + outMat2 = mat2.clone(mat2A); + outMat2 = mat2.copy(outMat2, mat2A); + outMat2 = mat2.identity(outMat2); + outMat2 = mat2.fromValues(1, 2, 3, 4); + outMat2 = mat2.set(outMat2, 1, 2, 3, 4); + outMat2 = mat2.transpose(outMat2, mat2A); + outMat2Null = mat2.invert(outMat2, mat2A); + outMat2 = mat2.adjoint(outMat2, mat2A); + outVal = mat2.determinant(mat2A); + outMat2 = mat2.multiply(outMat2, mat2A, mat2B); + outMat2 = mat2.mul(outMat2, mat2A, mat2B); + outMat2 = mat2.rotate(outMat2, mat2A, Math.PI * 0.5); + outMat2 = mat2.scale(outMat2, mat2A, vec2A); + outMat2 = mat2.fromRotation(outMat2, 0.5); + outMat2 = mat2.fromScaling(outMat2, vec2A); + outStr = mat2.str(mat2A); + outVal = mat2.frob(mat2A); + const L = mat2.create(); + const D = mat2.create(); + const U = mat2.create(); + outMat2 = mat2.LDU(L, D, U, mat2A); + outMat2 = mat2.add(outMat2, mat2A, mat2B); + outMat2 = mat2.subtract(outMat2, mat2A, mat2B); + outMat2 = mat2.sub(outMat2, mat2A, mat2B); + outBool = mat2.exactEquals(mat2A, mat2B); + outBool = mat2.equals(mat2A, mat2B); + outMat2 = mat2.multiplyScalar(outMat2, mat2A, 2); + outMat2 = mat2.multiplyScalarAndAdd(outMat2, mat2A, mat2B, 2); + } + + { + outMat2d = mat2d.create(); + outMat2d = mat2d.clone(mat2dA); + outMat2d = mat2d.copy(outMat2d, mat2dA); + outMat2d = mat2d.identity(outMat2d); + outMat2d = mat2d.fromValues(1, 2, 3, 4, 5, 6); + outMat2d = mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); + outMat2dNull = mat2d.invert(outMat2d, mat2dA); + outVal = mat2d.determinant(mat2dA); + outMat2d = mat2d.multiply(outMat2d, mat2dA, mat2dB); + outMat2d = mat2d.mul(outMat2d, mat2dA, mat2dB); + outMat2d = mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5); + outMat2d = mat2d.scale(outMat2d, mat2dA, vec2A); + outMat2d = mat2d.translate(outMat2d, mat2dA, vec2A); + outMat2d = mat2d.fromRotation(outMat2d, 0.5); + outMat2d = mat2d.fromScaling(outMat2d, vec2A); + outMat2d = mat2d.fromTranslation(outMat2d, vec2A); + outStr = mat2d.str(mat2dA); + outVal = mat2d.frob(mat2dA); + outMat2d = mat2d.add(outMat2d, mat2dA, mat2dB); + outMat2d = mat2d.subtract(outMat2d, mat2dA, mat2dB); + outMat2d = mat2d.sub(outMat2d, mat2dA, mat2dB); + outMat2d = mat2d.multiplyScalar(outMat2d, mat2dA, 2); + outMat2d = mat2d.multiplyScalarAndAdd(outMat2d, mat2dA, mat2dB, 2); + outBool = mat2d.exactEquals(mat2dA, mat2dB); + outBool = mat2d.equals(mat2dA, mat2dB); + } + + { + outMat3 = mat3.create(); + outMat3 = mat3.fromMat4(outMat3, mat4A); + outMat3 = mat3.clone(mat3A); + outMat3 = mat3.copy(outMat3, mat3A); + outMat3 = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); + outMat3 = mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); + outMat3 = mat3.identity(outMat3); + outMat3 = mat3.transpose(outMat3, mat3A); + outMat3Null = mat3.invert(outMat3, mat3A); + outMat3 = mat3.adjoint(outMat3, mat3A); + outVal = mat3.determinant(mat3A); + outMat3 = mat3.multiply(outMat3, mat3A, mat3B); + outMat3 = mat3.mul(outMat3, mat3A, mat3B); + outMat3 = mat3.translate(outMat3, mat3A, vec3A); + outMat3 = mat3.rotate(outMat3, mat3A, Math.PI / 2); + outMat3 = mat3.scale(outMat3, mat3A, vec2A); + outMat3 = mat3.fromTranslation(outMat3, vec2A); + outMat3 = mat3.fromRotation(outMat3, Math.PI); + outMat3 = mat3.fromScaling(outMat3, vec2A); + outMat3 = mat3.fromMat2d(outMat3, mat2dA); + outMat3 = mat3.fromQuat(outMat3, quatA); + outMat3Null = mat3.normalFromMat4(outMat3, mat4A); + outStr = mat3.str(mat3A); + outVal = mat3.frob(mat3A); + outMat3 = mat3.add(outMat3, mat3A, mat3B); + outMat3 = mat3.subtract(outMat3, mat3A, mat3B); + outMat3 = mat3.sub(outMat3, mat3A, mat3B); + outMat3 = mat3.multiplyScalar(outMat3, mat3A, 2); + outMat3 = mat3.multiplyScalarAndAdd(outMat3, mat3A, mat3B, 2); + outBool = mat3.exactEquals(mat3A, mat3B); + outBool = mat3.equals(mat3A, mat3B); + } + + { + outMat4 = mat4.create(); + outMat4 = mat4.clone(mat4A); + outMat4 = mat4.copy(outMat4, mat4A); + outMat4 = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + outMat4 = mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + outMat4 = mat4.identity(outMat4); + outMat4 = mat4.transpose(outMat4, mat4A); + outMat4Null = mat4.invert(outMat4, mat4A); + outMat4 = mat4.adjoint(outMat4, mat4A); + outVal = mat4.determinant(mat4A); + outMat4 = mat4.multiply(outMat4, mat4A, mat4B); + outMat4 = mat4.mul(outMat4, mat4A, mat4B); + outMat4 = mat4.translate(outMat4, mat4A, vec3A); + outMat4 = mat4.scale(outMat4, mat4A, vec3A); + outMat4Null = mat4.rotate(outMat4, mat4A, Math.PI, vec3A); + outMat4 = mat4.rotateX(outMat4, mat4A, Math.PI); + outMat4 = mat4.rotateY(outMat4, mat4A, Math.PI); + outMat4 = mat4.rotateZ(outMat4, mat4A, Math.PI); + outMat4 = mat4.fromTranslation(outMat4, vec3A); + outMat4Null = mat4.fromRotation(outMat4, Math.PI, vec3A); + outMat4 = mat4.fromScaling(outMat4, vec3A); + outMat4 = mat4.fromXRotation(outMat4, Math.PI); + outMat4 = mat4.fromYRotation(outMat4, Math.PI); + outMat4 = mat4.fromZRotation(outMat4, Math.PI); + outMat4 = mat4.fromRotationTranslation(outMat4, quatA, vec3A); + outVec3 = mat4.getTranslation(outVec3, mat4A); + outVec3 = mat4.getScaling(outVec3, mat4A); + outQuat = mat4.getRotation(outQuat, mat4A); + outMat4 = mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); + outMat4 = mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); + outMat4 = mat4.fromQuat(outMat4, quatB); + outMat4 = mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1); + outMat4 = mat4.perspective(outMat4, Math.PI, 1, 0, 1); + outMat4 = mat4.perspectiveFromFieldOfView(outMat4, { upDegrees: Math.PI, downDegrees: -Math.PI, leftDegrees: -Math.PI, rightDegrees: Math.PI }, 1, 0); + outMat4 = mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); + outMat4 = mat4.lookAt(outMat4, vec3A, vec3B, vec3A); + outStr = mat4.str(mat4A); + outVal = mat4.frob(mat4A); + outMat4 = mat4.add(outMat4, mat4A, mat4B); + outMat4 = mat4.subtract(outMat4, mat4A, mat4B); + outMat4 = mat4.sub(outMat4, mat4A, mat4B); + outMat4 = mat4.multiplyScalar(outMat4, mat4A, 2); + outMat4 = mat4.multiplyScalarAndAdd(outMat4, mat4A, mat4B, 2); + outBool = mat4.exactEquals(mat4A, mat4B); + outBool = mat4.equals(mat4A, mat4B); + } + + { + const deg90 = Math.PI / 2; + outQuat = quat.create(); + outQuat = quat.clone(quatA); + outQuat = quat.fromValues(1, 2, 3, 4); + outQuat = quat.copy(outQuat, quatA); + outQuat = quat.set(outQuat, 1, 2, 3, 4); + outQuat = quat.identity(outQuat); + outQuat = quat.rotationTo(outQuat, vec3A, vec3B); + outQuat = quat.setAxes(outQuat, vec3A, vec3B, vec3A); + outQuat = quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5); + outVal = quat.getAxisAngle(outVec3, quatA); + outQuat = quat.add(outQuat, quatA, quatB); + outQuat = quat.multiply(outQuat, quatA, quatB); + outQuat = quat.mul(outQuat, quatA, quatB); + outQuat = quat.scale(outQuat, quatA, 2); + outVal = quat.length(quatA); + outVal = quat.len(quatA); + outVal = quat.squaredLength(quatA); + outVal = quat.sqrLen(quatA); + outQuat = quat.normalize(outQuat, quatA); + outVal = quat.dot(quatA, quatB); + outQuat = quat.lerp(outQuat, quatA, quatB, 0.5); + outQuat = quat.slerp(outQuat, quatA, quatB, 0.5); + outQuat = quat.invert(outQuat, quatA); + outQuat = quat.conjugate(outQuat, quatA); + outStr = quat.str(quatA); + outQuat = quat.rotateX(outQuat, quatA, deg90); + outQuat = quat.rotateY(outQuat, quatA, deg90); + outQuat = quat.rotateZ(outQuat, quatA, deg90); + outQuat = quat.fromMat3(outQuat, mat3A); + outQuat = quat.calculateW(outQuat, quatA); + outBool = quat.exactEquals(quatA, quatB); + outBool = quat.equals(quatA, quatB); + } +} diff --git a/types/adone/test/glosses/math/simd.ts b/types/adone/test/glosses/math/simd.ts new file mode 100644 index 0000000000..59a6cf03ac --- /dev/null +++ b/types/adone/test/glosses/math/simd.ts @@ -0,0 +1,359 @@ +namespace mathTests.simdTests { + const { + Float32x4, + Int32x4, + Int16x8, + Int8x16, + Uint32x4, + Uint16x8, + Uint8x16, + Bool32x4, + Bool16x8, + Bool8x16 + } = adone.math.simd; + + const a0 = Float32x4(0, 1, 2, 3); + const a1 = Int32x4(0, 1, 2, 3); + const a2 = Int16x8(0, 1, 2, 3, 4, 5, 6, 7); + const a3 = Int8x16(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + const a4 = Uint32x4(0, 1, 2, 3); + const a5 = Uint16x8(0, 1, 2, 3, 4, 5, 6, 7); + const a6 = Uint8x16(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + const a7 = Bool32x4(true, true, true, true); + const a8 = Bool16x8(true, true, true, true, true, true, true, true); + const a9 = Bool8x16(true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true); + + Float32x4.length; + Float32x4.name; + Float32x4.arguments; + Float32x4.caller; + Float32x4.prototype; + Float32x4.extractLane(a0, 3); + Float32x4.swizzle(a0, 0, 1, 2, 3); + Float32x4.shuffle(a0, a0, 0, 1, 2, 3); + Float32x4.check(a0); + Float32x4.splat(1); + Float32x4.replaceLane(a0, 3, 1); + Float32x4.select(Bool32x4.splat(true), a0, a0); + Float32x4.equal(a0, a0); + Float32x4.notEqual(a0, a0); + Float32x4.lessThan(a0, a0); + Float32x4.lessThanOrEqual(a0, a0); + Float32x4.greaterThan(a0, a0); + Float32x4.greaterThanOrEqual(a0, a0); + Float32x4.add(a0, a0); + Float32x4.sub(a0, a0); + Float32x4.mul(a0, a0); + Float32x4.div(a0, a0); + Float32x4.neg(a0); + Float32x4.abs(a0); + Float32x4.min(a0, a0); + Float32x4.max(a0, a0); + Float32x4.minNum(a0, a0); + Float32x4.maxNum(a0, a0); + Float32x4.reciprocalApproximation(a0, a0); + Float32x4.reciprocalSqrtApproximation(a0); + Float32x4.sqrt(a0); + Float32x4.load(new Float32Array(16), 0); + Float32x4.load1(new Float32Array(16), 0); + Float32x4.load2(new Float32Array(16), 0); + Float32x4.load3(new Float32Array(16), 0); + Float32x4.store(new Float32Array(16), 1, a0); + Float32x4.store1(new Float32Array(16), 1, a0); + Float32x4.store2(new Float32Array(16), 1, a0); + Float32x4.store3(new Float32Array(16), 1, a0); + Float32x4.fromInt32x4(Int32x4.splat(0)); + Float32x4.fromUint32x4(Uint32x4.splat(0)); + Float32x4.fromInt32x4Bits(Int32x4.splat(0)); + Float32x4.fromInt16x8Bits(Int16x8.splat(0)); + Float32x4.fromInt8x16Bits(Int8x16.splat(0)); + Float32x4.fromUint32x4Bits(Uint32x4.splat(0)); + Float32x4.fromUint16x8Bits(Uint16x8.splat(0)); + Float32x4.fromUint8x16Bits(Uint8x16.splat(0)); + Int32x4.length; + Int32x4.name; + Int32x4.arguments; + Int32x4.caller; + Int32x4.prototype; + Int32x4.extractLane(a1, 3); + Int32x4.swizzle(a1, 0, 1, 2, 3); + Int32x4.shuffle(a1, a1, 0, 1, 2, 3); + Int32x4.check(a1); + Int32x4.splat(1); + Int32x4.replaceLane(a1, 3, 1); + Int32x4.select(Bool32x4.splat(true), a1, a1); + Int32x4.equal(a1, a1); + Int32x4.notEqual(a1, a1); + Int32x4.lessThan(a1, a1); + Int32x4.lessThanOrEqual(a1, a1); + Int32x4.greaterThan(a1, a1); + Int32x4.greaterThanOrEqual(a1, a1); + Int32x4.and(a1, a1); + Int32x4.or(a1, a1); + Int32x4.xor(a1, a1); + Int32x4.not(a1, a1); + Int32x4.add(a1, a1); + Int32x4.sub(a1, a1); + Int32x4.mul(a1, a1); + Int32x4.neg(a1); + Int32x4.shiftLeftByScalar(a1, 1); + Int32x4.shiftRightByScalar(a1, 1); + Int32x4.load(new Int32Array(16), 0); + Int32x4.load1(new Int32Array(16), 0); + Int32x4.load2(new Int32Array(16), 0); + Int32x4.load3(new Int32Array(16), 0); + Int32x4.store(new Int32Array(16), 1, a1); + Int32x4.store1(new Int32Array(16), 1, a1); + Int32x4.store2(new Int32Array(16), 1, a1); + Int32x4.store3(new Int32Array(16), 1, a1); + Int32x4.fromFloat32x4(Float32x4.splat(0)); + Int32x4.fromUint32x4(Uint32x4.splat(0)); + Int32x4.fromFloat32x4Bits(Float32x4.splat(0)); + Int32x4.fromInt16x8Bits(Int16x8.splat(0)); + Int32x4.fromInt8x16Bits(Int8x16.splat(0)); + Int32x4.fromUint32x4Bits(Uint32x4.splat(0)); + Int32x4.fromUint16x8Bits(Uint16x8.splat(0)); + Int32x4.fromUint8x16Bits(Uint8x16.splat(0)); + Int16x8.length; + Int16x8.name; + Int16x8.arguments; + Int16x8.caller; + Int16x8.prototype; + Int16x8.extractLane(a2, 7); + Int16x8.swizzle(a2, 0, 1, 2, 3, 4, 5, 6, 7); + Int16x8.shuffle(a2, a2, 0, 1, 2, 3, 4, 5, 6, 7); + Int16x8.check(a2); + Int16x8.splat(1); + Int16x8.replaceLane(a2, 7, 1); + Int16x8.select(Bool16x8.splat(true), a2, a2); + Int16x8.equal(a2, a2); + Int16x8.notEqual(a2, a2); + Int16x8.lessThan(a2, a2); + Int16x8.lessThanOrEqual(a2, a2); + Int16x8.greaterThan(a2, a2); + Int16x8.greaterThanOrEqual(a2, a2); + Int16x8.and(a2, a2); + Int16x8.or(a2, a2); + Int16x8.xor(a2, a2); + Int16x8.not(a2, a2); + Int16x8.add(a2, a2); + Int16x8.sub(a2, a2); + Int16x8.mul(a2, a2); + Int16x8.neg(a2); + Int16x8.shiftLeftByScalar(a2, 1); + Int16x8.shiftRightByScalar(a2, 1); + Int16x8.addSaturate(a2, a2); + Int16x8.subSaturate(a2, a2); + Int16x8.load(new Int16Array(16), 0); + Int16x8.store(new Int16Array(16), 1, a2); + Int16x8.fromUint16x8(Uint16x8.splat(0)); + Int16x8.fromFloat32x4Bits(Float32x4.splat(0)); + Int16x8.fromInt32x4Bits(Int32x4.splat(0)); + Int16x8.fromInt8x16Bits(Int8x16.splat(0)); + Int16x8.fromUint32x4Bits(Uint32x4.splat(0)); + Int16x8.fromUint16x8Bits(Uint16x8.splat(0)); + Int16x8.fromUint8x16Bits(Uint8x16.splat(0)); + Int8x16.length; + Int8x16.name; + Int8x16.arguments; + Int8x16.caller; + Int8x16.prototype; + Int8x16.extractLane(a3, 15); + Int8x16.swizzle(a3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + Int8x16.shuffle(a3, a3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + Int8x16.check(a3); + Int8x16.splat(1); + Int8x16.replaceLane(a3, 15, 1); + Int8x16.select(Bool8x16.splat(true), a3, a3); + Int8x16.equal(a3, a3); + Int8x16.notEqual(a3, a3); + Int8x16.lessThan(a3, a3); + Int8x16.lessThanOrEqual(a3, a3); + Int8x16.greaterThan(a3, a3); + Int8x16.greaterThanOrEqual(a3, a3); + Int8x16.and(a3, a3); + Int8x16.or(a3, a3); + Int8x16.xor(a3, a3); + Int8x16.not(a3, a3); + Int8x16.add(a3, a3); + Int8x16.sub(a3, a3); + Int8x16.mul(a3, a3); + Int8x16.neg(a3); + Int8x16.shiftLeftByScalar(a3, 1); + Int8x16.shiftRightByScalar(a3, 1); + Int8x16.addSaturate(a3, a3); + Int8x16.subSaturate(a3, a3); + Int8x16.load(new Int8Array(16), 0); + Int8x16.store(new Int8Array(16), 1, a3); + Int8x16.fromUint8x16(Uint8x16.splat(0)); + Int8x16.fromFloat32x4Bits(Float32x4.splat(0)); + Int8x16.fromInt32x4Bits(Int32x4.splat(0)); + Int8x16.fromInt16x8Bits(Int16x8.splat(0)); + Int8x16.fromUint32x4Bits(Uint32x4.splat(0)); + Int8x16.fromUint16x8Bits(Uint16x8.splat(0)); + Int8x16.fromUint8x16Bits(Uint8x16.splat(0)); + Uint32x4.length; + Uint32x4.name; + Uint32x4.arguments; + Uint32x4.caller; + Uint32x4.prototype; + Uint32x4.extractLane(a4, 3); + Uint32x4.swizzle(a4, 0, 1, 2, 3); + Uint32x4.shuffle(a4, a4, 0, 1, 2, 3); + Uint32x4.check(a4); + Uint32x4.splat(1); + Uint32x4.replaceLane(a4, 3, 1); + Uint32x4.select(Bool32x4.splat(true), a4, a4); + Uint32x4.equal(a4, a4); + Uint32x4.notEqual(a4, a4); + Uint32x4.lessThan(a4, a4); + Uint32x4.lessThanOrEqual(a4, a4); + Uint32x4.greaterThan(a4, a4); + Uint32x4.greaterThanOrEqual(a4, a4); + Uint32x4.and(a4, a4); + Uint32x4.or(a4, a4); + Uint32x4.xor(a4, a4); + Uint32x4.not(a4, a4); + Uint32x4.add(a4, a4); + Uint32x4.sub(a4, a4); + Uint32x4.mul(a4, a4); + Uint32x4.shiftLeftByScalar(a4, 1); + Uint32x4.shiftRightByScalar(a4, 1); + Uint32x4.load(new Uint32Array(16), 0); + Uint32x4.load1(new Uint32Array(16), 0); + Uint32x4.load2(new Uint32Array(16), 0); + Uint32x4.load3(new Uint32Array(16), 0); + Uint32x4.store(new Uint32Array(16), 1, a4); + Uint32x4.store1(new Uint32Array(16), 1, a4); + Uint32x4.store2(new Uint32Array(16), 1, a4); + Uint32x4.store3(new Uint32Array(16), 1, a4); + Uint32x4.fromFloat32x4(Float32x4.splat(0)); + Uint32x4.fromInt32x4(Int32x4.splat(0)); + Uint32x4.fromFloat32x4Bits(Float32x4.splat(0)); + Uint32x4.fromInt32x4Bits(Int32x4.splat(0)); + Uint32x4.fromInt16x8Bits(Int16x8.splat(0)); + Uint32x4.fromInt8x16Bits(Int8x16.splat(0)); + Uint32x4.fromUint16x8Bits(Uint16x8.splat(0)); + Uint32x4.fromUint8x16Bits(Uint8x16.splat(0)); + Uint16x8.length; + Uint16x8.name; + Uint16x8.arguments; + Uint16x8.caller; + Uint16x8.prototype; + Uint16x8.extractLane(a5, 7); + Uint16x8.swizzle(a5, 0, 1, 2, 3, 4, 5, 6, 7); + Uint16x8.shuffle(a5, a5, 0, 1, 2, 3, 4, 5, 6, 7); + Uint16x8.check(a5); + Uint16x8.splat(1); + Uint16x8.replaceLane(a5, 7, 1); + Uint16x8.select(Bool16x8.splat(true), a5, a5); + Uint16x8.equal(a5, a5); + Uint16x8.notEqual(a5, a5); + Uint16x8.lessThan(a5, a5); + Uint16x8.lessThanOrEqual(a5, a5); + Uint16x8.greaterThan(a5, a5); + Uint16x8.greaterThanOrEqual(a5, a5); + Uint16x8.and(a5, a5); + Uint16x8.or(a5, a5); + Uint16x8.xor(a5, a5); + Uint16x8.not(a5, a5); + Uint16x8.add(a5, a5); + Uint16x8.sub(a5, a5); + Uint16x8.mul(a5, a5); + Uint16x8.shiftLeftByScalar(a5, 1); + Uint16x8.shiftRightByScalar(a5, 1); + Uint16x8.addSaturate(a5, a5); + Uint16x8.subSaturate(a5, a5); + Uint16x8.load(new Uint16Array(16), 0); + Uint16x8.store(new Uint16Array(16), 1, a5); + Uint16x8.fromInt16x8(Int16x8.splat(0)); + Uint16x8.fromFloat32x4Bits(Float32x4.splat(0)); + Uint16x8.fromInt32x4Bits(Int32x4.splat(0)); + Uint16x8.fromInt16x8Bits(Int16x8.splat(0)); + Uint16x8.fromInt8x16Bits(Int8x16.splat(0)); + Uint16x8.fromUint32x4Bits(Uint32x4.splat(0)); + Uint16x8.fromUint8x16Bits(Uint8x16.splat(0)); + Uint8x16.length; + Uint8x16.name; + Uint8x16.arguments; + Uint8x16.caller; + Uint8x16.prototype; + Uint8x16.extractLane(a6, 15); + Uint8x16.swizzle(a6, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + Uint8x16.shuffle(a6, a6, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + Uint8x16.check(a6); + Uint8x16.splat(1); + Uint8x16.replaceLane(a6, 15, 1); + Uint8x16.select(Bool8x16.splat(true), a6, a6); + Uint8x16.equal(a6, a6); + Uint8x16.notEqual(a6, a6); + Uint8x16.lessThan(a6, a6); + Uint8x16.lessThanOrEqual(a6, a6); + Uint8x16.greaterThan(a6, a6); + Uint8x16.greaterThanOrEqual(a6, a6); + Uint8x16.and(a6, a6); + Uint8x16.or(a6, a6); + Uint8x16.xor(a6, a6); + Uint8x16.not(a6, a6); + Uint8x16.add(a6, a6); + Uint8x16.sub(a6, a6); + Uint8x16.mul(a6, a6); + Uint8x16.shiftLeftByScalar(a6, 1); + Uint8x16.shiftRightByScalar(a6, 1); + Uint8x16.addSaturate(a6, a6); + Uint8x16.subSaturate(a6, a6); + Uint8x16.load(new Uint8Array(16), 0); + Uint8x16.store(new Uint8Array(16), 1, a6); + Uint8x16.fromInt8x16(Int8x16.splat(0)); + Uint8x16.fromFloat32x4Bits(Float32x4.splat(0)); + Uint8x16.fromInt32x4Bits(Int32x4.splat(0)); + Uint8x16.fromInt16x8Bits(Int16x8.splat(0)); + Uint8x16.fromInt8x16Bits(Int8x16.splat(0)); + Uint8x16.fromUint32x4Bits(Uint32x4.splat(0)); + Uint8x16.fromUint16x8Bits(Uint16x8.splat(0)); + Bool32x4.length; + Bool32x4.name; + Bool32x4.arguments; + Bool32x4.caller; + Bool32x4.prototype; + Bool32x4.extractLane(a7, 3); + Bool32x4.check(a7); + Bool32x4.splat(true); + Bool32x4.replaceLane(a7, 3, true); + Bool32x4.allTrue(a7); + Bool32x4.anyTrue(a7); + Bool32x4.and(a7, a7); + Bool32x4.or(a7, a7); + Bool32x4.xor(a7, a7); + Bool32x4.not(a7, a7); + Bool16x8.length; + Bool16x8.name; + Bool16x8.arguments; + Bool16x8.caller; + Bool16x8.prototype; + Bool16x8.extractLane(a8, 7); + Bool16x8.check(a8); + Bool16x8.splat(true); + Bool16x8.replaceLane(a8, 7, true); + Bool16x8.allTrue(a8); + Bool16x8.anyTrue(a8); + Bool16x8.and(a8, a8); + Bool16x8.or(a8, a8); + Bool16x8.xor(a8, a8); + Bool16x8.not(a8, a8); + Bool8x16.length; + Bool8x16.name; + Bool8x16.arguments; + Bool8x16.caller; + Bool8x16.prototype; + Bool8x16.extractLane(a9, 15); + Bool8x16.check(a9); + Bool8x16.splat(true); + Bool8x16.replaceLane(a9, 15, true); + Bool8x16.allTrue(a9); + Bool8x16.anyTrue(a9); + Bool8x16.and(a9, a9); + Bool8x16.or(a9, a9); + Bool8x16.xor(a9, a9); + Bool8x16.not(a9, a9); +} diff --git a/types/adone/test/glosses/promise.ts b/types/adone/test/glosses/promise.ts index c16d1a4852..a8866d95a1 100644 --- a/types/adone/test/glosses/promise.ts +++ b/types/adone/test/glosses/promise.ts @@ -6,7 +6,7 @@ namespace promiseTests { a.promise.then((x) => 2); a.resolve(2); a.reject(3); - const b = promise.defer(); + const b = promise.defer(); b.resolve("3"); b.reject(2); b.promise.then((x: string) => x); @@ -27,6 +27,18 @@ namespace promiseTests { promise.nodeify(Promise.resolve(2), () => 42).then((x: number) => x); } + namespace callbackifyTests { + const { callbackify } = promise; + + callbackify(async () => {})((err: any, a: undefined) => {}).then((x: undefined) => {}); + callbackify(async () => 42)((err: any, a: number) => {}).then((x: number) => {}); + callbackify(async (a: number) => a)(123, (err: any, a: number) => {}).then((x: number) => {}); + callbackify(async (a: number, b: string) => b)(123, "456", (err: any, a: string) => {}).then((x: string) => {}); + callbackify(async (a: number, b: string, c: number) => c)(123, "456", 123, (err: any, a: number) => {}).then((x: number) => {}); + callbackify(async (a: number, b: string, c: number, d: string) => d)(123, "456", 123, "456", (err: any, a: string) => {}).then((x: string) => {}); + callbackify(async (a: number, b: string, c: number, d: string, e: number) => e)(123, "456", 123, "456", 123, (err: any, a: number) => {}).then((x: number) => {}); + } + namespace promisify { type Callback = (err?: any, result?: T) => void; namespace noargs { diff --git a/types/adone/test/glosses/shani.ts b/types/adone/test/glosses/shani.ts index 1c09ef3837..3bbe861633 100644 --- a/types/adone/test/glosses/shani.ts +++ b/types/adone/test/glosses/shani.ts @@ -177,7 +177,7 @@ namespace shaniTests { const check = (hook: adone.shani.I.Hook) => { hook.run().then((x) => x); hook.cause(); - hook.failed() === true; + { const a: boolean = hook.failed(); } hook.timeout() + 2; hook.timeout(10).timeout(10).timeout() + 2; }; @@ -193,9 +193,9 @@ namespace shaniTests { for (const hook of root.afterEachHooks()) { check(hook); } - root.isInclusive() === true; - root.isExclusive() === false; - root.hasInclusive() === true; + { const a: boolean = root.isInclusive(); } + { const a: boolean = root.isExclusive(); } + { const a: boolean = root.hasInclusive(); } root.skip().only().skip(); const a: number | null = root.timeout(); root.timeout(100).timeout(100); @@ -276,23 +276,23 @@ namespace shaniTests { namespace spyCallTests { const call = util.spy().firstCall; - call.calledBefore(call) === true; - call.calledAfter(call) === true; - call.calledWithNew(call) === true; + { const a: boolean = call.calledBefore(call); } + { const a: boolean = call.calledAfter(call); } + { const a: boolean = call.calledWithNew(call); } call.thisValue; call.args[0]; call.exception; call.returnValue; - call.calledOn({}) === true; - call.calledWith(1, 2, 3) === true; - call.calledWithExactly(1, 2, 3) === true; - call.calledWithMatch(1, 2, 3) === true; - call.notCalledWith(1, 2, 3) === true; - call.notCalledWithMatch(1, 2, 3) === true; - call.returned(1) === true; - call.threw() === true; - call.threw("12") === true; - call.threw({}) === true; + { const a: boolean = call.calledOn({}); } + { const a: boolean = call.calledWith(1, 2, 3); } + { const a: boolean = call.calledWithExactly(1, 2, 3); } + { const a: boolean = call.calledWithMatch(1, 2, 3); } + { const a: boolean = call.notCalledWith(1, 2, 3); } + { const a: boolean = call.notCalledWithMatch(1, 2, 3); } + { const a: boolean = call.returned(1); } + { const a: boolean = call.threw(); } + { const a: boolean = call.threw("12"); } + { const a: boolean = call.threw({}); } call.callArg(1); call.callArgOn(1, {}); call.callArgWith(1, 1, 2, 3); @@ -307,11 +307,11 @@ namespace shaniTests { util.spy(() => { }).alwaysCalledOn({}); const a: number = util.spy().callCount; const s = util.spy(); - s.called === true; - s.notCalled === true; - s.calledOnce === true; - s.calledTwice === true; - s.calledThrice === true; + { const a: boolean = s.called; } + { const a: boolean = s.notCalled; } + { const a: boolean = s.calledOnce; } + { const a: boolean = s.calledTwice; } + { const a: boolean = s.calledThrice; } s.firstCall.args; s.secondCall.args; s.thirdCall.args; @@ -325,24 +325,30 @@ namespace shaniTests { s.calledAfter(s); s.calledImmediatelyAfter(s); s.calledImmediatelyBefore(s); - s.calledWithNew() === true; + { const a: boolean = s.calledWithNew(); } s.withArgs(1, 2, 3).firstCall.args; - s.alwaysCalledOn({}) === true; - s.alwaysCalledWith(1, 2, 3) === true; - s.alwaysCalledWithExactly(1, 2, 3) === true; - s.alwaysCalledWithMatch(1, 2, 3) === true; - s.neverCalledWith(1, 2, 3) === true; - s.neverCalledWithMatch(1, 2, 3) === true; - s.alwaysThrew() === true; - s.alwaysThrew("a") === true; - s.alwaysThrew({}) === true; - s.alwaysReturned({}) === true; + { const a: boolean = s.alwaysCalledOn({}); } + { const a: boolean = s.alwaysCalledWith(1, 2, 3); } + { const a: boolean = s.alwaysCalledWithExactly(1, 2, 3); } + { const a: boolean = s.alwaysCalledWithMatch(1, 2, 3); } + { const a: boolean = s.neverCalledWith(1, 2, 3); } + { const a: boolean = s.neverCalledWithMatch(1, 2, 3); } + { const a: boolean = s.alwaysThrew(); } + { const a: boolean = s.alwaysThrew("a"); } + { const a: boolean = s.alwaysThrew({}); } + { const a: boolean = s.alwaysReturned({}); } s.invokeCallback(1, 2, 3); s.getCall(0).args; s.getCalls()[0].args; s.reset(); s.printf("%s", "1").toLowerCase(); s.restore(); + s.waitFor(() => true).then((x: adone.shani.util.I.SpyCall) => {}); + s.waitFor(() => true, () => 2).then((x: number) => {}); + s.waitForCall().then((x: adone.shani.util.I.SpyCall) => {}); + s.waitForNCalls(10).then((x: adone.shani.util.I.SpyCall[]) => {}); + s.waitForArg(1, "hello").then((x: adone.shani.util.I.SpyCall) => {}); + s.waitForArgs(1, 2, 3).then((x: adone.shani.util.I.SpyCall) => {}); } namespace stubTests { diff --git a/types/adone/test/glosses/std.ts b/types/adone/test/glosses/std.ts index 611f9401e9..9bcb6687d4 100644 --- a/types/adone/test/glosses/std.ts +++ b/types/adone/test/glosses/std.ts @@ -1,36 +1,4 @@ -import adone from "adone"; - -import * as assert from "assert"; -import * as fs from "fs"; -import * as path from "path"; -import * as util from "util"; -import * as events from "events"; -import * as stream from "stream"; -import * as url from "url"; -import * as net from "net"; -import * as http from "http"; -import * as https from "https"; -import * as child_process from "child_process"; -import * as os from "os"; -import * as cluster from "cluster"; -import * as repl from "repl"; -import * as punycode from "punycode"; -import * as readline from "readline"; -import * as string_decoder from "string_decoder"; -import * as querystring from "querystring"; -import * as crypto from "crypto"; -import * as vm from "vm"; -import * as v8 from "v8"; -import * as domain from "domain"; -import * as tty from "tty"; -import * as buffer from "buffer"; -import * as constants from "constants"; -import * as zlib from "zlib"; -import * as tls from "tls"; -import * as console from "console"; -import * as dns from "dns"; -import * as timers from "timers"; -import * as dgram from "dgram"; +import { adone } from "adone"; const { std } = adone; @@ -124,7 +92,7 @@ namespace stdTests { } namespace tty { - std.tty.isatty(1) === true; + const a: boolean = std.tty.isatty(1); } namespace buffer { diff --git a/types/adone/test/glosses/streams.ts b/types/adone/test/glosses/streams.ts new file mode 100644 index 0000000000..bd090dc467 --- /dev/null +++ b/types/adone/test/glosses/streams.ts @@ -0,0 +1,103 @@ +namespace streamsTests { + const { stream } = adone; + + namespace CoreStreamTests { + const { CoreStream } = stream; + + new CoreStream(); + new CoreStream(undefined); + new CoreStream(undefined, {}); + new CoreStream(undefined, { async: true }); + new CoreStream(undefined, { sync: true }); + new CoreStream(undefined, { + transform(x) { + this.push(x); + } + }); + new CoreStream(undefined, { + flush() { + this.push(1); + } + }); + + new CoreStream([]); + new CoreStream(new CoreStream([])); + + { const a: boolean = new CoreStream().write(1); } + { const a: boolean = new CoreStream().push(1); } + { const a: adone.stream.CoreStream = new CoreStream().end(); } + { const a: adone.stream.CoreStream = new CoreStream().destroy(); } + { const a: adone.stream.CoreStream = new CoreStream().pause(); } + { const a: adone.stream.CoreStream = new CoreStream().resume(); } + { const a: boolean = new CoreStream().isPaused(); } + { const a: boolean = new CoreStream().isEnded(); } + { const a: nodestd.stream.Transform = new CoreStream().pipe(new adone.std.stream.Transform()); } + { const a: adone.stream.CoreStream = new CoreStream().throughSync(function () { this.push(1); }); } + { const a: adone.stream.CoreStream = new CoreStream().throughSync(function () { this.push(1); }, function () { this.push(1); }); } + { const a: adone.stream.CoreStream = new CoreStream().throughAsync(function () { this.push(1); }); } + { const a: adone.stream.CoreStream = new CoreStream().throughAsync(function () { this.push(1); }, function () { this.push(1); }); } + { const a: adone.stream.CoreStream = new CoreStream().through(function () { this.push(1); }, function () { this.push(1); }); } + { const a: adone.stream.CoreStream = new CoreStream([1, 2, 3]).map((x) => `${x}`); } + { const a: adone.stream.CoreStream = new CoreStream().mapIf((x) => x === "1", () => 1); } + { const a: adone.stream.CoreStream = new CoreStream().mapIf(async (x) => x === "1", () => 1); } + { const a: adone.stream.CoreStream = new CoreStream().filter((x) => x === 1); } + { const a: adone.stream.CoreStream = new CoreStream().filter(async (x) => x === 1); } + { const a: adone.stream.CoreStream = new CoreStream().forEach(async (x) => x === 1); } + { const a: adone.stream.CoreStream = new CoreStream().forEach(async (x) => x === 1, {}); } + { const a: adone.stream.CoreStream = new CoreStream().forEach(async (x) => x === 1, { passthrough: true }); } + { const a: adone.stream.CoreStream = new CoreStream().forEach(async (x) => x === 1, { wait: true }); } + { const a: adone.stream.CoreStream = new CoreStream().done(() => {}); } + { const a: adone.stream.CoreStream = new CoreStream().done(() => {}, {}); } + { const a: adone.stream.CoreStream = new CoreStream().done(() => {}, { passthrough: true }); } + { const a: adone.stream.CoreStream = new CoreStream().toArray((x: any[]) => {}); } + { const a: adone.stream.CoreStream = new CoreStream().toArray((x: any[]) => {}, {}); } + { const a: adone.stream.CoreStream = new CoreStream().toArray((x: any[]) => {}, { passthrough: true }); } + { const a: adone.stream.CoreStream = new CoreStream().unique(); } + { const a: adone.stream.CoreStream = new CoreStream().unique((x) => x + 1); } + { const a: adone.stream.CoreStream = new CoreStream().stash((x) => x === 1); } + { const a: adone.stream.CoreStream = new CoreStream().stash("hello", (x) => x === 1); } + { const a: adone.stream.CoreStream = new CoreStream().unstash("hello"); } + { const a: adone.stream.CoreStream = new CoreStream().unstash(); } + { const a: adone.stream.CoreStream = new CoreStream().flatten(); } + { const a: Promise = new CoreStream().then(); } + { const a: Promise = new CoreStream().then(() => "1"); } + { const a: Promise = new CoreStream().then(() => 1, () => 2); } + { const a: Promise = new CoreStream().catch(); } + { const a: Promise = new CoreStream().catch(() => 1); } + { const a: adone.stream.CoreStream = CoreStream.merge([new CoreStream()]); } + { const a: adone.stream.CoreStream = CoreStream.merge([new adone.std.stream.Readable()]); } + { const a: adone.stream.CoreStream = CoreStream.merge([new adone.std.stream.Transform()]); } + { const a: adone.stream.CoreStream = CoreStream.merge([new adone.std.stream.Transform()]); } + { const a: adone.stream.CoreStream = CoreStream.merge([new adone.std.stream.Duplex()]); } + { const a: adone.stream.CoreStream = CoreStream.merge([], {}); } + { const a: adone.stream.CoreStream = CoreStream.merge([], { end: true }); } + { const a: adone.stream.CoreStream = CoreStream.merge([], { sourceOptions: {} }); } + { const a: adone.stream.CoreStream = CoreStream.merge([], { sourceOptions: { async: true } }); } + { const a: adone.stream.CoreStream = CoreStream.merge([], { sourceOptions: { sync: false } }); } + { const a: adone.stream.CoreStream = CoreStream.merge([], { sourceOptions: { transform(x) { this.push(x); } } }); } + { const a: adone.stream.CoreStream = CoreStream.merge([], { sourceOptions: { flush() { this.push(1); } } }); } + (async () => { + const res = await new CoreStream([1, 2, 3, 4, 5]) + .map((x: number) => `${x}`) + .mapIf((x: string) => x[0] === "1", (x) => x.slice(1)) + .map((x) => [x, x, x]) + .filter((x: [string, string, string]) => x[1] === "hello"); + for (const [a, b, c] of res) { + const d: string = a; + const e: string = b; + const f: string = c; + } + }); + } + + namespace coreTests { + { const a: adone.stream.CoreStream = stream.core(); } + { const a: adone.stream.CoreStream = stream.core([1, 2, 3]); } + { const a: adone.stream.CoreStream = stream.core(stream.core([])); } + { const a: adone.stream.CoreStream = stream.core(undefined, {}); } + { const a: adone.stream.CoreStream = stream.core(undefined, { async: true }); } + { const a: adone.stream.CoreStream = stream.core(undefined, { sync: false }); } + { const a: adone.stream.CoreStream = stream.core(undefined, { transform(x) { this.push(Number(x)); } }); } + { const a: adone.stream.CoreStream = stream.core(undefined, { flush() { this.push(1); } }); } + } +} diff --git a/types/adone/test/glosses/utils.ts b/types/adone/test/glosses/utils.ts index 9372fb4b30..33698bfb29 100644 --- a/types/adone/test/glosses/utils.ts +++ b/types/adone/test/glosses/utils.ts @@ -376,6 +376,12 @@ namespace utilTests { const g: string = util.uuid.v4({ nsecs: 1 }); } + namespace v3 { + const a: string = util.uuid.v3([], []); + const b: number[] = util.uuid.v3([], [], []); + const c: number[] = util.uuid.v3([], [], [], 1); + } + namespace v5 { const a: string = util.uuid.v5([], []); const b: number[] = util.uuid.v5([], [], []); @@ -509,7 +515,7 @@ namespace utilTests { } const a: string = util.Editor.DEFAULT; - new util.Editor().spawn().then((x: adone.std.child_process.ChildProcess) => { }); + new util.Editor().spawn().then((x: nodestd.child_process.ChildProcess) => { }); new util.Editor().run().then((x: string) => { }); new util.Editor().cleanup().then((x: undefined) => { }); util.Editor.edit().then((x: string) => { }); @@ -658,80 +664,106 @@ namespace utilTests { const e: [number, number] = clock.hrtime(); const f: [number, number] = clock.hrtime(e); } + } - namespace ltgt { - namespace contains { - const a: boolean = util.ltgt.contains({ lt: 2 }, 2); - const b: boolean = util.ltgt.contains({ lt: 2 }, 2, (a, b) => b - a); - const c: boolean = util.ltgt.contains({ lt: "2" }, "2"); - const d: boolean = util.ltgt.contains({ lt: "2" }, "2", (a, b) => b.charCodeAt(0) - a.charCodeAt(0)); - } + namespace ltgt { + namespace contains { + const a: boolean = util.ltgt.contains({ lt: 2 }, 2); + const b: boolean = util.ltgt.contains({ lt: 2 }, 2, (a, b) => b - a); + const c: boolean = util.ltgt.contains({ lt: "2" }, "2"); + const d: boolean = util.ltgt.contains({ lt: "2" }, "2", (a, b) => b.charCodeAt(0) - a.charCodeAt(0)); + } - namespace filter { - const a: (a: number) => boolean = util.ltgt.filter({ lt: 2 }); - const b: (a: number) => boolean = util.ltgt.filter({ lt: 2 }, (a, b) => b - a); - const c: (a: string) => boolean = util.ltgt.filter({ lt: "2" }); - const d: (a: string) => boolean = util.ltgt.filter({ lt: "2" }, (a, b) => b.charCodeAt(0) - a.charCodeAt(0)); - } + namespace filter { + const a: (a: number) => boolean = util.ltgt.filter({ lt: 2 }); + const b: (a: number) => boolean = util.ltgt.filter({ lt: 2 }, (a, b) => b - a); + const c: (a: string) => boolean = util.ltgt.filter({ lt: "2" }); + const d: (a: string) => boolean = util.ltgt.filter({ lt: "2" }, (a, b) => b.charCodeAt(0) - a.charCodeAt(0)); + } - namespace toLtgt { - const a: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}); - const b: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => `${a}`); - const c: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => a, 2); - const d: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => a, 2, 5); - } + namespace toLtgt { + const a: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}); + const b: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => `${a}`); + const c: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => a, 2); + const d: adone.util.ltgt.I.Range = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => a, 2, 5); + } - namespace endEnclusive { - const a: boolean = util.ltgt.endInclusive({ lt: 2 }); - } + namespace endEnclusive { + const a: boolean = util.ltgt.endInclusive({ lt: 2 }); + } - namespace startInclusive { - const a: boolean = util.ltgt.startInclusive({ lt: 2 }); - } + namespace startInclusive { + const a: boolean = util.ltgt.startInclusive({ lt: 2 }); + } - namespace end { - const a: number | undefined = util.ltgt.end({ lt: 2 }); - const b: number | string = util.ltgt.end({ lt: 2 }, "2"); - const c: number = util.ltgt.end({ lt: 2 }, 2); - } + namespace end { + const a: number | undefined = util.ltgt.end({ lt: 2 }); + const b: number | string = util.ltgt.end({ lt: 2 }, "2"); + const c: number = util.ltgt.end({ lt: 2 }, 2); + } - namespace start { - const a: number | undefined = util.ltgt.start({ lt: 2 }); - const b: number | string = util.ltgt.start({ lt: 2 }, "2"); - const c: number = util.ltgt.start({ lt: 2 }, 2); - } + namespace start { + const a: number | undefined = util.ltgt.start({ lt: 2 }); + const b: number | string = util.ltgt.start({ lt: 2 }, "2"); + const c: number = util.ltgt.start({ lt: 2 }, 2); + } - namespace upperBound { - const a: number | undefined = util.ltgt.upperBound({ lt: 2 }); - const b: number | string = util.ltgt.upperBound({ lt: 2 }, "2"); - const c: number = util.ltgt.upperBound({ lt: 2 }, 2); - } + namespace upperBound { + const a: number | undefined = util.ltgt.upperBound({ lt: 2 }); + const b: number | string = util.ltgt.upperBound({ lt: 2 }, "2"); + const c: number = util.ltgt.upperBound({ lt: 2 }, 2); + } - namespace upperBoundKey { - const a: number | undefined = util.ltgt.upperBoundKey({ lt: 2 }); - } + namespace upperBoundKey { + const a: number | undefined = util.ltgt.upperBoundKey({ lt: 2 }); + } - namespace upperBoundExclusive { - const a: boolean = util.ltgt.upperBoundInclusive({ lt: 2 }); - } + namespace upperBoundExclusive { + const a: boolean = util.ltgt.upperBoundInclusive({ lt: 2 }); + } - namespace lowerBoundExclusive { - const a: boolean = util.ltgt.lowerBoundInclusive({ lt: 2 }); - } + namespace lowerBoundExclusive { + const a: boolean = util.ltgt.lowerBoundInclusive({ lt: 2 }); + } - namespace upperBoundInclusive { - const a: boolean = util.ltgt.upperBoundInclusive({ lt: 2 }); - } + namespace upperBoundInclusive { + const a: boolean = util.ltgt.upperBoundInclusive({ lt: 2 }); + } - namespace lowerBoundInclusive { - const a: boolean = util.ltgt.lowerBoundInclusive({ lt: 2 }); - } + namespace lowerBoundInclusive { + const a: boolean = util.ltgt.lowerBoundInclusive({ lt: 2 }); + } - namespace lowerBound { - const a: number | undefined = util.ltgt.lowerBound({ lt: 2 }); - const b: number | string = util.ltgt.lowerBound({ lt: 2 }, "2"); - const c: number = util.ltgt.lowerBound({ lt: 2 }, 2); - } + namespace lowerBound { + const a: number | undefined = util.ltgt.lowerBound({ lt: 2 }); + const b: number | string = util.ltgt.lowerBound({ lt: 2 }, "2"); + const c: number = util.ltgt.lowerBound({ lt: 2 }, 2); } } + + namespace userid { + const { userid } = util; + + { const a: number = userid.uid("someone").gid; } + { const a: number = userid.uid("someone").uid; } + { const a: number = userid.gid("someone"); } + { const a: string = userid.username(1000); } + { const a: string = userid.groupname(1000); } + { const gids: number[] = userid.gids("someone"); } + } + + namespace LogRotator { + const { LogRotator } = util; + new LogRotator("file.log"); + new LogRotator("file.log", {}); + new LogRotator("file.log", { checkInterval: 1000 }); + new LogRotator("file.log", { checkInterval: "10 minutes" }); + new LogRotator("file.log", { maxSize: 1000 }); + new LogRotator("file.log", { maxSize: "100kb" }); + new LogRotator("file.log", { maxFiles: 10 }); + new LogRotator("file.log", { compress: true }); + new LogRotator("file.log").rotate().then(() => {}); + new LogRotator("file.log").start(); + new LogRotator("file.log").stop(); + } } diff --git a/types/adone/test/index-import.ts b/types/adone/test/index-import.ts index 906e57938c..7c546aa03f 100644 --- a/types/adone/test/index-import.ts +++ b/types/adone/test/index-import.ts @@ -1,4 +1,4 @@ -import adone from "adone"; +import { adone } from "adone"; namespace AdoneRootImportTests { adone.falsely() === false; diff --git a/types/adone/test/index.ts b/types/adone/test/index.ts index 2ba475ee89..a9de1ab34b 100644 --- a/types/adone/test/index.ts +++ b/types/adone/test/index.ts @@ -29,9 +29,12 @@ namespace AdoneRootTests { adone.lazify({}); adone.lazify({}, {}); adone.lazify({}, {}, () => { }); + adone.lazify({}, {}, () => { }, {}); adone.lazify({}, {}, () => { }, { configurable: true }); + adone.lazify({}, {}, () => { }, { writable: false }); + adone.lazify({}, {}, () => { }, { mapper: (key: string, obj: any) => null }); adone.tag.set({}, "123"); - adone.tag.has({}, "123") === true; + { const a: boolean = adone.tag.has({}, "123"); } adone.tag.define("12"); adone.tag.define("123", "456"); { const a: symbol = adone.tag.SUBSYSTEM; } @@ -59,8 +62,6 @@ namespace AdoneRootTests { { const a: symbol = adone.tag.FAST_STREAM; } { const a: symbol = adone.tag.FAST_FS_STREAM; } { const a: symbol = adone.tag.FAST_FS_MAP_STREAM; } - { const a: Promise = adone.run({}); } - { const a: Promise = adone.run({}, false); } { const a: object = adone.bind("library"); } // hmm { const a: string = adone.getAssetAbsolutePath("asset"); } { const a: Buffer | string = adone.loadAsset("asset"); } diff --git a/types/adone/tsconfig.json b/types/adone/tsconfig.json index ad90d2b5d7..d472e48dba 100644 --- a/types/adone/tsconfig.json +++ b/types/adone/tsconfig.json @@ -19,24 +19,48 @@ "files": [ "index.d.ts", "adone.d.ts", - "glosses/common.d.ts", - "glosses/math.d.ts", + "glosses/math/index.d.ts", + "glosses/math/matrix.d.ts", + "glosses/math/simd.d.ts", "glosses/std.d.ts", "glosses/utils.d.ts", "glosses/assertion.d.ts", "glosses/promise.d.ts", "glosses/shani.d.ts", "glosses/shani-global.d.ts", + "glosses/collections.d.ts", + "glosses/events.d.ts", + "glosses/fs.d.ts", + "glosses/is.d.ts", + "glosses/exceptions.d.ts", + "glosses/streams.d.ts", + "glosses/fast.d.ts", + "glosses/data.d.ts", + "glosses/datetime.d.ts", + "glosses/compressors.d.ts", + "glosses/archives.d.ts", "adone-tests.ts", "test/index.ts", "test/index-import.ts", - "test/glosses/common.ts", - "test/glosses/math.ts", + "test/glosses/math/index.ts", + "test/glosses/math/matrix.ts", + "test/glosses/math/simd.ts", "test/glosses/std.ts", "test/glosses/utils.ts", "test/glosses/assertion.ts", "test/glosses/promise.ts", "test/glosses/shani.ts", - "test/glosses/shani-global.ts" + "test/glosses/shani-global.ts", + "test/glosses/collections.ts", + "test/glosses/events.ts", + "test/glosses/fs.ts", + "test/glosses/is.ts", + "test/glosses/exceptions.ts", + "test/glosses/streams.ts", + "test/glosses/fast.ts", + "test/glosses/data.ts", + "test/glosses/datetime.ts", + "test/glosses/compressors.ts", + "test/glosses/archives.ts" ] } diff --git a/types/adone/tslint.json b/types/adone/tslint.json index ef323bd7a5..8c265eebb4 100644 --- a/types/adone/tslint.json +++ b/types/adone/tslint.json @@ -12,6 +12,7 @@ "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, "unified-signatures": false, - "space-before-function-paren": false + "space-before-function-paren": false, + "await-promise": false } } \ No newline at end of file