This commit is contained in:
Zev Spitz
2018-02-10 21:40:54 +02:00
153 changed files with 6042 additions and 3751 deletions
File diff suppressed because it is too large Load Diff
+44
View File
@@ -0,0 +1,44 @@
declare namespace adone.collection {
/**
* 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<T = any> {
/**
* 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<T>(iterable: Iterable<T>, allowDuplicates?: boolean): ArraySet<T>;
}
}
+12
View File
@@ -0,0 +1,12 @@
declare namespace adone.collection {
/**
* 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<T = any> extends Queue<T, Promise<T>> {
/**
* Returns a promise that will be resolved with an existing element or an element that will be pushed in the future
*/
pop(): Promise<T>;
}
}
+48
View File
@@ -0,0 +1,48 @@
declare namespace adone.collection {
/**
* Represents an AVL tree, a self-balancing binary search tree
*/
class AVLTree<K = any, V = any> {
constructor(options?: I.BinarySearchTree.ConstructorOptions<K, V, AVLTree<K, V>>);
/**
* 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<K>): V[];
/**
* Executed the given callback for each node from left to right
*/
executeOnEveryNode(fn: (tree: AVLTree<K, V>) => void): void;
/**
* Prints the tree
*/
prettyPrint(printDate?: boolean, spacing?: string): void;
}
}
+110
View File
@@ -0,0 +1,110 @@
declare namespace adone.collection {
namespace I.BinarySearchTree {
interface ConstructorOptions<K, V, Tree> {
/**
* 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<K> {
$lt?: K;
$lte?: K;
$gt?: K;
$gte?: K;
}
}
/**
* Represents a binary search tree
*/
class BinarySearchTree<K = any, V = any> {
constructor(options?: I.BinarySearchTree.ConstructorOptions<K, V, BinarySearchTree<K, V>>);
/**
* Returns the max descendant tree
*/
getMaxKeyDescendant(): BinarySearchTree<K, V>;
/**
* Returns the maximum key
*/
getMaxKey(): K;
/**
* Returns the min descendant tree
*/
getMinKeyDescendant(): BinarySearchTree<K, V>;
/**
* 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<K>): 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<K, V>) => void): void;
/**
* Prints the tree
*/
prettyPrint(printData?: boolean, spacing?: string): void;
}
}
+92
View File
@@ -0,0 +1,92 @@
declare namespace adone.collection {
namespace I.BufferList {
type Appendable = Buffer | BufferList | string | number | Array<Buffer | BufferList | string | number>;
}
/**
* Represents a Node.js Buffer list collector, reader and streamer with callback/promise interface support
*/
class BufferList extends std.stream.Duplex implements PromiseLike<Buffer> {
/**
* 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;
end(chunk?: () => void): 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<T extends Buffer = Buffer>(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 start slice from
* @param 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<T1 = Buffer, T2 = never>(
onfulfilled?: ((value: Buffer) => T1 | PromiseLike<T1>) | null,
onrejected?: ((reason: any) => T2 | PromiseLike<T2>) | null
): PromiseLike<T1 | T2>;
catch<T>(onrejected?: ((reason: any) => T | PromiseLike<T>) | null): PromiseLike<T | Buffer>;
}
}
+892
View File
@@ -0,0 +1,892 @@
declare namespace adone.collection {
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 {
readonly woffset: number;
readonly roffset: number;
readonly buffer: Buffer;
readonly noAssert: boolean;
/**
* 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 at
* @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 at
*/
writeBitSet(value: number[], offset: number): number;
/**
* Writes a buffer at the given offset
* @param buf Buffer to write
* @param offset Offset to write at
*/
writeBuffer(buf: Buffer, offset?: number): this;
/**
* Writes an 8bit signed integer
*
* @param offset Offset to write at
*/
writeInt8(value: number, offset?: number): this;
/**
* Writes an 8bit unsigned integer
*
* @param offset Offset to write at
*/
writeUInt8(value: number, offset?: number): this;
/**
* Writes a 16bit signed le integer
*
* @param offset Offset to write at
*/
writeInt16LE(value: number, offset?: number): this;
/**
* Writes a 16bit signed be integer
*
* @param offset Offset to write at
*/
writeInt16BE(value: number, offset?: number): this;
/**
* Writes a 16bit unsigned le integer
*
* @param offset Offset to write at
*/
writeUInt16LE(value: number, offset?: number): this;
/**
* Writes a 16bit unsigned be integer
*
* @param offset Offset to write at
*/
writeUInt16BE(value: number, offset?: number): this;
/**
* Writes a 32bit signed le integer
*
* @param offset Offset to write at
*/
writeInt32LE(value: number, offset?: number): this;
/**
* Writes a 32bit signed be integer
*
* @param offset Offset to write at
*/
writeInt32BE(value: number, offset?: number): this;
/**
* Writes a 32bit unsigned le integer
*
* @param offset Offset to write at
*/
writeUInt32LE(value: number, offset?: number): this;
/**
* Writes a 32bit unsigned be integer
*
* @param offset Offset to write at
*/
writeUInt32BE(value: number, offset?: number): this;
/**
* Writes a 64bit signed le long integer
*
* @param offset Offset to write at
*/
writeInt64LE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit signed be long integer
*
* @param offset Offset to write at
*/
writeInt64BE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit unsigned le long integer
*
* @param offset Offset to write at
*/
writeUInt64LE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit unsigned be long integer
*
* @param offset Offset to write at
*/
writeUInt64BE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 32bit le float
*
* @param offset Offset to write at
*/
writeFloatLE(value: number, offset?: number): this;
/**
* Writes a 32bit be float
*
* @param offset Offset to write at
*/
writeFloatBE(value: number, offset?: number): this;
/**
* Writes a 64bit le float
*
* @param offset Offset to write at
*/
writeDoubleLE(value: number, offset?: number): this;
/**
* Writes a 64bit be float
*
* @param offset Offset to write at
*/
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 at
*/
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 at
*/
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 at
*/
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 at
*/
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 at
*/
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 at
*/
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 capacity Capacity required
*/
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;
}
}
+9
View File
@@ -0,0 +1,9 @@
declare namespace adone.collection {
/**
* Represents a Map that has a default values factory object or function.
* Each get of non-existent key goes through the factory
*/
class DefaultMap<K = string, V = any> extends Map<K, V> {
constructor(factory?: ((key: K) => V) | { [key: string]: V }, iterable?: Iterable<[K, V]>);
}
}
+61
View File
@@ -0,0 +1,61 @@
declare namespace adone.collection {
/**
* Represents a faster LRU cache but with less functionality
*/
class FastLRU<K = any, V = any> {
/**
* @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<K>;
/**
* Returns the values iterator
*/
values(): IterableIterator<V>;
/**
* Returns the entries iterator
*/
entries(): IterableIterator<[K, V]>;
/**
* Clears the cache
*/
clear(): void;
}
}
+28
View File
@@ -0,0 +1,28 @@
/// <reference path="./array_set.d.ts" />
/// <reference path="./async_queue.d.ts" />
/// <reference path="./avl_tree.d.ts" />
/// <reference path="./binary_search_tree.d.ts" />
/// <reference path="./buffer_list.d.ts" />
/// <reference path="./byte_array.d.ts" />
/// <reference path="./default_map.d.ts" />
/// <reference path="./fast_lru.d.ts" />
/// <reference path="./linked_list.d.ts" />
/// <reference path="./lru.d.ts" />
/// <reference path="./map_cache.d.ts" />
/// <reference path="./ns_cache.d.ts" />
/// <reference path="./priority_queue.d.ts" />
/// <reference path="./queue.d.ts" />
/// <reference path="./rb_tree.d.ts" />
/// <reference path="./refcounted_cache.d.ts" />
/// <reference path="./set.d.ts" />
/// <reference path="./stack.d.ts" />
/// <reference path="./timedout_map.d.ts" />
declare namespace adone {
/**
* Data structures
*/
namespace collection {
//
}
}
+150
View File
@@ -0,0 +1,150 @@
declare namespace adone.collection {
namespace I.LinkedList {
/**
* Represents the node of a linked list
*/
interface Node<T> {
/**
* The next node
*/
next?: Node<T>;
/**
* The previous node
*/
prev?: Node<T>;
/**
* The value this node contains
*/
value: T;
}
}
/**
* Represents a linked list
*/
class LinkedList<T = any> {
/**
* 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<T>;
/**
* 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<T>;
/**
* Moves the given node to the end of the list
*/
pushNode(node: I.LinkedList.Node<T>): void;
/**
* Moved the given node to the beginning of the list
*/
unshiftNode(node: I.LinkedList.Node<T>): void;
/**
* Removes the given node from the list
*/
removeNode(node: I.LinkedList.Node<T>): 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<T>;
/**
* Returns the next node for the given node
*/
nextNode(node: I.LinkedList.Node<T>): I.LinkedList.Node<T>;
/**
* Maps this linked list to a new one using the given function
*/
map<R>(fn: (value: T, index: number) => R): LinkedList<R>;
/**
* 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;
}
}
+213
View File
@@ -0,0 +1,213 @@
declare namespace adone.collection {
namespace I.LRU {
type LengthCalculator<K, V> = (value: V, key: K) => number;
interface ConstructorOptions<K, V> {
/**
* 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<K, V>;
/**
* 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<K, V> {
/**
* key
*/
key: K;
/**
* value
*/
value: V;
/**
* when it becomes expired
*/
e: number;
}
interface Entry<K, V> {
/**
* 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<K = any, V = any> {
/**
* Creates an LRU cache of the given size
*/
constructor(max: number);
/**
* Creates an LRU cache with the given options
*/
constructor(options?: I.LRU.ConstructorOptions<K, V>);
/**
* 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<K, V>;
/**
* 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<T = any>(fn: (this: T, value: V, key: K, cache: LRU<K, V>) => void, thisp?: T): void;
/**
* Iterates over all the keys in the cache, in order of recent-ness
*/
forEach<T = any>(fn: (this: T, value: V, key: K, cache: LRU<K, V>) => 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<I.LRU.SerializedEntry<K, V>>;
/**
* Returns an internal lru list of entries
*/
dumpLru(): LinkedList<I.LRU.Entry<K, V>>;
/**
* @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<K, V>;
/**
* 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<I.LRU.SerializedEntry<K, V>>): void;
/**
* Manually iterates over the entire cache proactively pruning old entries
*/
prune(): void;
}
}
+13
View File
@@ -0,0 +1,13 @@
declare namespace adone.collection {
class MapCache<T = any> {
has(key: string): boolean;
get(key: string): T;
set(key: string, value: T): void;
delete(key: string): void;
clear(): void;
}
}
+17
View File
@@ -0,0 +1,17 @@
declare namespace adone.collection {
class NSCache<T = any> {
constructor(size: number, namespaces: string[]);
resize(newSize: number): void;
set(ns: string, key: string, value: T): void;
get(ns: string, key: string): T;
has(ns: string, key: string): boolean;
delete(ns: string, key: string): void;
clear(): void;
}
}
+78
View File
@@ -0,0 +1,78 @@
declare namespace adone.collection {
namespace I.PriorityQueue {
interface ConstructorOptions<T> {
/**
* 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<T = any> {
/**
* Whether the queue is empty
*/
readonly empty: boolean;
/**
* The length of the queue
*/
readonly length: number;
constructor(options?: I.PriorityQueue.ConstructorOptions<T>);
/**
* Clones the queue
*/
clone(): PriorityQueue<T>;
/**
* 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<T>(iterable: Iterable<T>, options?: I.PriorityQueue.ConstructorOptions<T>): PriorityQueue<T>;
}
}
+31
View File
@@ -0,0 +1,31 @@
declare namespace adone.collection {
/**
* Represents a queue
*/
class Queue<S = any, T = S> {
/**
* 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;
}
}
+184
View File
@@ -0,0 +1,184 @@
declare namespace adone.collection {
namespace I.RedBlackTree {
interface Node<K, V> {
/**
* The key associated to the node
*/
key: K;
/**
* The value associated to the node
*/
value: V;
/**
* The left subtree of the node
*/
left?: Node<K, V>;
/**
* The right subtree of the node
*/
right?: Node<K, V>;
}
interface Iterator<K, V> {
/**
* 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<K, V> | 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<K, V>;
/**
* Makes a copy of the iterator
*/
clone(): Iterator<K, V>;
/**
* Removes the item at the position of the iterator and returns a new rb-tree
*/
remove(): RedBlackTree<K, V>;
/**
* 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<K, V>;
/**
* Moves the iterator backward one element
*/
prev(): void;
}
}
/**
* Represents a fully persistent red-black tree
*/
class RedBlackTree<K = any, V = any> {
/**
* The root node of the tree
*/
root: I.RedBlackTree.Node<K, V>;
constructor(compare?: (a: K, b: K) => number, root?: RedBlackTree<K, V>);
/**
* 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<K, V>;
/**
* An iterator pointing to the last element in the tree
*/
readonly end: I.RedBlackTree.Iterator<K, V>;
/**
* Creates a new tree with the new pair inserted
*/
insert(key: K, value: V): RedBlackTree<K, V>;
/**
* 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<T>(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<K, V>;
/**
* Finds the first item in the tree whose key is >= key
*/
ge(key: K): I.RedBlackTree.Iterator<K, V>;
/**
* Finds the first item in the tree whose key is > key
*/
gt(key: K): I.RedBlackTree.Iterator<K, V>;
/**
* Finds the first item in the tree whose key is < key
*/
lt(key: K): I.RedBlackTree.Iterator<K, V>;
/**
* Finds the first item in the tree whose key is <= key
*/
le(key: K): I.RedBlackTree.Iterator<K, V>;
/**
* Returns an iterator pointing to the first item in the tree with key, otherwise null
*/
find(key: K): I.RedBlackTree.Iterator<K, V> | null;
/**
* Removes the first item with key in the tree
*/
remove(key: K): RedBlackTree<K, V>;
/**
* Retrieves the value associated to the given key
*/
get(key: K): V | undefined;
}
}
+9
View File
@@ -0,0 +1,9 @@
declare namespace adone.collection {
class RefcountedCache<T = any> extends MapCache<T> {
ref(key: string): void;
unref(key: string): void;
references(key: string): number;
}
}
+17
View File
@@ -0,0 +1,17 @@
declare namespace adone.collection {
class Set<T = any> {
constructor(key?: (x: T) => any);
has(value: T): boolean;
add(value: T): void;
delete(value: T): void;
get(value: T): T; // ???
readonly size: number;
only(): T;
}
}
+36
View File
@@ -0,0 +1,36 @@
declare namespace adone.collection {
/**
* Represents a stack
*/
class Stack<T = any> {
/**
* 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<T>;
/**
* Creates a stack and pushed all the values from the given iterable object
*/
static from<T>(iterable: Iterable<T>): Stack<T>;
}
}
+32
View File
@@ -0,0 +1,32 @@
declare namespace adone.collection {
/**
* Represents a Map that keeps keys only for a specified interval of time
*/
class TimedoutMap<K = any, V = any> extends Map<K, V> {
/**
* @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<T = any>(callback: (this: T, value: V, key: K, cache: this) => void, thisArg?: T): this;
/**
* Deletes the given key
*/
delete(key: K): boolean;
}
}
+178
View File
@@ -1050,5 +1050,183 @@ declare namespace adone {
*/
function decode(buf: Buffer, options?: I.DeserializeOptions): any;
}
namespace protobuf {
namespace schema {
namespace I {
interface Field {
name: string | null;
type: string | null;
tag: number;
map: {
from: string;
to: string;
} | null;
oneof: string | null;
required: boolean;
repeated: boolean;
options: object;
}
interface Enum {
name: string;
values: object;
options: object;
}
interface Extend {
name: string;
message: Message;
}
interface Message {
name: string;
enums: Enum[];
extends: Extend[];
messages: Message[];
fields: Field[];
extensions: {
from: number,
to: number
} | null;
}
interface RPCMethod {
name: string;
input_type: string | null;
output_type: string | null;
client_streaming: boolean;
server_streaming: boolean;
options: object;
}
interface Service {
name: string;
methods: RPCMethod[];
options: object;
}
interface Schema {
syntax: any; // ??
package: string | null;
imports: string[];
enums: Enum[];
messages: Message[];
options: object;
extends: Extend[];
services?: Service[];
}
}
function parse(buf: Buffer | string): I.Schema;
function stringify(schema: object): string;
}
function create(proto: Buffer | string | object, opts?: object): object;
}
namespace base32 {
function charmap<T = object>(alphabet: string, mappings?: T): T;
namespace I {
interface Spec {
alphabet: string;
charmap: {
[c: string]: number;
};
}
}
const rfc4648: I.Spec;
const crockford: I.Spec;
const base32hex: I.Spec;
namespace I {
interface DecoderOptions {
type: "rfc4648" | "crockford" | "base32hex";
charmap?: object;
}
interface EncoderOptions {
type: "rfc4648" | "crockford" | "base32hex";
alphabet?: string;
}
}
class Decoder {
constructor(options?: I.DecoderOptions);
write(str: string): this;
finalize(str?: string): Buffer;
}
class Encoder {
constructor(options?: I.EncoderOptions);
write(buf: Buffer): this;
finalize(buf?: Buffer): string;
}
function encode(buf: Buffer, options?: I.EncoderOptions): string;
function decode(str: string, options?: I.DecoderOptions): Buffer;
}
namespace I {
interface BaseX {
encode(buf: Buffer): string;
decode(str: string): Buffer;
decodeUnsafe(str: string): Buffer;
}
}
function basex(alphabet: string): I.BaseX;
const base58: I.BaseX;
namespace base64url {
function unescape(str: string): string;
function escape(str: string): string;
namespace I {
interface EncodeOptions {
encoding?: string;
}
interface DecodeOptions {
encoding?: string;
buffer?: boolean;
}
}
function encode(str: Buffer | string, options?: I.EncodeOptions): string;
function decode(str: string, options: I.DecodeOptions & { buffer: true }): Buffer;
function decode(str: string, options?: I.DecodeOptions): string;
}
namespace varint {
function encode<T = any>(num: number, out?: T[], offset?: number): T[];
function decode(buf: Buffer, offset?: number): number;
function encodingLength(value: number): number;
}
namespace varintSigned {
function encode<T = any>(num: number, out?: T[], offset?: number): T[];
function decode(buf: Buffer, offset?: number): number;
function encodingLength(value: number): number;
}
}
}
+337
View File
@@ -0,0 +1,337 @@
declare namespace adone {
namespace fake {
namespace I {
interface Card {
name: string;
username: string;
email: string;
address: FullAddress;
phone: string;
website: string;
company: Company;
posts: Post[];
accountHistory: string[];
}
interface FullAddress {
streetA: string;
streetB: string;
streetC: string;
streetD: string;
city: string;
state: string;
county: string;
zipcode: string;
geo: Geo;
}
interface Geo {
lat: string;
lng: string;
}
interface Company {
name: string;
catchPhrase: string;
bs: string;
}
interface Post {
words: string;
sentence: string;
sentences: string;
paragraph: string;
}
interface ContextualCard {
name: string;
username: string;
email: string;
dob: Date;
phone: string;
address: Address;
website: string;
company: Company;
}
interface Address {
street: string;
suite: string;
city: string;
state: string;
zipcode: string;
geo: Geo;
}
interface UserCard {
name: string;
username: string;
email: string;
address: Address;
phone: string;
website: string;
company: Company;
}
interface Transaction {
amount: string;
date: Date;
business: string;
name: string;
type: string;
account: string;
}
}
namespace address {
function zipCode(format?: string): string;
function city(format?: number): string;
function cityPrefix(): string;
function citySuffix(): string;
function streetName(): string;
function streetAddress(useFullAddress?: boolean): string;
function streetSuffix(): string;
function streetPrefix(): string;
function secondaryAddress(): string;
function county(): string;
function country(): string;
function countryCode(): string;
function state(useAbbr?: boolean): string;
function stateAbbr(): string;
function latitude(): string;
function longitude(): string;
}
namespace commerce {
function color(): string;
function department(): string;
function productName(): string;
function price(min?: number, max?: number, dec?: number, symbol?: string): string;
function productAdjective(): string;
function productMaterial(): string;
function product(): string;
}
namespace company {
function suffixes(): string[];
function companyName(format?: number): string;
function companySuffix(): string;
function catchPhrase(): string;
function bs(): string;
function catchPhraseAdjective(): string;
function catchPhraseDescriptor(): string;
function catchPhraseNoun(): string;
function bsAdjective(): string;
function bsBuzz(): string;
function bsNoun(): string;
}
namespace database {
function column(): string;
function type(): string;
function collation(): string;
function engine(): string;
}
namespace date {
function past(years?: number, refDate?: string|Date): Date;
function future(years?: number, refDate?: string|Date): Date;
function between(from: string|number|Date, to: string|Date): Date;
function recent(days?: number): Date;
function soon(days?: number): Date;
function month(options?: { abbr?: boolean, context?: boolean }): string;
function weekday(options?: { abbr?: boolean, context?: boolean }): string;
}
function fake(str: string): string;
namespace finance {
function account(length?: number): string;
function accountName(): string;
function mask(length?: number, parens?: boolean, elipsis?: boolean): string;
function amount(min?: number, max?: number, dec?: number, symbol?: string): string;
function transactionType(): string;
function currencyCode(): string;
function currencyName(): string;
function currencySymbol(): string;
function bitcoinAddress(): string;
function ethereumAddress(): string;
function iban(formatted?: boolean): string;
function bic(): string;
}
namespace hacker {
function abbreviation(): string;
function adjective(): string;
function noun(): string;
function verb(): string;
function ingverb(): string;
function phrase(): string;
}
namespace helpers {
function randomize<T>(array: T[]): T;
function randomize(): string;
function slugify(string?: string): string;
function replaceSymbolWithNumber(string?: string, symbol?: string): string;
function replaceSymbols(string?: string): string;
function shuffle<T>(o: T[]): T[];
function shuffle(): string[];
function mustache(str: string, data: { [key: string]: string|((substring: string, ...args: any[]) => string) }): string;
function createCard(): I.Card;
function contextualCard(): I.ContextualCard;
function userCard(): I.UserCard;
function createTransaction(): I.Transaction;
}
namespace image {
function image(): string;
function avatar(): string;
function imageUrl(width?: number, height?: number, category?: string): string;
function abstract(width?: number, height?: number): string;
function animals(width?: number, height?: number): string;
function business(width?: number, height?: number): string;
function cats(width?: number, height?: number): string;
function city(width?: number, height?: number): string;
function food(width?: number, height?: number): string;
function nightlife(width?: number, height?: number): string;
function fashion(width?: number, height?: number): string;
function people(width?: number, height?: number): string;
function nature(width?: number, height?: number): string;
function sports(width?: number, height?: number): string;
function technics(width?: number, height?: number): string;
function transport(width?: number, height?: number): string;
function dataUri(width?: number, height?: number): string;
}
namespace internet {
function avatar(): string;
function email(firstName?: string, lastName?: string, provider?: string): string;
function exampleEmail(firstName?: string, lastName?: string): string;
function userName(firstName?: string, lastName?: string): string;
function protocol(): string;
function url(): string;
function domainName(): string;
function domainSuffix(): string;
function domainWord(): string;
function ip(): string;
function ipv6(): string;
function userAgent(): string;
function color(baseRed255?: number, baseGreen255?: number, baseBlue255?: number): string;
function mac(): string;
function password(len?: number, memorable?: boolean, pattern?: string|RegExp, prefix?: string): string;
}
namespace lorem {
function word(): string;
function words(num?: number): string;
function sentence(wordCount?: number, range?: number): string;
function slug(wordCount?: number): string;
function sentences(sentenceCount?: number): string;
function paragraph(sentenceCount?: number): string;
function paragraphs(paragraphCount?: number, separator?: string): string;
function text(times?: number): string;
function lines(lineCount?: number): string;
}
namespace name {
function firstName(gender?: number): string;
function lastName(gender?: number): string;
function findName(firstName?: string, lastName?: string, gender?: number): string;
function jobTitle(): string;
function prefix(): string;
function suffix(): string;
function title(): string;
function jobDescriptor(): string;
function jobArea(): string;
function jobType(): string;
}
namespace phone {
function phoneNumber(format?: string): string;
function phoneNumberFormat(phoneFormatsArrayIndex?: number): string;
function phoneFormats(): string;
}
namespace random {
function number(max: number): number;
function number(options?: { min?: number, max?: number, precision?: number }): number;
function arrayElement(): string;
function arrayElement<T>(array: T[]): T;
function objectElement(object?: { [key: string]: any }, field?: "key"): string;
function objectElement<T>(object?: { [key: string]: T }, field?: any): T;
function uuid(): string;
function boolean(): boolean;
function word(type?: string): string;
function words(count?: number): string;
function image(): string;
function locale(): string;
function alphaNumeric(count?: number): string;
function hexaDecimal(count?: number): string;
}
namespace system {
function fileName(ext: string, type: string): string;
function commonFileName(ext: string, type: string): string;
function mimeType(): string;
function commonFileType(): string;
function commonFileExt(): string;
function fileType(): string;
function fileExt(mimeType: string): string;
function directoryPath(): string;
function filePath(): string;
function semver(): string;
}
function seed(value: number): void;
namespace I {
type Locale =
| "az"
| "cz"
| "de"
| "de_AT"
| "de_CH"
| "el"
| "en"
| "en_AU"
| "en_BORK"
| "en_CA"
| "en_GB"
| "en_IE"
| "en_IND"
| "en_US"
| "en_au_ocker"
| "es"
| "es_MX"
| "fa"
| "fr"
| "fr_CA"
| "ge"
| "id_ID"
| "it"
| "ja"
| "ko"
| "lv"
| "nb_NO"
| "nep"
| "nl"
| "nl_BE"
| "pl"
| "pt_BR"
| "ro"
| "ru"
| "sk"
| "sv"
| "tr"
| "uk"
| "vi"
| "zh_CN"
| "zh_TW";
}
function getLocale(): I.Locale;
function setLocale(locale: I.Locale): void;
}
}
+6 -2
View File
@@ -227,13 +227,13 @@ declare namespace adone {
/**
* Checks whether the given object is a function
*/
function _function(obj: any): boolean;
function _function(obj: any): obj is (...args: any[]) => any;
export { _function as function };
/**
* Checks whether the given object is an async function
*/
export function asyncFunction(obj: any): boolean;
export function asyncFunction(obj: any): obj is (...args: any[]) => Promise<any>;
/**
* Checks whether the given object is a promise
@@ -672,5 +672,9 @@ declare namespace adone {
* Checks whether the given object is a valid UUID identifier (v1, v2, v3, v4 or v5)
*/
export function uuid(obj: any, version?: "all"): obj is string;
export function emitter(obj: any): obj is event.Emitter;
export function asyncEmitter(obj: any): obj is event.AsyncEmitter;
}
}
+2 -1
View File
@@ -8,12 +8,13 @@
/// <reference path="./glosses/application.d.ts" />
/// <reference path="./glosses/archives.d.ts" />
/// <reference path="./glosses/assertion.d.ts" />
/// <reference path="./glosses/collections.d.ts" />
/// <reference path="./glosses/collections/index.d.ts" />
/// <reference path="./glosses/compressors.d.ts" />
/// <reference path="./glosses/data.d.ts" />
/// <reference path="./glosses/datetime.d.ts" />
/// <reference path="./glosses/events.d.ts" />
/// <reference path="./glosses/exceptions.d.ts" />
/// <reference path="./glosses/fake.d.ts" />
/// <reference path="./glosses/fast.d.ts" />
/// <reference path="./glosses/fs.d.ts" />
/// <reference path="./glosses/is.d.ts" />
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,19 @@
namespace adoneTests.collection.ArraySet {
const {
collection: {
ArraySet
}
} = adone;
type ArraySet<T = any> = adone.collection.ArraySet<T>;
new ArraySet();
{ const a: number = new ArraySet().length; }
{ const a: ArraySet = new ArraySet<string>().add("hello"); }
{ const a: ArraySet = new ArraySet<string>().add("hello", true); }
{ const a: boolean = new ArraySet<string>().has("string"); }
{ const a: number = new ArraySet<string>().indexOf("hello"); }
{ const a: string[] = new ArraySet<string>().toArray(); }
{ const a: ArraySet<number> = ArraySet.from([1]); }
{ const a: ArraySet<number> = ArraySet.from([1], true); }
}
@@ -0,0 +1,12 @@
namespace adoneTests.collection.AsyncQueue {
const {
collection: {
AsyncQueue
}
} = adone;
type AsyncQueue = adone.collection.AsyncQueue;
{ const a: AsyncQueue = new AsyncQueue().push(123); }
{ const a: Promise<number> = new AsyncQueue<number>().push(123).pop(); }
}
@@ -0,0 +1,28 @@
namespace adoneTests.collection.AVLTree {
const {
collection: {
AVLTree
}
} = adone;
type AVLTree<K = any, V = any> = adone.collection.AVLTree<K, V>;
new AVLTree();
new AVLTree<string, number>({ checkValueEquality: (a: number, b: number) => a === b });
new AVLTree<string, number>({ compareKeys: (a: string, b: string) => a.length - b.length });
new AVLTree<string, number>({ parent: new AVLTree() });
new AVLTree<string, number>({ unique: false });
new AVLTree<string, number>({ value: 123 });
new AVLTree<string, number>().checkIsAVLT();
new AVLTree<string, number>().insert("123", 123);
new AVLTree<string, number>().delete("123");
new AVLTree<string, number>().delete("123", 123);
{ const a: number = new AVLTree<string, number>().getNumberOFKeys(); }
{ const a: number[] = new AVLTree<string, number>().search("key"); }
{ const a: number[] = new AVLTree<string, number>().betweenBounds({}); }
{ const a: number[] = new AVLTree<string, number>().betweenBounds({ $gt: "ads" }); }
{ const a: number[] = new AVLTree<string, number>().betweenBounds({ $lt: "ads" }); }
{ const a: number[] = new AVLTree<string, number>().betweenBounds({ $gte: "ads" }); }
{ const a: number[] = new AVLTree<string, number>().betweenBounds({ $lte: "ads" }); }
new AVLTree<string, number>().executeOnEveryNode((tree: AVLTree<string, number>) => null);
}
@@ -0,0 +1,36 @@
namespace adoneTests.collection.BinarySearchTree {
const {
collection: {
BinarySearchTree
}
} = adone;
type BinarySearchTree<K = any, V = any> = adone.collection.BinarySearchTree<K, V>;
new BinarySearchTree();
new BinarySearchTree({});
new BinarySearchTree<string, number>({ checkValueEquality: (a: number, b: number) => a === b });
new BinarySearchTree<string, number>({ compareKeys: (a: string, b: string) => a.length - b.length });
new BinarySearchTree<string, number>({ parent: new BinarySearchTree<string, number>() });
new BinarySearchTree<string, number>({ unique: true });
new BinarySearchTree<string, number>({ value: 123 });
{ const a: BinarySearchTree<string, number> = new BinarySearchTree<string, number>().getMaxKeyDescendant(); }
{ const a: string = new BinarySearchTree<string, number>().getMaxKey(); }
{ const a: BinarySearchTree<string, number> = new BinarySearchTree<string, number>().getMinKeyDescendant(); }
{ const a: string = new BinarySearchTree<string, number>().getMinKey(); }
new BinarySearchTree<string, number>().checkAllNodesFullfillCondition((key: string, value: number) => null);
new BinarySearchTree<string, number>().checkIsBST();
{ const a: number = new BinarySearchTree<string, number>().getNumberOfKeys(); }
new BinarySearchTree<string, number>().insert("asd", 123);
{ const a: number[] = new BinarySearchTree<string, number>().search("asd"); }
{ const a: number[] = new BinarySearchTree<string, number>().betweenBounds({ $gt: "" }); }
{ const a: number[] = new BinarySearchTree<string, number>().betweenBounds({ $lt: "" }); }
{ const a: number[] = new BinarySearchTree<string, number>().betweenBounds({ $lte: "" }); }
{ const a: number[] = new BinarySearchTree<string, number>().betweenBounds({ $gte: "" }); }
new BinarySearchTree<string, number>().delete("key");
new BinarySearchTree<string, number>().delete("key", 123);
new BinarySearchTree<string, number>().executeOnEveryNode((tree: BinarySearchTree<string, number>) => null);
new BinarySearchTree<string, number>().prettyPrint();
new BinarySearchTree<string, number>().prettyPrint(true);
new BinarySearchTree<string, number>().prettyPrint(true, " ");
}
@@ -0,0 +1,42 @@
namespace adoneTests.collection.BufferList {
const {
collection: {
BufferList
}
} = adone;
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);
}
@@ -0,0 +1,561 @@
namespace adoneTests.collection.ByteArray {
const {
collection: {
ByteArray
}
} = adone;
new ByteArray();
new ByteArray(10);
new ByteArray(10, true);
const buffer = new ByteArray();
buffer.woffset === 2;
buffer.roffset === 3;
buffer.noAssert === true;
buffer.buffer.writeUInt8(0, 0);
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;
}
}
}
@@ -0,0 +1,14 @@
namespace adoneTests.collection.DefaultMap {
const {
collection: {
DefaultMap
}
} = adone;
type DefaultMap<K = any, V = any> = adone.collection.DefaultMap<K, V>;
new DefaultMap();
{ const a: DefaultMap<string, number> = new DefaultMap(undefined, [["1", 2]]); }
{ const a: DefaultMap<string, number> = new DefaultMap((key: string) => 123); }
{ const a: DefaultMap<string, number> = new DefaultMap({ a: 123 }); }
}
@@ -0,0 +1,21 @@
namespace adoneTests.collection.FastLRU {
const {
collection: {
FastLRU
}
} = adone;
new FastLRU();
new FastLRU(100);
new FastLRU<string, number>(100, { dispose: (key: string, value: number) => null });
{ const a: number = new FastLRU().size; }
{ const a: number | undefined = new FastLRU<string, number>().get("key"); }
new FastLRU<string, number>().set("key", 123);
{ const a: boolean = new FastLRU<string, number>().delete("key"); }
{ const a: boolean = new FastLRU<string, number>().has("key"); }
{ const a: string[] = [...new FastLRU<string, number>().keys()]; }
{ const a: number[] = [...new FastLRU<string, number>().values()]; }
{ const a: number[] = [...new FastLRU<string, number>().values()]; }
{ const a: Array<[string, number]> = [...new FastLRU<string, number>().entries()]; }
new FastLRU<string, number>().clear();
}
@@ -0,0 +1,123 @@
namespace adoneTests.collection.LinkedList {
const {
collection: {
LinkedList
}
} = adone;
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<number>().push(10);
a.next;
a.prev;
const b: number = a.value;
}
namespace pop {
const a: number | undefined = new LinkedList<number>().pop();
}
namespace shift {
const a: number | undefined = new LinkedList<number>().shift();
}
namespace unshift {
const a = new LinkedList<string>().unshift("hello");
a.next;
a.prev;
const b: string = a.value;
}
namespace pushNode {
const a = new LinkedList<string>();
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<string>();
const node = a.unshift("10");
a.removeNode(node);
}
namespace clear {
new LinkedList().clear();
new LinkedList().clear(true);
}
namespace toArray {
const a = new LinkedList<number>();
const b: number[] = a.toArray();
}
namespace front {
const a = new LinkedList<number>();
const b: number = a.front;
}
namespace back {
const a = new LinkedList<number>();
const b: number = a.back;
}
namespace iterating {
const a = new LinkedList<string>();
for (const b of a) {
const i: string = b;
}
const c = new LinkedList<number>();
for (const b of c) {
const i: number = b;
}
}
namespace nextNode {
const a = new LinkedList<string>();
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<number>();
const f = (a: number, idx: number) => `${a}${idx}`;
const b = a.map(f);
const c: string = b.front;
}
namespace forEach {
const a = new LinkedList<number>();
a.forEach((a: number, b: number) => {
const c = a + b;
});
}
namespace static {
const a: number = LinkedList.DEFAULT_LENGTH;
}
}
@@ -0,0 +1,67 @@
namespace adoneTests.collection.LRU {
const {
collection: {
LRU
}
} = adone;
type LRU = adone.collection.LRU;
new LRU();
new LRU(100);
new LRU({});
new LRU({ max: 100 });
new LRU<string, number>({ dispose: (key: string, value: number) => null });
new LRU<string, number>({ maxAge: 100 });
new LRU<string, number>({ noDisposeOnSet: false });
new LRU<string, number>({ stale: true });
{ const a: number = new LRU<string, number>().max; }
{ new LRU<string, number>().max = 100; }
{ const a: boolean = new LRU<string, number>().allowStale; }
{ new LRU<string, number>().allowStale = false; }
{ const a: number = new LRU<string, number>().maxAge; }
{ new LRU<string, number>().maxAge = 100; }
{ const a: (v: number, k: string) => number = new LRU<string, number>().lengthCalculator; }
{ new LRU<string, number>().lengthCalculator = () => 123; }
{ const a: number = new LRU<string, number>().length; }
{ const a: number = new LRU<string, number>().itemCount; }
new LRU<string, number>().rforEach((value: number, key: string) => null);
new LRU<string, number>().rforEach(function (value: number, key: string) {
const b: number = this.a;
}, { a: 1 });
new LRU<string, number>().forEach((value: number, key: string) => null);
new LRU<string, number>().forEach(function (value: number, key: string) {
const b: number = this.a;
}, { a: 1 });
{ const a: string[] = new LRU<string, number>().keys(); }
{ const a: number[] = new LRU<string, number>().values(); }
new LRU<string, number>().reset();
{
const a: Array<adone.collection.I.LRU.SerializedEntry<string, number>> = new LRU<string, number>().dump();
const [b] = a;
{ const c: number = b.e; }
{ const c: string = b.key; }
{ const c: number = b.value; }
}
{
const a: adone.collection.LinkedList<adone.collection.I.LRU.Entry<string, number>> = new LRU<string, number>().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<string, number>().inspect(); }
{ const a: string = new LRU<string, number>().inspect({}); }
{ const a: boolean = new LRU<string, number>().set("asd", 13); }
{ const a: boolean = new LRU<string, number>().set("asd", 13, 100500); }
{ const a: boolean = new LRU<string, number>().has("asd"); }
{ const a: number | undefined = new LRU<string, number>().get("asd"); }
{ const a: number | undefined = new LRU<string, number>().peek("asd"); }
{ const a: adone.collection.I.LRU.Entry<string, number> = new LRU<string, number>().pop(); }
new LRU<string, number>().del("asd");
new LRU<string, number>().load(new LRU<string, number>().dump());
new LRU<string, number>().prune();
}
@@ -0,0 +1,21 @@
namespace adoneTests.collection.MapCache {
const {
collection: {
MapCache
}
} = adone;
new MapCache();
new MapCache().has("hello");
new MapCache().get("hello");
new MapCache().set("hello", "world");
new MapCache().delete("hello");
new MapCache().clear();
{
const a = new MapCache<string>();
a.set("a", "b");
a.get("a").charCodeAt(20);
}
}
@@ -0,0 +1,21 @@
namespace adoneTests.collection.NSCache {
const {
collection: {
NSCache
}
} = adone;
new NSCache(10, ["a", "b", "c"]);
new NSCache(10, ["a", "b", "c"]).resize(100);
new NSCache(10, ["a", "b", "c"]).set("a", "b", "c");
new NSCache(10, ["a", "b", "c"]).get("a", "b");
new NSCache(10, ["a", "b", "c"]).has("a", "b");
new NSCache(10, ["a", "b", "c"]).delete("a", "b");
new NSCache(10, ["a", "b", "c"]).clear();
{
const a = new NSCache<string>(10, ["a", "b", "c"]);
a.set("a", "b", "c");
a.get("a", "b").charCodeAt(100);
}
}
@@ -0,0 +1,36 @@
namespace adoneTests.collection.PriorityQueue {
const {
collection: {
PriorityQueue
}
} = adone;
type PriorityQueue<T = any> = adone.collection.PriorityQueue<T>;
{ const a: boolean = new PriorityQueue().empty; }
{ const a: number = new PriorityQueue().length; }
new PriorityQueue();
new PriorityQueue({});
new PriorityQueue<number>({
compare(a: number, b: number) {
return a - b;
}
});
new PriorityQueue<string>({
priority(a: string, b: string) {
return a.length - b.length;
}
});
{ const a: PriorityQueue<string> = new PriorityQueue<string>().clone(); }
{ const a: PriorityQueue<string> = new PriorityQueue<string>().push("123"); }
{ const a: string | undefined = new PriorityQueue<string>().pop(); }
{ const a: PriorityQueue<string> = new PriorityQueue<string>().delete("123"); }
{ const a: PriorityQueue<string> = new PriorityQueue<string>().delete("123"); }
{ const a: string = new PriorityQueue<string>().replace("123"); }
{ const a: string = new PriorityQueue<string>().pushpop("123"); }
{ const a: string[] = new PriorityQueue<string>().toArray(); }
{ const a: PriorityQueue<string> = PriorityQueue.from(["1"]); }
{ const a: PriorityQueue<string> = PriorityQueue.from(["1"], {}); }
{ const a: PriorityQueue<string> = PriorityQueue.from(["1"], { compare: (a: string, b: string) => a.length - b.length }); }
{ const a: PriorityQueue<string> = PriorityQueue.from(["1"], { priority: (a: string, b: string) => a.length - b.length }); }
}
@@ -0,0 +1,17 @@
namespace adoneTests.collection.Queue {
const {
collection: {
Queue
}
} = adone;
type Queue = adone.collection.Queue;
new Queue();
{ const a: Queue = new Queue().push(123).push(123); }
{ const a: number | undefined = new Queue<number>().push(123).pop(); }
{ const a: string | undefined = new Queue<number, string>().push(123).pop(); }
{ const a: boolean = new Queue().full; }
{ const a: number = new Queue().length; }
{ const a: boolean = new Queue().empty; }
}
@@ -0,0 +1,48 @@
namespace adoneTests.collection.RedBlackTree {
const {
collection: {
RedBlackTree
}
} = adone;
type RedBlackTree<K = any, V = any> = adone.collection.RedBlackTree<K, V>;
type RedBlackTreeIterator<K = any, V = any> = adone.collection.I.RedBlackTree.Iterator<K, V>;
type RedBlackTreeNode<K = any, V = any> = adone.collection.I.RedBlackTree.Node<K, V>;
new RedBlackTree();
new RedBlackTree<string, number>((a: string, b: string) => a.length - b.length);
new RedBlackTree<string, number>(undefined, new RedBlackTree());
{ const a: string[] = new RedBlackTree<string, number>().keys; }
{ const a: number[] = new RedBlackTree<string, number>().values; }
{ const a: number = new RedBlackTree<string, number>().length; }
{
const a: RedBlackTreeIterator<string, number> = new RedBlackTree<string, number>().begin;
{ const b: boolean = a.valid; }
{ const b: RedBlackTreeNode<string, number> | 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<string, number> = a.tree; }
{ const b: RedBlackTreeIterator<string, number> = a.clone(); }
{ const b: RedBlackTree<string, number> = a.remove(); }
a.next();
{ const b: RedBlackTree<string, number> = a.update(333); }
a.prev();
}
{ const a: RedBlackTreeIterator<string, number> = new RedBlackTree<string, number>().end; }
{ const a: RedBlackTree<string, number> = new RedBlackTree<string, number>().insert("123", 456); }
{ const a: number = new RedBlackTree<string, number>().forEach((key: string, value: number) => value); }
{ const a: number = new RedBlackTree<string, number>().forEach((key: string, value: number) => value, "1"); }
{ const a: number = new RedBlackTree<string, number>().forEach((key: string, value: number) => value, "1", "2"); }
{ const a: RedBlackTreeIterator<string, number> = new RedBlackTree<string, number>().at(1); }
{ const a: RedBlackTreeIterator<string, number> = new RedBlackTree<string, number>().ge("1"); }
{ const a: RedBlackTreeIterator<string, number> = new RedBlackTree<string, number>().gt("1"); }
{ const a: RedBlackTreeIterator<string, number> = new RedBlackTree<string, number>().lt("1"); }
{ const a: RedBlackTreeIterator<string, number> = new RedBlackTree<string, number>().le("1"); }
{ const a: RedBlackTreeIterator<string, number> | null = new RedBlackTree<string, number>().find("1"); }
{ const a: RedBlackTree<string, number> = new RedBlackTree<string, number>().remove("1"); }
{ const a: RedBlackTree<string, number> = new RedBlackTree<string, number>().remove("1"); }
{ const a: number | undefined = new RedBlackTree<string, number>().get("1"); }
}
@@ -0,0 +1,17 @@
namespace adoneTests.collection.RefcountedCache {
const {
collection: {
RefcountedCache
}
} = adone;
new RefcountedCache();
new RefcountedCache().ref("a");
new RefcountedCache().unref("a");
new RefcountedCache().references("a") === 5;
{
const a = new RefcountedCache<string>();
a.get("b").charCodeAt(100);
}
}
@@ -0,0 +1,26 @@
namespace adoneTests.collection.Set {
const {
collection: {
Set
}
} = adone;
new Set().add("a");
new Set().has("a");
new Set().delete("a");
new Set().get("a");
new Set().has("a") === true;
new Set().only();
new Set().size === 5;
{
const a = new Set<number>();
a.add(1);
a.has(2);
a.delete(2);
a.get(2); // ???
a.only() === 5;
a.size === 5;
}
}
@@ -0,0 +1,16 @@
namespace adoneTests.collection.Stack {
const {
collection: {
Stack
}
} = adone;
type Stack<T = any> = adone.collection.Stack<T>;
{ const a: boolean = new Stack().empty; }
{ const a: number = new Stack<number>().top; }
{ const a: Stack<number> = new Stack<number>().push(123); }
{ const a: number | undefined = new Stack<number>().pop(); }
{ const a: number[] = [...new Stack<number>()]; }
{ const a: Stack<number> = Stack.from([1, 2, 3]); }
}
@@ -0,0 +1,22 @@
namespace adoneTests.collection.TimedoutMap {
const {
collection: {
TimedoutMap
}
} = adone;
type TimedoutMap<K = any, V = any> = adone.collection.TimedoutMap<K, V>;
new TimedoutMap();
new TimedoutMap(1000);
new TimedoutMap<string, number>(1000, (key: string) => null);
{
const a: TimedoutMap<string, number> = new TimedoutMap<string, number>().forEach((value: number, key: string) => null);
}
{
const a: TimedoutMap<string, number> = new TimedoutMap<string, number>().forEach(function (value: number, key: string) {
const a: number = this.a;
}, { a: 1 });
}
{ const a: boolean = new TimedoutMap<string, number>().delete("123"); }
}
+273
View File
@@ -570,4 +570,277 @@ namespace dataTests {
bson.decode(bson.encode({ a: 1 }), { promoteLongs: false }).a;
bson.decode(bson.encode({ a: 1 }), { promoteValues: true }).a;
}
namespace protobuf {
const {
protobuf
} = data;
protobuf.create("hello");
protobuf.create(Buffer.from("hello"));
protobuf.create({});
protobuf.create({}, {});
namespace schema {
const {
schema
} = protobuf;
const s = schema.parse("hello");
s.syntax;
s.package;
if (!adone.is.null(s.package)) {
const c: string = s.package;
}
s.imports[0].charCodeAt(100);
namespace enums {
const [a] = s.enums;
a.name.charCodeAt(100);
a.values;
a.options;
}
namespace message {
const [msg] = s.messages;
msg.name;
{
const [a] = msg.enums;
a.name;
a.options;
a.values;
}
{
const [a] = msg.extends;
a.name;
a.message;
}
{
const [a] = msg.messages;
a.name;
a.enums;
a.extends;
a.messages;
a.fields;
a.extensions;
}
{
const [a] = msg.fields;
if (!adone.is.null(a.name)) {
a.name.charCodeAt(100);
}
if (!adone.is.null(a.type)) {
a.type.charCodeAt(100);
}
a.tag === 3;
if (!adone.is.null(a.map)) {
a.map.from.charCodeAt(100);
a.map.to.charCodeAt(100);
}
if (!adone.is.null(a.oneof)) {
a.oneof.charCodeAt(100);
}
a.required === false;
a.repeated === true;
a.options;
}
if (!adone.is.null(msg.extensions)) {
msg.extensions.from === 2;
msg.extensions.to === 3;
}
}
s.options;
s.extends[0].message;
s.extends[0].name;
if (!adone.is.nil(s.services)) {
const [svc] = s.services;
svc.name.charCodeAt(100);
svc.options;
const [m] = svc.methods;
m.name.charCodeAt(100);
if (!adone.is.null(m.input_type)) {
m.input_type.charCodeAt(100);
}
if (!adone.is.null(m.output_type)) {
m.output_type.charCodeAt(100);
}
m.client_streaming === true;
m.server_streaming === true;
m.options;
}
}
}
namespace base32 {
const {
base32
} = data;
base32.charmap("asd");
base32.charmap("asd", {});
base32.rfc4648.alphabet.charCodeAt(0);
base32.rfc4648.charmap["X"] === 2;
base32.crockford.alphabet.charCodeAt(0);
base32.crockford.charmap["X"] === 2;
base32.base32hex.alphabet.charCodeAt(0);
base32.base32hex.charmap["X"] === 2;
namespace decoder {
const {
Decoder
} = base32;
new Decoder();
new Decoder({
type: "base32hex"
});
new Decoder({
type: "crockford"
});
new Decoder({
type: "rfc4648"
});
new Decoder({
type: "rfc4648",
charmap: {}
});
const d = new Decoder();
d.write("asd").write("aa");
{ const a: Buffer = d.finalize(); }
{ const a: Buffer = d.finalize("c"); }
}
namespace encoder {
const {
Encoder
} = base32;
new Encoder();
new Encoder({
type: "base32hex"
});
new Encoder({
type: "crockford"
});
new Encoder({
type: "rfc4648"
});
new Encoder({
type: "rfc4648",
alphabet: "a"
});
const e = new Encoder();
e.write(Buffer.from("b")).write(Buffer.from("a"));
{ const a: string = e.finalize(); }
{ const a: string = e.finalize(Buffer.from("c")); }
}
base32.encode(Buffer.from("hello")).charCodeAt(100);
base32.encode(Buffer.from("hello"), {
type: "rfc4648"
}).charCodeAt(100);
base32.encode(Buffer.from("hello"), {
type: "crockford"
}).charCodeAt(100);
base32.encode(Buffer.from("hello"), {
type: "base32hex"
}).charCodeAt(100);
base32.encode(Buffer.from("hello"), {
type: "base32hex",
alphabet: "asd"
}).charCodeAt(100);
base32.decode("asd").writeUInt8(100, 0);
base32.decode("asd", {
type: "base32hex"
}).writeUInt8(100, 0);
base32.decode("asd", {
type: "crockford"
}).writeUInt8(100, 0);
base32.decode("asd", {
type: "rfc4648"
}).writeUInt8(100, 0);
base32.decode("asd", {
type: "rfc4648",
charmap: {}
}).writeUInt8(100, 0);
}
namespace basex {
const {
basex
} = data;
const d = basex("abc");
const a: Buffer = d.decode("str");
const b: string = d.encode(Buffer.from("hello"));
const c: Buffer = d.decodeUnsafe("hello");
}
namespace base58 {
const {
base58
} = data;
const a: Buffer = base58.decode("str");
const b: string = base58.encode(Buffer.from("hello"));
const c: Buffer = base58.decodeUnsafe("hello");
}
namespace base64url {
const {
base64url
} = data;
base64url.unescape("a").charCodeAt(100);
base64url.escape("a").charCodeAt(100);
base64url.encode("a").charCodeAt(100);
base64url.encode(Buffer.from("a")).charCodeAt(100);
base64url.encode(Buffer.from("a"), {}).charCodeAt(100);
base64url.encode(Buffer.from("a"), {
encoding: "utf8"
}).charCodeAt(100);
base64url.decode("a").charCodeAt(100);
base64url.decode("a", { buffer: true }).writeUInt8(0, 0);
base64url.decode("a", { encoding: "utf8" }).charCodeAt(100);
}
namespace varint {
const {
varint
} = data;
varint.encode(12)[0];
varint.encode(12, [])[0];
varint.encode(12, [], 1)[0];
varint.decode(Buffer.from("hello")) === 5;
varint.decode(Buffer.from("hello"), 2) === 5;
varint.encodingLength(100500) === 5;
}
namespace varintSigned {
const {
varintSigned
} = data;
varintSigned.encode(12)[0];
varintSigned.encode(12, [])[0];
varintSigned.encode(12, [], 1)[0];
varintSigned.decode(Buffer.from("hello")) === 5;
varintSigned.decode(Buffer.from("hello"), 2) === 5;
varintSigned.encodingLength(100500) === 5;
}
}
+206
View File
@@ -0,0 +1,206 @@
namespace adoneTests.fake {
const {
fake
} = adone;
{ const a: string = fake.address.zipCode(); }
{ const a: string = fake.address.zipCode('###'); }
{ const a: string = fake.address.city(); }
{ const a: string = fake.address.city(0); }
{ const a: string = fake.address.cityPrefix(); }
{ const a: string = fake.address.citySuffix(); }
{ const a: string = fake.address.streetName(); }
{ const a: string = fake.address.streetAddress(); }
{ const a: string = fake.address.streetAddress(false); }
{ const a: string = fake.address.streetSuffix(); }
{ const a: string = fake.address.streetPrefix(); }
{ const a: string = fake.address.secondaryAddress(); }
{ const a: string = fake.address.county(); }
{ const a: string = fake.address.country(); }
{ const a: string = fake.address.countryCode(); }
{ const a: string = fake.address.state(); }
{ const a: string = fake.address.state(false); }
{ const a: string = fake.address.stateAbbr(); }
{ const a: string = fake.address.latitude(); }
{ const a: string = fake.address.longitude(); }
{ const a: string = fake.commerce.color(); }
{ const a: string = fake.commerce.department(); }
{ const a: string = fake.commerce.productName(); }
{ const a: string = fake.commerce.price(); }
{ const a: string = fake.commerce.price(0, 0, 0, '#'); }
{ const a: string = fake.commerce.productAdjective(); }
{ const a: string = fake.commerce.productMaterial(); }
{ const a: string = fake.commerce.product(); }
{ const a: string[] = fake.company.suffixes(); }
{ const a: string = fake.company.companyName(); }
{ const a: string = fake.company.companyName(0); }
{ const a: string = fake.company.companySuffix(); }
{ const a: string = fake.company.catchPhrase(); }
{ const a: string = fake.company.bs(); }
{ const a: string = fake.company.catchPhraseAdjective(); }
{ const a: string = fake.company.catchPhraseDescriptor(); }
{ const a: string = fake.company.catchPhraseNoun(); }
{ const a: string = fake.company.bsAdjective(); }
{ const a: string = fake.company.bsBuzz(); }
{ const a: string = fake.company.bsNoun(); }
{ const a: string = fake.database.column(); }
{ const a: string = fake.database.type(); }
{ const a: string = fake.database.collation(); }
{ const a: string = fake.database.engine(); }
{ const a: Date = fake.date.past(); }
{ const a: Date = fake.date.future(); }
{ const a: Date = fake.date.between('foo', 'bar'); }
{ const a: Date = fake.date.between(new Date(), new Date()); }
{ const a: Date = fake.date.recent(); }
{ const a: Date = fake.date.recent(100); }
{ const a: Date = fake.date.soon(); }
{ const a: Date = fake.date.soon(30); }
{ const a: string = fake.date.month(); }
{ const a: string = fake.date.month({
abbr: true,
context: true
}); }
{ const a: string = fake.date.weekday(); }
{ const a: string = fake.date.weekday({
abbr: true,
context: true
}); }
{ const a: string = fake.finance.account(); }
{ const a: string = fake.finance.account(0); }
{ const a: string = fake.finance.accountName(); }
{ const a: string = fake.finance.mask(); }
{ const a: string = fake.finance.mask(0, false, false); }
{ const a: string = fake.finance.amount(); }
{ const a: string = fake.finance.amount(0, 0, 0, '#'); }
{ const a: string = fake.finance.transactionType(); }
{ const a: string = fake.finance.currencyCode(); }
{ const a: string = fake.finance.currencyName(); }
{ const a: string = fake.finance.currencySymbol(); }
{ const a: string = fake.finance.bitcoinAddress(); }
{ const a: string = fake.finance.ethereumAddress(); }
{ const a: string = fake.finance.iban(); }
{ const a: string = fake.finance.iban(true); }
{ const a: string = fake.finance.bic(); }
{ const a: string = fake.hacker.abbreviation(); }
{ const a: string = fake.hacker.adjective(); }
{ const a: string = fake.hacker.noun(); }
{ const a: string = fake.hacker.verb(); }
{ const a: string = fake.hacker.ingverb(); }
{ const a: string = fake.hacker.phrase(); }
{ const a: string = fake.helpers.randomize(); }
{ const a: number = fake.helpers.randomize([1, 2, 3, 4]); }
{ const a: string = fake.helpers.randomize(['foo', 'bar', 'quux']); }
{ const a: string = fake.helpers.slugify('foo bar quux'); }
{ const a: string = fake.helpers.replaceSymbolWithNumber('foo# bar#'); }
{ const a: string = fake.helpers.replaceSymbols('foo# bar? quux#'); }
{ const a: string[] = fake.helpers.shuffle(['foo', 'bar', 'quux']); }
{ const a: string = fake.helpers.mustache('{{foo}}{{bar}}', {foo: 'x', bar: 'y'}); }
const card = fake.helpers.createCard();
{ const a: string = card.name; }
{ const a: string = card.address.streetA; }
const contextualCard = fake.helpers.contextualCard();
{ const a: string = contextualCard.name; }
{ const a: string = contextualCard.address.suite; }
const userCard = fake.helpers.userCard();
{ const a: string = userCard.name; }
{ const a: string = userCard.address.suite; }
{ const a: string = fake.internet.avatar(); }
{ const a: string = fake.internet.email(); }
{ const a: string = fake.internet.email('foo', 'bar', 'quux'); }
{ const a: string = fake.internet.exampleEmail(); }
{ const a: string = fake.internet.exampleEmail('foo', 'bar'); }
{ const a: string = fake.internet.protocol(); }
{ const a: string = fake.internet.url(); }
{ const a: string = fake.internet.domainName(); }
{ const a: string = fake.internet.domainSuffix(); }
{ const a: string = fake.internet.domainWord(); }
{ const a: string = fake.internet.ip(); }
{ const a: string = fake.internet.userAgent(); }
{ const a: string = fake.internet.color(); }
{ const a: string = fake.internet.color(0, 0, 0); }
{ const a: string = fake.internet.mac(); }
{ const a: string = fake.internet.password(); }
{ const a: string = fake.internet.password(0, false, '#', 'foo'); }
{ const a: string = fake.lorem.word(); }
{ const a: string = fake.lorem.words(); }
{ const a: string = fake.lorem.words(0); }
{ const a: string = fake.lorem.sentence(); }
{ const a: string = fake.lorem.sentence(0, 0); }
{ const a: string = fake.lorem.slug(); }
{ const a: string = fake.lorem.slug(0); }
{ const a: string = fake.lorem.sentences(); }
{ const a: string = fake.lorem.sentences(0); }
{ const a: string = fake.lorem.paragraph(); }
{ const a: string = fake.lorem.paragraph(0); }
{ const a: string = fake.lorem.paragraphs(); }
{ const a: string = fake.lorem.paragraphs(0, ''); }
{ const a: string = fake.lorem.text(); }
{ const a: string = fake.lorem.text(0); }
{ const a: string = fake.lorem.lines(); }
{ const a: string = fake.lorem.lines(0); }
{ const a: string = fake.name.firstName(); }
{ const a: string = fake.name.firstName(0); }
{ const a: string = fake.name.lastName(); }
{ const a: string = fake.name.lastName(0); }
{ const a: string = fake.name.findName(); }
{ const a: string = fake.name.findName('', '', 0); }
{ const a: string = fake.name.jobTitle(); }
{ const a: string = fake.name.prefix(); }
{ const a: string = fake.name.suffix(); }
{ const a: string = fake.name.title(); }
{ const a: string = fake.name.jobDescriptor(); }
{ const a: string = fake.name.jobArea(); }
{ const a: string = fake.name.jobType(); }
{ const a: string = fake.phone.phoneNumber(); }
{ const a: string = fake.phone.phoneNumber('#'); }
{ const a: string = fake.phone.phoneNumberFormat(); }
{ const a: string = fake.phone.phoneNumberFormat(0); }
{ const a: string = fake.phone.phoneFormats(); }
{ const a: number = fake.random.number(); }
{ const a: number = fake.random.number(0); }
{ const a: number = fake.random.number({
min: 0,
max: 0,
precision: 0
}); }
{ const a: string = fake.random.arrayElement(); }
{ const a: string = fake.random.arrayElement(['foo', 'bar', 'quux']); }
{ const a: string = fake.random.objectElement(); }
{ const a: string = fake.random.objectElement({foo: 'bar', field: 'foo'}); }
{ const a: string = fake.random.uuid(); }
{ const a: boolean = fake.random.boolean(); }
{ const a: string = fake.random.word(); }
{ const a: string = fake.random.word("noun"); }
{ const a: string = fake.random.words(); }
{ const a: string = fake.random.words(0); }
{ const a: string = fake.random.image(); }
{ const a: string = fake.random.locale(); }
{ const a: string = fake.random.alphaNumeric(); }
{ const a: string = fake.random.alphaNumeric(0); }
{ const a: string = fake.random.hexaDecimal(); }
{ const a: string = fake.random.hexaDecimal(3); }
{ const a: string = fake.system.fileName("foo", "bar"); }
{ const a: string = fake.system.commonFileName("foo", "bar"); }
{ const a: string = fake.system.mimeType(); }
{ const a: string = fake.system.commonFileType(); }
{ const a: string = fake.system.commonFileExt(); }
{ const a: string = fake.system.fileType(); }
{ const a: string = fake.system.fileExt("foo"); }
{ const a: string = fake.system.directoryPath(); }
{ const a: string = fake.system.filePath(); }
{ const a: string = fake.system.semver(); }
}
+14 -2
View File
@@ -133,8 +133,20 @@ namespace isTests {
}
}
{ const a: boolean = is.dotfile("abc"); }
{ const a: boolean = is.function(() => { }); }
{ const a: boolean = is.asyncFunction(async () => { }); }
{
const a: boolean = is.function(() => { });
const b: any = 2;
if (is.function(b)) {
b();
}
}
{
const a: boolean = is.asyncFunction(async () => { });
const b: any = 2;
if (is.asyncFunction(b)) {
b().then(() => {});
}
}
{
const a: boolean = is.promise({});
const b: any = 2;
+41 -2
View File
@@ -22,6 +22,7 @@
"files": [
"index.d.ts",
"adone.d.ts",
"glosses/fake.d.ts",
"glosses/math/index.d.ts",
"glosses/math/matrix.d.ts",
"glosses/math/simd.d.ts",
@@ -32,7 +33,26 @@
"glosses/promise.d.ts",
"glosses/shani.d.ts",
"glosses/shani-global.d.ts",
"glosses/collections.d.ts",
"glosses/collections/index.d.ts",
"glosses/collections/array_set.d.ts",
"glosses/collections/async_queue.d.ts",
"glosses/collections/avl_tree.d.ts",
"glosses/collections/binary_search_tree.d.ts",
"glosses/collections/buffer_list.d.ts",
"glosses/collections/byte_array.d.ts",
"glosses/collections/default_map.d.ts",
"glosses/collections/fast_lru.d.ts",
"glosses/collections/linked_list.d.ts",
"glosses/collections/lru.d.ts",
"glosses/collections/map_cache.d.ts",
"glosses/collections/ns_cache.d.ts",
"glosses/collections/priority_queue.d.ts",
"glosses/collections/queue.d.ts",
"glosses/collections/rb_tree.d.ts",
"glosses/collections/refcounted_cache.d.ts",
"glosses/collections/set.d.ts",
"glosses/collections/stack.d.ts",
"glosses/collections/timedout_map.d.ts",
"glosses/events.d.ts",
"glosses/fs.d.ts",
"glosses/is.d.ts",
@@ -46,7 +66,27 @@
"adone-tests.ts",
"test/index.ts",
"test/index-import.ts",
"test/glosses/fake.ts",
"test/glosses/application.ts",
"test/glosses/collections/array_set.ts",
"test/glosses/collections/async_queue.ts",
"test/glosses/collections/avl_tree.ts",
"test/glosses/collections/binary_search_tree.ts",
"test/glosses/collections/buffer_list.ts",
"test/glosses/collections/byte_array.ts",
"test/glosses/collections/default_map.ts",
"test/glosses/collections/fast_lru.ts",
"test/glosses/collections/linked_list.ts",
"test/glosses/collections/lru.ts",
"test/glosses/collections/map_cache.ts",
"test/glosses/collections/ns_cache.ts",
"test/glosses/collections/priority_queue.ts",
"test/glosses/collections/queue.ts",
"test/glosses/collections/rb_tree.ts",
"test/glosses/collections/refcounted_cache.ts",
"test/glosses/collections/set.ts",
"test/glosses/collections/stack.ts",
"test/glosses/collections/timedout_map.ts",
"test/glosses/math/index.ts",
"test/glosses/math/matrix.ts",
"test/glosses/math/simd.ts",
@@ -57,7 +97,6 @@
"test/glosses/promise.ts",
"test/glosses/shani.ts",
"test/glosses/shani-global.ts",
"test/glosses/collections.ts",
"test/glosses/events.ts",
"test/glosses/fs.ts",
"test/glosses/is.ts",
+1 -1
View File
@@ -1124,7 +1124,7 @@ ships.on('fetched', (collection, response) => {
User.collection()
.orderBy('-name')
.fetch()
.then((users: Bookshelf.Collection<User>) => {
.then((users: Bookshelf.Collection<Bookshelf.Model<User>>) => {
console.log(users);
})
}
+1 -1
View File
@@ -250,7 +250,7 @@ declare namespace Bookshelf {
detach(options?: SyncOptions): BlueBird<any>;
fetchOne(options?: CollectionFetchOneOptions): BlueBird<T>;
load(relations: string | string[], options?: SyncOptions): BlueBird<Collection<T>>;
orderBy(column: string, order?: SortOrder): T;
orderBy(column: string, order?: SortOrder): Collection<T>;
// Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[])
query(): Knex.QueryBuilder;
+9 -1
View File
@@ -1,4 +1,4 @@
import { Chart, ChartData } from 'chart.js';
import { Chart, ChartData, Point } from 'chart.js';
// alternative:
// import chartjs = require('chart.js');
@@ -65,3 +65,11 @@ if (chart.chartArea) {
console.log(chart.chartArea.bottom);
console.log(chart.chartArea.left);
}
// http://www.chartjs.org/docs/latest/configuration/tooltip.html#position-modes
Chart.Tooltip.positioners.custom = (elements: any[], eventPosition: Point) => {
return {
x: eventPosition.x,
y: eventPosition.y + 10
};
};
+15 -1
View File
@@ -44,6 +44,9 @@ declare class Chart {
static controllers: {
[key: string]: any;
};
// Tooltip Static Options
static Tooltip: Chart.ChartTooltipsStaticConfiguration;
}
declare class PluginServiceStatic {
register(plugin: PluginServiceRegistrationOptions): void;
@@ -268,13 +271,19 @@ declare namespace Chart {
callbacks?: ChartTooltipCallback;
filter?(item: ChartTooltipItem): boolean;
itemSort?(itemA: ChartTooltipItem, itemB: ChartTooltipItem): number;
position?: "average"|"nearest";
position?: string;
caretPadding?: number;
displayColors?: boolean;
borderColor?: ChartColor;
borderWidth?: number;
}
interface ChartTooltipsStaticConfiguration {
positioners: {[mode: string]: ChartTooltipPositioner};
}
type ChartTooltipPositioner = (elements: any[], eventPosition: Point) => Point;
interface ChartHoverOptions {
mode?: string;
animationDuration?: number;
@@ -561,6 +570,11 @@ declare namespace Chart {
pointLabels?: PointLabelOptions;
ticks?: TickOptions;
}
interface Point {
x: number;
y: number;
}
}
export = Chart;
+8
View File
@@ -14,3 +14,11 @@ const result = commentJson.parse(`
// comment at the bottom
`);
const str = commentJson.stringify(result);
const numericallyIndexed = commentJson.stringify(result, (key, value) => {
return key && Number.isInteger(Number(key))
? value
: undefined;
});
const whiteListed = commentJson.stringify(result, ['a', 1]);
+16 -1
View File
@@ -4,5 +4,20 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export type Reviver = (k: number | string, v: any) => any;
/**
* Converts a JavaScript Object Notation (JSON) string into an object.
* @param json A valid JSON string.
* @param reviver A function that transforms the results. This function is called for each member of the object.
* @param removes_comments If true, the comments won't be maintained, which is often used when we want to get a clean object.
* If a member contains nested objects, the nested objects are transformed before the parent object is.
*/
export function parse(json: string, reviver?: Reviver, removes_comments?: boolean): any;
export function stringify(value: any, replacer?: any, space?: string | number): string;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
* @param value A JavaScript value, usually an object or array, to be converted.
* @param replacer A function that transforms the results or an array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
*/
export function stringify(value: any, replacer?: ((key: string, value: any) => any) | Array<number | string> | null, space?: string | number): string;
+4
View File
@@ -3,6 +3,7 @@
// Definitions by: Roman Korneev <https://github.com/RWander>
// Forrest Bice <https://github.com/forrestbice>
// James Donald <https://github.com/jndonald3>
// Alberto Vasquez <https://github.com/albertovasquez>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -39,6 +40,9 @@ declare namespace c {
// Return the sources for the configurations
getConfigSources(): IConfigSource[];
// Returns a new deep copy of the current config object, or any part of the config if provided.
toObject(config?: any): any;
/**
* This allows module developers to attach their configurations onto
+22 -9
View File
@@ -11,28 +11,41 @@ const init: RequestInit = {};
let p1: Promise<Blob> = d3Fetch.blob(url);
p1 = d3Fetch.blob(url, init);
let p2: Promise<ArrayBuffer> = d3Fetch.buffer(url);
p2 = d3Fetch.buffer(url, init);
let p3: Promise<HTMLImageElement> = d3Fetch.image(url);
p3 = d3Fetch.image(url, init);
const imageProperties = {
width: '300px',
height: '500px'
};
p3 = d3Fetch.image(url, imageProperties);
let p4: Promise<any> = d3Fetch.json(url);
p4 = d3Fetch.json(url, init);
let p5: Promise<MyType> = d3Fetch.json<MyType>(url);
p5 = d3Fetch.json<MyType>(url, init);
let myString: Promise<string>;
myString = d3Fetch.text(url);
myString = d3Fetch.text(url, init);
const parseRow = (d: {}) => {
const myType: MyType = { foo: 'foo' };
const parseRow = (rawRow: DSVRowString, index: number, columns: string[]): (MyType | undefined | null) => {
const myType: MyType | null = rawRow['foo'] ? { foo: rawRow['foo'] + '+ bar' } : null;
return myType;
};
let promise1: Promise<DSVParsedArray<DSVRowString>>;
let promise2: Promise<DSVParsedArray<MyType>>;
promise2 = d3Fetch.csv<MyType>(url);
promise2 = d3Fetch.csv<MyType>(url, init);
promise1 = d3Fetch.csv(url);
promise1 = d3Fetch.csv(url, init);
promise2 = d3Fetch.csv<MyType>(url, parseRow);
promise2 = d3Fetch.csv<MyType>(url, init, parseRow);
promise2 = d3Fetch.dsv<MyType>(';', url);
promise2 = d3Fetch.dsv<MyType>(';', url, init);
promise1 = d3Fetch.dsv(';', url);
promise1 = d3Fetch.dsv(';', url, init);
promise2 = d3Fetch.dsv<MyType>(';', url, parseRow);
promise2 = d3Fetch.dsv<MyType>(';', url, init, parseRow);
promise2 = d3Fetch.tsv<MyType>(url);
promise2 = d3Fetch.tsv<MyType>(url, init);
promise1 = d3Fetch.tsv(url);
promise1 = d3Fetch.tsv(url, init);
promise2 = d3Fetch.tsv<MyType>(url, parseRow);
promise2 = d3Fetch.tsv<MyType>(url, init, parseRow);
+210 -16
View File
@@ -3,40 +3,234 @@
// Definitions by: Hugues Stefanski <https://github.com/ledragon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// Last module patch version validated against: 1.0.1
import { DSVParsedArray, DSVRowString, DSVRowAny } from 'd3-dsv';
/** Fetches the binary file at the specified input URL as a Blob. If init is specified, it is passed along to the underlying call to fetch. */
/**
* Fetches the binary file at the specified input URL and returns it as a Promise of a Blob.
* If init is specified, it is passed along to the underlying call to fetch.
*
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
export function blob(url: string, init?: RequestInit): Promise<Blob>;
/** Fetches the binary file at the specified input URL as an ArrayBuffer. If init is specified, it is passed along to the underlying call to fetch. */
/**
* Fetches the binary file at the specified input URL and returns it as a Promise of an ArrayBuffer.
* If init is specified, it is passed along to the underlying call to fetch.
*
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
export function buffer(url: string, init?: RequestInit): Promise<ArrayBuffer>;
/** Equivalent to d3.dsv with the comma character as the delimiter. */
export function csv<ParsedRow extends DSVRowAny>(
/**
* Fetches the CSV file at the specified input URL and returns
* a promise of an array of objects representing the parsed rows. The values of the properties of the parsed row
* objects are represented as strings.
*
* If init is specified, it is passed along to the underlying call to fetch.
*
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
export function csv(
url: string,
init?: RequestInit,
row?: (d: DSVRowAny) => ParsedRow
): Promise<DSVParsedArray<DSVRowString>>;
/**
* Fetches the CSV file at the specified input URL and returns
* a promise of an array of objects representing the parsed rows.
*
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.csvParse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
*
* @param url A valid URL string.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
* the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined,
* the row is skipped and will be ommitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function csv<ParsedRow extends DSVRowAny>(
url: string,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
/**
* Fetches the CSV file at the specified input URL and returns
* a promise of an array of objects representing the parsed rows.
*
* The init object is passed along to the underlying call to fetch.
*
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.csvParse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
*
* @param url A valid URL string.
* @param init An request initialization object.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
* the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined,
* the row is skipped and will be ommitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function csv<ParsedRow extends DSVRowAny>(
url: string,
init: RequestInit,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
/** Fetches the DSV file at the specified input URL. */
export function dsv<ParsedRow extends DSVRowAny>(
/**
* Fetches the DSV file with the specified delimiter character at the specified input URL and returns
* a promise of an array of objects representing the parsed rows. The values of the properties of the parsed row
* objects are represented as strings.
*
* If init is specified, it is passed along to the underlying call to fetch.
*
* @param delimiter The delimiter character used in the DSV file to be fetched.
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
export function dsv(
delimiter: string,
url: string,
init?: RequestInit,
row?: (d: DSVRowAny) => ParsedRow
): Promise<DSVParsedArray<DSVRowString>>;
/**
* Fetches the DSV file with the specified delimiter character at the specified input URL and returns
* a promise of an array of objects representing the parsed rows.
*
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.parse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
*
* @param delimiter The delimiter character used in the DSV file to be fetched.
* @param url A valid URL string.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
* the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined,
* the row is skipped and will be ommitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function dsv<ParsedRow extends DSVRowAny>(
delimiter: string,
url: string,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
/**
* Fetches the DSV file with the specified delimiter character at the specified input URL and returns
* a promise of an array of objects representing the parsed rows.
*
* The init object is passed along to the underlying call to fetch.
*
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.parse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
*
* @param delimiter The delimiter character used in the DSV file to be fetched.
* @param url A valid URL string.
* @param init An request initialization object.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
* the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined,
* the row is skipped and will be ommitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function dsv<ParsedRow extends DSVRowAny>(
delimiter: string,
url: string,
init: RequestInit,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
/** Fetches the image at the specified input URL. If init is specified, it is passed along to the underlying call to fetch. */
export function image(url: string, init?: RequestInit): Promise<HTMLImageElement>;
/**
* Fetches the image at the specified input URL and returns a promise of an HTML image element.
*
* If init is specified, sets any additional properties on the image before loading.
*
* @param url A valid URL string.
* @param init An optional object of image properties to set.
*/
export function image(url: string, init?: {[key: string]: any}): Promise<HTMLImageElement>;
/** Fetches the json file at the specified input URL. If init is specified, it is passed along to the underlying call to fetch. */
export function json(url: string, init?: RequestInit): Promise<{}>;
/**
* Fetches the json file at the specified input URL and returns it as a Promise of a parsed JSON object.
*
* If init is specified, it is passed along to the underlying call to fetch.
*
* The generic parameter describes the type of the object parsed from the returned JSON.
*
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
export function json<ParsedJSONObject extends any>(url: string, init?: RequestInit): Promise<ParsedJSONObject>;
/** Fetches the text file at the specified input URL. If init is specified, it is passed along to the underlying call to fetch. */
/**
* Fetches the text file at the specified input URL and returns it as a Promise of a string.
*
* If init is specified, it is passed along to the underlying call to fetch.
*
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
export function text(url: string, init?: RequestInit): Promise<string>;
/** Equivalent to d3.dsv with the tab character as the delimiter. */
export function tsv<ParsedRow extends DSVRowAny>(
/**
* Fetches the TSV file at the specified input URL and returns
* a promise of an array of objects representing the parsed rows.
*
* If init is specified, it is passed along to the underlying call to fetch.
*
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
export function tsv(
url: string,
init?: RequestInit,
row?: (d: DSVRowAny) => ParsedRow
): Promise<DSVParsedArray<DSVRowString>>;
/**
* Fetches the TSV file at the specified input URL and returns
* a promise of an array of objects representing the parsed rows. The values of the properties of the parsed row
* objects are represented as strings.
*
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.tsvParse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
*
* @param url A valid URL string.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
* the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined,
* the row is skipped and will be ommitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function tsv<ParsedRow extends DSVRowAny>(
url: string,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
/**
* Fetches the TSV file at the specified input URL and returns
* a promise of an array of objects representing the parsed rows.
*
* The init object is passed along to the underlying call to fetch.
*
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.tsvParse for details.
*
* The generic parameter describes the type of the object representation of a parsed row.
*
* @param url A valid URL string.
* @param init An request initialization object.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
* the index (i) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined,
* the row is skipped and will be ommitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
export function tsv<ParsedRow extends DSVRowAny>(
url: string,
init: RequestInit,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
): Promise<DSVParsedArray<ParsedRow>>;
+7 -1
View File
@@ -1 +1,7 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json",
"rules": {
"unified-signatures": false,
"no-unnecessary-generics": false
}
}
+32 -14
View File
@@ -89,10 +89,11 @@ const body5: d3Selection.Selection<HTMLBodyElement, BodyDatum, null, undefined>
// d3Selection.select<HTMLBodyElement, BodyDatum>(baseTypeEl.node()!); // fails as baseTypeEl.node() is not of type HTMLBodyElement
// test, when it is not certain, whether an element of the type to be selected exists
let maybeSVG1: d3Selection.Selection<SVGSVGElement | null, any, HTMLElement, undefined> = d3Selection.select<SVGSVGElement, any>('svg');
let maybeSVG1: d3Selection.Selection<SVGSVGElement | null, any, HTMLElement, undefined>;
maybeSVG1 = d3Selection.select<SVGSVGElement | null, any>('svg');
let maybeSVG2: d3Selection.Selection<SVGSVGElement | null, any, null, undefined>;
// maybeSVG2 = d3Selection.select<SVGSVGElement, any>(maybeSVG1.node()); // fails with strict function types
maybeSVG2 = d3Selection.select<SVGSVGElement | null, any>(maybeSVG1.node());
// fails, as node type mismatches selection type
@@ -144,8 +145,7 @@ const xSVGCircleElementList: NodeListOf<SVGCircleElement> = document.querySelect
const circleSelection: d3Selection.Selection<SVGCircleElement, any, null, undefined> = d3Selection.selectAll(xSVGCircleElementList);
// selectAll(...) accepts HTMLCollection, HTMLCollectionOf<...> argument
const documentLinks: d3Selection.Selection<HTMLAnchorElement | HTMLAreaElement, any, null, undefined> = d3Selection.selectAll(document.links);
const documentLinks: d3Selection.Selection<HTMLAnchorElement | HTMLAreaElement, any, null, undefined> = d3Selection.selectAll<HTMLAnchorElement | HTMLAreaElement, any>(document.links);
// ---------------------------------------------------------------------------------------
// Tests of Sub-Selection Functions
@@ -166,12 +166,13 @@ let firstG: d3Selection.Selection<SVGGElement, SVGDatum, HTMLElement, any> = svg
// firstG = svgEl.select<SVGSVGElement>('svg'); // fails, element type of SVGSVGElement provided, but SVGGElement expexted on left-hand side (silly test to begin with)
// test, when it is not certain, whether an element of the type to be selected exists
let maybeG: d3Selection.Selection<SVGGElement | null, SVGDatum, HTMLElement, any> = svgEl.select<SVGGElement>('g');
let maybeG: d3Selection.Selection<SVGGElement | null, SVGDatum, HTMLElement, any>;
// maybeG = svgEl.select<SVGGElement>('g'); // fails, with strictFunctionTypes
maybeG = svgEl.select<SVGGElement | null>('g');
// Using select(...) sub-selection with a selector function argument.
function svgGroupSelector(this: SVGSVGElement, d: SVGDatum, i: number, groups: SVGSVGElement[]): SVGGElement {
function svgGroupSelector(this: SVGSVGElement, d: SVGDatum, i: number, groups: SVGSVGElement[] | ArrayLike<SVGSVGElement>): SVGGElement {
return this.querySelector('g')!; // this-type compatible with group element-type to which the selector function will be appplied
}
@@ -215,13 +216,14 @@ emptySubSelection = svgEl.selectAll(undefined);
// Using selectAll(...) sub-selection with a string argument.
let elementsUnknownData: d3Selection.Selection<d3Selection.BaseType, any, SVGSVGElement, SVGDatum> = svgEl.selectAll('g');
let elementsUnknownData: d3Selection.Selection<SVGGElement, any, SVGSVGElement, SVGDatum> = svgEl.selectAll<SVGGElement, any>('g');
// let elementsAndDataUnknown: d3Selection.Selection<d3Selection.BaseType, any, SVGSVGElement, SVGDatum> = svgEl.selectAll('g'); // fails with strictFunctionTypes
let gElementsOldData: d3Selection.Selection<SVGGElement, CircleDatum, SVGSVGElement, SVGDatum> = svgEl.selectAll<SVGGElement, CircleDatum>('g');
// gElementsOldData = svgEl.selectAll('g'); // fails default type parameters of selectAll for group element type and datum type do not match
// Using selectAll(...) sub-selection with a selector function argument.
function svgGroupSelectorAll(this: SVGSVGElement, d: SVGDatum, i: number, groups: SVGSVGElement[]): NodeListOf<SVGGElement> {
function svgGroupSelectorAll(this: SVGSVGElement, d: SVGDatum, i: number, groups: SVGSVGElement[] | d3Selection.ArrayLike<SVGSVGElement>): NodeListOf<SVGGElement> {
return this.querySelectorAll('g'); // this-type compatible with group element-type to which the selector function will be appplied
}
@@ -774,7 +776,7 @@ nRow = td2.data(); // flattened matrix (Array[16] of number)
// Tests of Alternative DOM Manipulation
// ---------------------------------------------------------------------------------------
// append(...) and creator(...) ----------------------------------------------------------
// append(...), creator(...) and create(...) ---------------------------------------------
// without append<...> typing returned selection has group element of type BaseType
let newDiv: d3Selection.Selection<d3Selection.BaseType, BodyDatum, HTMLElement, any>;
@@ -805,6 +807,12 @@ newDiv2 = body.append(function(d, i, g) {
// return this.ownerDocument.createElement('a'); // fails, HTMLDivElement expected by inference, HTMLAnchorElement returned
// });
// create a detached element
let detachedDiv: d3Selection.Selection<HTMLDivElement, undefined, null, undefined>;
detachedDiv = d3Selection.create<HTMLDivElement>('div');
// insert(...) ---------------------------------------------------------------------------
// without insert<...> typing returned selection has group element of type BaseType
@@ -847,6 +855,18 @@ newParagraph2 = body.insert(typeValueFunction, 'p.second-paragraph');
newParagraph2 = body.insert(typeValueFunction, beforeValueFunction);
newParagraph2 = body.insert(typeValueFunction);
// clone(...) ----------------------------------------------------------------------------
let clonedParagraph: d3Selection.Selection<HTMLParagraphElement, BodyDatum, HTMLElement, any>;
// shallow clone
clonedParagraph = newParagraph2.clone();
// deep clone
newParagraph.append('span');
clonedParagraph = newParagraph2.clone(true);
// sort(...) -----------------------------------------------------------------------------
// NB: Return new selection of same type
@@ -925,14 +945,14 @@ circles = circles.call(enforceMinRadius, 40); // check chaining return type by r
// on(...) -------------------------------------------------------------------------------
let listener: undefined | ((this: HTMLBodyElement, datum: BodyDatum, index: number, group: HTMLBodyElement[] | ArrayLike<HTMLBodyElement>) => void);
let listener: undefined | ((this: HTMLBodyElement, datum: BodyDatum, index: number, group: HTMLBodyElement[] | d3Selection.ArrayLike<HTMLBodyElement>) => void);
body = body.on('click', function(d, i, g) {
const that: HTMLBodyElement = this;
// const that2: SVGElement = this; // fails, type mismatch
const datum: BodyDatum = d;
const index: number = i;
const group: HTMLBodyElement[] | ArrayLike<HTMLBodyElement> = g;
const group: HTMLBodyElement[] | d3Selection.ArrayLike<HTMLBodyElement> = g;
console.log('onclick print body background color: ', this.bgColor); // HTMLBodyElement
console.log('onclick print "foo" datum property: ', d.foo); // BodyDatum type
});
@@ -988,13 +1008,11 @@ interface SuccessEvent {
}
const successEvent = { type: 'wonEuro2016', team: 'Island' };
let customListener: (this: HTMLBodyElement, finalOpponent: string) => string;
customListener = finalOpponent => {
function customListener(this: HTMLBodyElement | null, finalOpponent: string): string {
const e = <SuccessEvent> d3Selection.event;
return `${e.team} defeated ${finalOpponent} in the EURO 2016 Cup. Who would have thought!!!`;
};
}
const resultText: string = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales');
+20 -2
View File
@@ -1,9 +1,9 @@
// Type definitions for D3JS d3-selection module 1.2
// Type definitions for D3JS d3-selection module 1.3
// Project: https://github.com/d3/d3-selection/
// Definitions by: Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Last module patch version validated against: 1.2.0
// Last module patch version validated against: 1.3.0
// --------------------------------------------------------------------------
// Shared Type Definitions and Interfaces
@@ -532,6 +532,15 @@ export interface Selection<GElement extends BaseType, Datum, PElement extends Ba
*/
remove(): this;
/**
* Inserts clones of the selected elements immediately following the selected elements and returns a selection of the newly
* added clones. If deep is true, the descendant nodes of the selected elements will be cloned as well. Otherwise, only the elements
* themselves will be cloned.
*
* @param deep Perform deep cloning if this flag is set to true.
*/
clone(deep?: boolean): Selection<GElement, Datum, PElement, PDatum>;
/**
* Returns a new selection merging this selection with the specified other selection.
* The returned selection has the same number of groups and the same parents as this selection.
@@ -1103,6 +1112,15 @@ export function window(DOMNode: Window | Document | Element): Window;
// for explicit bound-context dependent use
// ---------------------------------------------------------------------------
/**
* Given the specified element name, returns a single-element selection containing
* a detached element of the given name in the current document.
*
* @param name Tag name of the element to be added. See "namespace" for details on supported namespace prefixes,
* such as for SVG elements.
*/
export function create<NewGElement extends Element>(name: string): Selection<NewGElement, undefined, null, undefined>;
/**
* Given the specified element name, returns a function which creates an element of the given name,
* assuming that "this" is the parent element.
+2 -2
View File
@@ -8,7 +8,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
@@ -22,4 +22,4 @@
"index.d.ts",
"d3-selection-tests.ts"
]
}
}
+4 -3
View File
@@ -4,7 +4,7 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Diff2Html {
export interface Options {
inputFormat?: string;
outputFormat?: string;
@@ -53,10 +53,11 @@ declare namespace Diff2Html {
checksumAfter?: string;
mode?: string;
}
export interface Diff2Html {
getJsonFromDiff(input: string, configuration?: Options): Result;
getJsonFromDiff(input: string, configuration?: Options): Result[];
getPrettyHtml(input: any, configuration?: Options): string;
getPrettyHtmlFromJson(input: Result[], configuration?: Options): string;
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ declare namespace echarts {
function dispose(target: ECharts | HTMLDivElement | HTMLCanvasElement): void;
function getInstanceByDom(target: HTMLDivElement | HTMLCanvasElement): void;
function getInstanceByDom(target: HTMLDivElement | HTMLCanvasElement): ECharts;
function registerMap(mapName: string, geoJson: Object, specialAreas?: Object): void;
+2 -2
View File
@@ -15,7 +15,7 @@ export as namespace ed2curve;
export function convertPublicKey(publicKey: SignKeyPair["publicKey"]): BoxKeyPair["publicKey"] | null;
/** Converts Ed25519 secret key to Curve25519 secret key. */
export function convertSecretKey(secretKey: SignKeyPair["secretKey"]): BoxKeyPair["secretKey"] | null;
export function convertSecretKey(secretKey: SignKeyPair["secretKey"]): BoxKeyPair["secretKey"];
/** Converts Ed25519 key pair to Curve25519 key pair. */
export function convertKeyPair(keyPair: SignKeyPair): BoxKeyPair;
export function convertKeyPair(keyPair: SignKeyPair): BoxKeyPair | null;
@@ -10,7 +10,8 @@ const graphqlOption: graphqlHTTP.OptionsObj = {
schema: schema,
formatError: (error: Error) => ({
message: error.message
})
}),
extensions: (args) => { }
};
const graphqlOptionRequest = (request: express.Request): graphqlHTTP.OptionsObj => ({
@@ -23,7 +24,8 @@ const graphqlOptionRequestAsync = async (request: express.Request): Promise<grap
return {
graphiql: true,
schema: await Promise.resolve(schema),
context: request.session
context: request.session,
extensions: async (args) => { }
};
};
+15
View File
@@ -3,6 +3,7 @@
// Definitions by: Isman Usoh <https://github.com/isman-usoh>
// Nitin Tutlani <https://github.com/nitintutlani>
// Daniel Fader <https://github.com/hubel>
// Ehsan Ziya <https://github.com/zya>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -48,8 +49,22 @@ declare namespace graphqlHTTP {
* A boolean to optionally enable GraphiQL mode.
*/
graphiql?: boolean,
/**
* An optional function for adding additional metadata to the GraphQL response as a key-value object.
* The result will be added to "extensions" field in the resulting JSON.
*/
extensions?: ((args: ExtenstionsArgs) => any) | ((args: ExtenstionsArgs) => Promise<any>);
};
interface ExtenstionsArgs {
document: object,
variables: object,
operationName: any,
result: object
}
type Middleware = (request: Request, response: Response) => void;
}
+5 -2
View File
@@ -1,6 +1,9 @@
// Type definitions for express-session 1.15
// Project: https://www.npmjs.org/package/express-session
// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi>, Jacob Bogers <https://github.com/jacobbogers>, Naoto Yokoyama <https://github.com/builtinnya>
// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi>
// Jacob Bogers <https://github.com/jacobbogers>
// Naoto Yokoyama <https://github.com/builtinnya>
// Ryan Cannon <https://github.com/ry7n>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -51,7 +54,7 @@ declare function session(options?: session.SessionOptions): express.RequestHandl
declare namespace session {
interface SessionOptions {
secret: string;
secret: string | string[];
name?: string;
store?: Store | MemoryStore;
cookie?: express.CookieOptions;
+1 -1
View File
@@ -75,7 +75,7 @@ export interface FtpServerOptions {
/**
* If this is set, the server will allow explicit TLS authentication. Value should be a dictionary which is suitable as the options argument of tls.createServer.
*/
tlsOptions?: tls.TlsOptions;
tlsOptions?: tls.TlsServerOptions;
/**
* If this is set to true, and tlsOptions is also set, then the server will not allow logins over non-secure connections.
* Default false
+1 -1
View File
@@ -80,7 +80,7 @@ declare namespace got {
type GotStreamFn = (url: GotUrl, options?: GotOptions<string | null>) => GotEmitter & nodeStream.Duplex;
type GotUrl = string | http.RequestOptions | URL;
type GotUrl = string | http.RequestOptions | Url;
interface GotBodyOptions<E extends string | null> extends GotOptions<E> {
body?: string | Buffer | nodeStream.Readable;
+8
View File
@@ -0,0 +1,8 @@
import * as React from "react";
import { Flex, Box } from "grid-styled";
const Layout = () => (
<Flex m={4}>
<Box px={3} py={2} />
</Flex>
);
+76
View File
@@ -0,0 +1,76 @@
// Type definitions for grid-styled 3.0
// Project: https://github.com/jxnblk/grid-styled
// Definitions by: Anton Vasin <https://github.com/antonvasin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
export type Diff<T extends string, U extends string> = ({ [P in T]: P } &
{ [P in U]: never } & { [x: string]: never })[T];
export type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>;
import { ComponentClass } from "react";
import { StyledComponentClass } from "styled-components";
export type ResponsiveProp = number | string | Array<string | number>;
export interface CommonProps {
width: ResponsiveProp;
fontSize: ResponsiveProp;
color: ResponsiveProp;
bg: ResponsiveProp;
m: ResponsiveProp;
mt: ResponsiveProp;
mr: ResponsiveProp;
mb: ResponsiveProp;
ml: ResponsiveProp;
mx: ResponsiveProp;
my: ResponsiveProp;
p: ResponsiveProp;
pt: ResponsiveProp;
pr: ResponsiveProp;
pb: ResponsiveProp;
pl: ResponsiveProp;
px: ResponsiveProp;
py: ResponsiveProp;
theme: any;
}
export interface BoxProps
extends Omit<React.HTMLProps<HTMLDivElement>, "width" | "wrap" | "is"> {
flex: ResponsiveProp;
order: ResponsiveProp;
is: string | ComponentClass<any>;
}
export interface FlexProps extends BoxProps {
wrap: ResponsiveProp | boolean;
direction: ResponsiveProp | boolean;
align: ResponsiveProp | boolean;
justify: ResponsiveProp | boolean;
column: boolean;
}
export type BoxComponent = StyledComponentClass<
Partial<CommonProps & BoxProps>,
any
>;
export type FlexComponent = StyledComponentClass<
Partial<CommonProps & FlexProps>,
any
>;
export interface Theme {
breakpoints: string[];
space: number[];
fontSizes: number[];
}
export const Box: BoxComponent;
export const Flex: FlexComponent;
export const theme: Theme;
export type DivProps = Omit<React.HTMLProps<HTMLDivElement>, "ref"> & {
innerRef: (el: HTMLDivElement) => any;
};
export const div: ComponentClass<DivProps>;
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"styled-components": "^3.1.6"
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"jsx": "react"
},
"files": [
"index.d.ts",
"grid-styled-tests.tsx"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -43,7 +43,7 @@ declare namespace proxy {
target?: string;
forward?: string;
agent?: http.Agent;
ssl?: tls.TlsOptions;
ssl?: tls.TlsServerOptions;
ws?: boolean;
xfwd?: boolean;
secure?: boolean;
+10
View File
@@ -548,6 +548,16 @@ declare namespace jest {
// Relevant parts of Jasmine's API are below so they can be changed and removed over time.
// This file can't reference jasmine.d.ts since the globals aren't compatible.
declare function spyOn(object: any, method: string): jasmine.Spy;
/**
* If you call the function pending anywhere in the spec body,
* no matter the expectations, the spec will be marked pending.
*/
declare function pending(reason?: string): void;
/**
* Fails a test when called within one.
*/
declare function fail(error?: any): void;
declare namespace jasmine {
let DEFAULT_TIMEOUT_INTERVAL: number;
function clock(): Clock;
+1 -1
View File
@@ -31,7 +31,7 @@ interface JQueryColorpickerOptions {
closeOnOutside?: boolean;
color?: string;
colorFormat?: string;
disabled: boolean;
disabled?: boolean;
draggable?: boolean;
duration?: string;
format?: string;
@@ -70,6 +70,9 @@ colorpicker.colorpicker("destroy");
colorpicker.colorpicker("setColor", "#deadbeef");
colorpicker.colorpicker("option", "disabled", true);
// check if all options are optional
let defaultColorpicker = $("<input type=\"text\"/>").colorpicker({});
// example plugins provided
$.colorpicker.parts["memory"] = function (inst) {
+2
View File
@@ -314,6 +314,7 @@ interface KnockoutUtils {
triggerEvent(element: any, eventType: any): void;
unwrapObservable<T>(value: KnockoutObservable<T> | T): T;
unwrapObservable<T>(value: KnockoutObservableArray<T> | T[]): T[];
// NOT PART OF THE MINIFIED API SURFACE (ONLY IN knockout-{version}.debug.js) https://github.com/SteveSanderson/knockout/issues/670
// forceRefresh(node: any): void;
@@ -454,6 +455,7 @@ interface KnockoutStatic {
renderTemplate(template: Function, viewModel: any, options?: any, target?: any, renderMode?: any): any;
renderTemplate(template: string, viewModel: any, options?: any, target?: any, renderMode?: any): any;
unwrap<T>(value: KnockoutObservable<T> | T): T;
unwrap<T>(value: KnockoutObservableArray<T> | T[]): T[];
computedContext: KnockoutComputedContext;
+44 -1
View File
@@ -52,7 +52,7 @@ export interface ClientOptions {
export interface SearchOptions {
scope?: string;
filter?: string;
filter?: string | Filter;
attributes?: string[];
sizeLimit?: number;
timeLimit?: number;
@@ -238,3 +238,46 @@ export interface Client extends EventEmitter {
}
export function createClient(options?: ClientOptions): Client;
declare class Filter {
matches(obj: any): boolean;
type: string;
}
export function parseFilter(filterString: string): Filter;
export class EqualityFilter extends Filter {
constructor(options: { attribute: string, value: string })
}
export class PresenceFilter extends Filter {
constructor(options: { attribute: string })
}
export class SubstringFilter extends Filter {
constructor(options: { attribute: string, initial: string, any?: string[], final?: string })
}
export class GreaterThanEqualsFilter extends Filter {
constructor(options: { attribute: string, value: string })
}
export class LessThanEqualsFilter extends Filter {
constructor(options: { attribute: string, value: string })
}
export class AndFilter extends Filter {
constructor(options: { filters: Filter[] })
}
export class OrFilter extends Filter {
constructor(options: { filters: Filter[] })
}
export class NotFilter extends Filter {
constructor(options: { filter: Filter })
}
export class ApproximateFilter extends Filter {
constructor(options: { attribute: string, value: string })
}
+87 -10
View File
@@ -2,7 +2,7 @@
import ldap = require("ldapjs");
let client = ldap.createClient({
url: 'ldap://127.0.0.1:1389'
url: 'ldap://127.0.0.1:1389'
});
client.bind('cn=root', 'secret', (err: Error): void => {
@@ -10,9 +10,9 @@ client.bind('cn=root', 'secret', (err: Error): void => {
});
let opts: ldap.SearchOptions = {
filter: '(&(l=Seattle)(email=*@foo.com))',
scope: 'sub',
attributes: ['dn', 'sn', 'cn']
filter: '(&(l=Seattle)(email=*@foo.com))',
scope: 'sub',
attributes: ['dn', 'sn', 'cn']
};
client.search('o=example', opts, (err: Error, res: NodeJS.EventEmitter): void => {
@@ -20,12 +20,89 @@ client.search('o=example', opts, (err: Error, res: NodeJS.EventEmitter): void =>
});
let change = new ldap.Change({
operation: 'add',
modification: {
pets: ['cat', 'dog']
}
operation: 'add',
modification: {
pets: ['cat', 'dog']
}
});
client.modify('cn=foo, o=example', change, function(err) {
// nothing
client.modify('cn=foo, o=example', change, function (err) {
// nothing
});
let f = ldap.parseFilter('(objectclass=*)');
f.matches({});
let equalityFilter = new ldap.EqualityFilter({
attribute: 'cn',
value: 'foo'
});
equalityFilter.matches({ cn: 'foo' });
let presenceFilter = new ldap.PresenceFilter({
attribute: 'cn'
});
presenceFilter.matches({ cn: 'foo' });
let substringFilter = new ldap.SubstringFilter({
attribute: 'cn',
initial: 'foo',
any: ['bar'],
final: 'baz'
});
substringFilter.matches({ cn: 'foobigbardogbaz' });
let greaterThanEqualsFilter = new ldap.GreaterThanEqualsFilter({
attribute: 'cn',
value: 'foo',
});
greaterThanEqualsFilter.matches({ cn: 'foobar' });
let lessThanEqualsFilter = new ldap.LessThanEqualsFilter({
attribute: 'cn',
value: 'foo',
});
lessThanEqualsFilter.matches({ cn: 'abc' });
let andFilter = new ldap.AndFilter({
filters: [
new ldap.EqualityFilter({
attribute: 'cn',
value: 'foo'
}),
new ldap.EqualityFilter({
attribute: 'sn',
value: 'bar'
})
]
});
andFilter.matches({ cn: 'foo', sn: 'bar' });
let orFilter = new ldap.OrFilter({
filters: [
new ldap.EqualityFilter({
attribute: 'cn',
value: 'foo'
}),
new ldap.EqualityFilter({
attribute: 'sn',
value: 'bar'
})
]
});
orFilter.matches({ cn: 'foo', sn: 'baz' });
let notFilter = new ldap.NotFilter({
filter: new ldap.EqualityFilter({
attribute: 'cn',
value: 'foo'
})
});
notFilter.matches({ cn: 'bar' });
let approximateFilter = new ldap.ApproximateFilter({
attribute: 'cn',
value: 'foo'
});
approximateFilter.matches({ cn: 'foo' });
+2 -2
View File
@@ -2,7 +2,7 @@ import _ = require("../index");
type GlobalPartial<T> = Partial<T>;
declare module "../index" {
type PartialObject<T> = GlobalPartial<T>;
type Many<T> = T | T[];
type Many<T> = T | ReadonlyArray<T>;
interface LoDashStatic {
/**
* Creates a lodash object which wraps value to enable implicit method chain sequences.
@@ -252,4 +252,4 @@ declare module "../index" {
type LoDashExplicitNillableObjectWrapper<T> = LoDashExplicitWrapper<T | null | undefined>;
type LoDashExplicitNumberArrayWrapper = LoDashExplicitWrapper<number[]>;
type LoDashExplicitStringWrapper = LoDashExplicitWrapper<string>;
}
}
-1
View File
@@ -3,7 +3,6 @@
// Definitions by: Brian Zengel <https://github.com/bczengel>,
// Ilya Mochalov <https://github.com/chrootsu>,
// Stepan Mikhaylyuk <https://github.com/stepancar>,
// Eric L Anderson <https://github.com/ericanderson>,
// AJ Richardson <https://github.com/aj-r>,
// Junyoung Clare Jang <https://github.com/ailrun>,
// e-cloud <https://github.com/e-cloud>,
+84 -103
View File
@@ -3775,77 +3775,75 @@ namespace TestCommit {
// _.prototype.concat
namespace TestConcat {
{
let result: _.LoDashImplicitArrayWrapper<number>;
const numberROA: ReadonlyArray<number> = [0];
result = _(1).concat<number>(2);
result = _(1).concat<number>(2, 3);
result = _(1).concat<number>(2, 3, 4);
_.concat(1); // $ExpectType number[]
_.concat([1]); // $ExpectType number[]
_.concat(numberROA); // $ExpectType number[]
_.concat(1, 2); // $ExpectType number[]
_.concat(1, [1]); // $ExpectType number[]
_.concat(1, [1], numberROA); // $ExpectType number[]
result = _(1).concat(2);
result = _(1).concat(2, 3);
result = _(1).concat(2, 3, 4);
}
_(1).concat(2); // $ExpectType LoDashImplicitWrapper<number[]>
_(1).concat([1]); // $ExpectType LoDashImplicitWrapper<number[]>
_(1).concat([2], numberROA); // $ExpectType LoDashImplicitWrapper<number[]>
_([1]).concat(2); // $ExpectType LoDashImplicitWrapper<number[]>
_(numberROA).concat(numberROA); // $ExpectType LoDashImplicitWrapper<number[]>
_(numberROA).concat(numberROA, numberROA); // $ExpectType LoDashImplicitWrapper<number[]>
{
let result: _.LoDashImplicitArrayWrapper<string>;
_.chain(1).concat(2); // $ExpectType LoDashExplicitWrapper<number[]>
_.chain(1).concat([1]); // $ExpectType LoDashExplicitWrapper<number[]>
_.chain(1).concat([2], numberROA); // $ExpectType LoDashExplicitWrapper<number[]>
_.chain([1]).concat(2); // $ExpectType LoDashExplicitWrapper<number[]>
_.chain(numberROA).concat(numberROA); // $ExpectType LoDashExplicitWrapper<number[]>
_.chain(numberROA).concat(numberROA, numberROA); // $ExpectType LoDashExplicitWrapper<number[]>
result = _(['']).concat<string>(['']);
result = _(['']).concat<string>([''], ['']);
result = _(['']).concat<string>([''], [''], ['']);
const stringROA: ReadonlyArray<string> = [''];
result = _(['']).concat(['']);
result = _(['']).concat([''], ['']);
result = _(['']).concat([''], [''], ['']);
}
_.concat('a'); // $ExpectType string[]
_.concat(['a']); // $ExpectType string[]
_.concat(stringROA); // $ExpectType string[]
_.concat('a', 'b'); // $ExpectType string[]
_.concat('a', ['a']); // $ExpectType string[]
_.concat('a', ['a'], stringROA); // $ExpectType string[]
{
let result: _.LoDashImplicitArrayWrapper<{a: string}>;
_('a').concat('b'); // $ExpectType LoDashImplicitWrapper<string[]>
_('a').concat(['a']); // $ExpectType LoDashImplicitWrapper<string[]>
_('a').concat(['b'], stringROA); // $ExpectType LoDashImplicitWrapper<string[]>
_(['a']).concat('b'); // $ExpectType LoDashImplicitWrapper<string[]>
_(stringROA).concat(stringROA); // $ExpectType LoDashImplicitWrapper<string[]>
_(stringROA).concat(stringROA, stringROA); // $ExpectType LoDashImplicitWrapper<string[]>
result = _({a: ''}).concat<{a: string}>({a: ''});
result = _({a: ''}).concat<{a: string}>({a: ''}, {a: ''});
result = _({a: ''}).concat<{a: string}>({a: ''}, {a: ''}, {a: ''});
_.chain('a').concat('b'); // $ExpectType LoDashExplicitWrapper<string[]>
_.chain('a').concat(['a']); // $ExpectType LoDashExplicitWrapper<string[]>
_.chain('a').concat(['b'], stringROA); // $ExpectType LoDashExplicitWrapper<string[]>
_.chain(['a']).concat('b'); // $ExpectType LoDashExplicitWrapper<string[]>
_.chain(stringROA).concat(stringROA); // $ExpectType LoDashExplicitWrapper<string[]>
_.chain(stringROA).concat(stringROA, stringROA); // $ExpectType LoDashExplicitWrapper<string[]>
result = _({a: ''}).concat({a: ''});
result = _({a: ''}).concat({a: ''}, {a: ''});
result = _({a: ''}).concat({a: ''}, {a: ''}, {a: ''});
}
const abcObject: AbcObject = { a: 1, b: 'foo', c: true };
const objectROA: ReadonlyArray<AbcObject> = [{ a: 1, b: 'foo', c: true }];
{
let result: _.LoDashExplicitArrayWrapper<number>;
_.concat(abcObject); // $ExpectType AbcObject[]
_.concat([abcObject]); // $ExpectType AbcObject[]
_.concat(objectROA); // $ExpectType AbcObject[]
_.concat(abcObject, abcObject); // $ExpectType AbcObject[]
_.concat(abcObject, [abcObject]); // $ExpectType AbcObject[]
_.concat(abcObject, [abcObject], objectROA); // $ExpectType AbcObject[]
result = _(1).chain().concat<number>(2);
result = _(1).chain().concat<number>(2, 3);
result = _(1).chain().concat<number>(2, 3, 4);
_(abcObject).concat(abcObject); // $ExpectType LoDashImplicitWrapper<AbcObject[]>
_(abcObject).concat([abcObject]); // $ExpectType LoDashImplicitWrapper<AbcObject[]>
_(abcObject).concat([abcObject], objectROA); // $ExpectType LoDashImplicitWrapper<AbcObject[]>
_([abcObject]).concat(abcObject); // $ExpectType LoDashImplicitWrapper<AbcObject[]>
_(objectROA).concat(objectROA); // $ExpectType LoDashImplicitWrapper<AbcObject[]>
_(objectROA).concat(objectROA, objectROA); // $ExpectType LoDashImplicitWrapper<AbcObject[]>
result = _(1).chain().concat(2);
result = _(1).chain().concat(2, 3);
result = _(1).chain().concat(2, 3, 4);
}
{
let result: _.LoDashExplicitArrayWrapper<string>;
result = _(['']).chain().concat<string>(['']);
result = _(['']).chain().concat<string>([''], ['']);
result = _(['']).chain().concat<string>([''], [''], ['']);
result = _(['']).chain().concat(['']);
result = _(['']).chain().concat([''], ['']);
result = _(['']).chain().concat([''], [''], ['']);
}
{
let result: _.LoDashExplicitArrayWrapper<{a: string}>;
result = _({a: ''}).chain().concat<{a: string}>({a: ''});
result = _({a: ''}).chain().concat<{a: string}>({a: ''}, {a: ''});
result = _({a: ''}).chain().concat<{a: string}>({a: ''}, {a: ''}, {a: ''});
result = _({a: ''}).chain().concat({a: ''});
result = _({a: ''}).chain().concat({a: ''}, {a: ''});
result = _({a: ''}).chain().concat({a: ''}, {a: ''}, {a: ''});
}
_.chain(abcObject).concat(abcObject); // $ExpectType LoDashExplicitWrapper<AbcObject[]>
_.chain(abcObject).concat([abcObject]); // $ExpectType LoDashExplicitWrapper<AbcObject[]>
_.chain(abcObject).concat([abcObject], objectROA); // $ExpectType LoDashExplicitWrapper<AbcObject[]>
_.chain([abcObject]).concat(abcObject); // $ExpectType LoDashExplicitWrapper<AbcObject[]>
_.chain(objectROA).concat(objectROA); // $ExpectType LoDashExplicitWrapper<AbcObject[]>
_.chain(objectROA).concat(objectROA, objectROA); // $ExpectType LoDashExplicitWrapper<AbcObject[]>
}
// _.prototype.plant
@@ -11802,52 +11800,35 @@ namespace TestOmitBy {
// _.pick
namespace TestPick {
let obj1: AbcObject | null | undefined = anything;
let obj2: AbcObject = anything;
const obj1: AbcObject | null | undefined = anything;
const obj2: AbcObject = anything;
const readonlyArray: ReadonlyArray<string> = ['a', 'b'];
const literalsArray = ['a' as 'a', 'b' as 'b'];
const roLiteralsArray: ReadonlyArray<'a' | 'b'> = literalsArray;
{
let result: Partial<AbcObject>;
_.pick(obj1, 'a'); // $ExpectType PartialDeep<AbcObject>
_.pick(obj1, 0, 'a'); // $ExpectType PartialDeep<AbcObject>
_.pick(obj1, ['b', 1], 0, 'a'); // $ExpectType PartialDeep<AbcObject>
_.pick(obj1, readonlyArray); // $ExpectType PartialDeep<AbcObject>
_.pick(obj2, 'a', 'b'); // $ExpectType Pick<AbcObject, "a" | "b">
_.pick(obj2, literalsArray); // $ExpectType Pick<AbcObject, "a" | "b">
_.pick(obj2, roLiteralsArray); // $ExpectType Pick<AbcObject, "a" | "b">
result = _.pick(obj1, 'a');
result = _.pick(obj1, 0, 'a');
result = _.pick(obj1, ['b', 1], 0, 'a');
}
_(obj1).pick('a'); // $ExpectType LoDashImplicitWrapper<Partial<AbcObject>>
_(obj1).pick(0, 'a'); // $ExpectType LoDashImplicitWrapper<Partial<AbcObject>>
_(obj1).pick(['b', 1], 0, 'a'); // $ExpectType LoDashImplicitWrapper<Partial<AbcObject>>
_(obj1).pick(readonlyArray); // $ExpectType LoDashImplicitWrapper<Partial<AbcObject>>
_(obj2).pick('a', 'b'); // $ExpectType LoDashImplicitWrapper<Pick<AbcObject, "a" | "b">>
_(obj2).pick(literalsArray); // $ExpectType LoDashImplicitWrapper<Pick<AbcObject, "a" | "b">>
_(obj2).pick(roLiteralsArray); // $ExpectType LoDashImplicitWrapper<Pick<AbcObject, "a" | "b">>
{
let result: Pick<AbcObject, 'a' | 'b'>;
result = _.pick(obj2, 'a', 'b');
result = _.pick(obj2, ['a' as 'a', 'b' as 'b']);
}
{
let result: _.LoDashImplicitWrapper<Partial<AbcObject>>;
result = _(obj1).pick('a');
result = _(obj1).pick(0, 'a');
result = _(obj1).pick(['b', 1], 0, 'a');
}
{
let result: _.LoDashImplicitWrapper<Pick<AbcObject, 'a' | 'b'>>;
result = _(obj2).pick('a', 'b');
result = _(obj2).pick(['a' as 'a', 'b' as 'b']);
}
{
let result: _.LoDashExplicitWrapper<Partial<AbcObject>>;
result = _(obj1).chain().pick('a');
result = _(obj1).chain().pick(0, 'a');
result = _(obj1).chain().pick(['b', 1], 0, 'a');
}
{
let result: _.LoDashExplicitWrapper<Pick<AbcObject, 'a' | 'b'>>;
result = _(obj2).chain().pick('a', 'b');
result = _(obj2).chain().pick(['a' as 'a', 'b' as 'b']);
}
_.chain(obj1).pick('a'); // $ExpectType LoDashExplicitWrapper<Partial<AbcObject>>
_.chain(obj1).pick(0, 'a'); // $ExpectType LoDashExplicitWrapper<Partial<AbcObject>>
_.chain(obj1).pick(['b', 1], 0, 'a'); // $ExpectType LoDashExplicitWrapper<Partial<AbcObject>>
_.chain(obj1).pick(readonlyArray); // $ExpectType LoDashExplicitWrapper<Partial<AbcObject>>
_.chain(obj2).pick('a', 'b'); // $ExpectType LoDashExplicitWrapper<Pick<AbcObject, "a" | "b">>
_.chain(obj2).pick(literalsArray); // $ExpectType LoDashExplicitWrapper<Pick<AbcObject, "a" | "b">>
_.chain(obj2).pick(roLiteralsArray); // $ExpectType LoDashExplicitWrapper<Pick<AbcObject, "a" | "b">>
}
// _.pickBy
+1 -1
View File
@@ -287,7 +287,7 @@ declare module 'luxon' {
type Features = {
intl: boolean;
intlTokens: boolean;
timezones: boolean;
zones: boolean;
};
namespace Info {
+3
View File
@@ -78,6 +78,9 @@ i.toString();
/* Info */
Info.months();
Info.weekdays('long');
Info.features().intl;
Info.features().intlTokens;
Info.features().zones;
/* Settings */
Settings.defaultLocale;
+1 -1
View File
@@ -9,7 +9,7 @@ interface Milliseconds {
hours(hours: number): number
days(days: number): number
weeks(weeks: number): number
month(month: number): number
months(months: number): number
years(years: number): number
}
+1 -1
View File
@@ -5,5 +5,5 @@ milliseconds.minutes(2)
milliseconds.hours(3)
milliseconds.days(4)
milliseconds.weeks(5)
milliseconds.month(6)
milliseconds.months(6)
milliseconds.years(7)
+43 -63
View File
@@ -18,6 +18,7 @@
// Hannes Magnusson <https://github.com/Hannes-Magnusson-CK>
// Alberto Schiabel <https://github.com/jkomyno>
// Klaus Meinhardt <https://github.com/ajafff>
// Huw <https://github.com/hoo29>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/** inspector module types */
@@ -113,17 +114,22 @@ declare function clearImmediate(immediateId: any): void;
// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version.
interface NodeRequireFunction {
/* tslint:disable-next-line:callable-types */
/* tslint:disable-next-line:callable-types */
(id: string): any;
}
interface NodeRequire extends NodeRequireFunction {
resolve(id: string): string;
resolve: RequireResolve;
cache: any;
extensions: NodeExtensions;
main: NodeModule | undefined;
}
interface RequireResolve {
(id: string, options?: { paths?: string[]; }): string;
paths(request: string): string[] | null;
}
interface NodeExtensions {
'.js': (m: NodeModule, filename: string) => any;
'.json': (m: NodeModule, filename: string) => any;
@@ -1740,33 +1746,20 @@ declare module "https" {
import * as http from "http";
import { URL } from "url";
export interface ServerOptions {
pfx?: any;
key?: any;
passphrase?: string;
cert?: any;
ca?: any;
crl?: any;
ciphers?: string;
honorCipherOrder?: boolean;
requestCert?: boolean;
rejectUnauthorized?: boolean;
NPNProtocols?: any;
SNICallback?: (servername: string, cb: (err: Error | null, ctx: tls.SecureContext) => void) => void;
secureProtocol?: string;
}
export type ServerOptions = tls.SecureContextOptions & tls.TlsServerOptions;
export interface RequestOptions extends http.RequestOptions {
pfx?: any;
key?: any;
export type RequestOptions = http.RequestOptions & {
rejectUnauthorized?: boolean; // Defaults to true
servername?: string; // SNI TLS Extension
pfx?: string | Buffer | Array<string | Buffer | Object>;
key?: string | Buffer | Array<Buffer | Object>;
passphrase?: string;
cert?: any;
ca?: any;
cert?: string | Buffer | Array<string | Buffer>;
ca?: string | Buffer | Array<string | Buffer>;
ciphers?: string;
rejectUnauthorized?: boolean;
secureProtocol?: string;
servername?: string;
}
clientCertEngine?: string;
secureProtocol?: string; // SSL Method, e.g. SSLv23_method
};
export interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
rejectUnauthorized?: boolean;
@@ -2621,9 +2614,9 @@ declare module "net" {
destroy(err?: any): void;
pause(): this;
resume(): this;
setTimeout(timeout: number, callback?: Function): void;
setNoDelay(noDelay?: boolean): void;
setKeepAlive(enable?: boolean, initialDelay?: number): void;
setTimeout(timeout: number, callback?: Function): this;
setNoDelay(noDelay?: boolean): this;
setKeepAlive(enable?: boolean, initialDelay?: number): this;
address(): { port: number; family: string; address: string; };
unref(): void;
ref(): void;
@@ -3716,7 +3709,7 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: Array<string | Buffer>) => void): void;
export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void;
/**
* Asynchronous readdir(3) - read a directory.
@@ -3745,7 +3738,7 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<Array<string | Buffer>>;
export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string[] | Buffer[]>;
}
/**
@@ -3767,7 +3760,7 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): Array<string | Buffer>;
export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): string[] | Buffer[];
/**
* Asynchronous close(2) - close a file descriptor.
@@ -4839,7 +4832,7 @@ declare module "tls" {
* An array of strings or a Buffer naming possible NPN protocols.
* (Protocols should be ordered by their priority.)
*/
NPNProtocols?: string[] | Buffer,
NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array,
/**
* An array of strings or a Buffer naming possible ALPN protocols.
* (Protocols should be ordered by their priority.) When the server
@@ -4847,7 +4840,7 @@ declare module "tls" {
* precedence over NPN and the server does not send an NPN extension
* to the client.
*/
ALPNProtocols?: string[] | Buffer,
ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array,
/**
* SNICallback(servername, cb) <Function> A function that will be
* called if the client supports SNI TLS extension. Two arguments
@@ -4923,7 +4916,7 @@ declare module "tls" {
* @param callback - callback(err) will be executed with null as err, once the renegotiation
* is successfully completed.
*/
renegotiate(options: TlsOptions, callback: (err: Error | null) => void): any;
renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): any;
/**
* Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512).
* Smaller fragment size decreases buffering latency on the client: large fragments are buffered by
@@ -4966,30 +4959,16 @@ declare module "tls" {
prependOnceListener(event: "secureConnect", listener: () => void): this;
}
export interface TlsOptions {
host?: string;
port?: number;
pfx?: string | Buffer[];
key?: string | string[] | Buffer | any[];
passphrase?: string;
cert?: string | string[] | Buffer | Buffer[];
ca?: string | string[] | Buffer | Buffer[];
crl?: string | string[];
ciphers?: string;
honorCipherOrder?: boolean;
export interface TlsServerOptions extends SecureContextOptions {
clientCertEngine?: string;
handshakeTimeout?: number;
requestCert?: boolean;
rejectUnauthorized?: boolean;
NPNProtocols?: string[] | Buffer;
NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array;
ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array;
SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void;
ecdhCurve?: string;
dhparam?: string | Buffer;
handshakeTimeout?: number;
ALPNProtocols?: string[] | Buffer;
sessionTimeout?: number;
ticketKeys?: Buffer;
sessionIdContext?: string;
secureProtocol?: string;
secureOptions?: number;
}
export interface ConnectionOptions extends SecureContextOptions {
@@ -4998,8 +4977,8 @@ declare module "tls" {
path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored.
socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket
rejectUnauthorized?: boolean; // Defaults to true
NPNProtocols?: Array<string | Buffer>;
ALPNProtocols?: Array<string | Buffer>;
NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array;
ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array;
checkServerIdentity?: typeof checkServerIdentity;
servername?: string; // SNI TLS Extension
session?: Buffer;
@@ -5097,6 +5076,7 @@ declare module "tls" {
ciphers?: string;
honorCipherOrder?: boolean;
ecdhCurve?: string;
clientCertEngine?: string;
crl?: string | Buffer | Array<string | Buffer>;
dhparam?: string | Buffer;
secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options
@@ -5116,7 +5096,7 @@ declare module "tls" {
* Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined.
*/
export function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined;
export function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server;
export function createServer(options: TlsServerOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server;
export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): TLSSocket;
export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
@@ -5400,7 +5380,7 @@ declare module "stream" {
readonly writableLength: number;
constructor(opts?: WritableOptions);
_write(chunk: any, encoding: string, callback: (err?: Error) => void): void;
_writev?(chunks: Array<{chunk: any, encoding: string}>, callback: (err?: Error) => void): void;
_writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void;
_destroy(err: Error, callback: Function): void;
_final(callback: Function): void;
write(chunk: any, cb?: Function): boolean;
@@ -5493,7 +5473,7 @@ declare module "stream" {
readonly writableLength: number;
constructor(opts?: DuplexOptions);
_write(chunk: any, encoding: string, callback: (err?: Error) => void): void;
_writev?(chunks: Array<{chunk: any, encoding: string}>, callback: (err?: Error) => void): void;
_writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void;
_destroy(err: Error, callback: Function): void;
_final(callback: Function): void;
write(chunk: any, cb?: Function): boolean;
@@ -5573,9 +5553,9 @@ declare module "util" {
export function callbackify<T1, T2>(fn: (arg1: T1, arg2: T2) => Promise<void>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2) => Promise<TResult>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, T4>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, T3, T4, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, T4, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, T4, T5>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, T3, T4, T5, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, T4, T5, T6>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void;
@@ -6168,7 +6148,7 @@ declare module "http2" {
}
export interface ServerStreamFileResponseOptions {
statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void|boolean;
statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean;
getTrailers?: (trailers: OutgoingHttpHeaders) => void;
offset?: number;
length?: number;
@@ -6514,7 +6494,7 @@ declare module "http2" {
export type ServerSessionOptions = SessionOptions;
export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { }
export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { }
export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsServerOptions { }
export interface ServerOptions extends ServerSessionOptions {
allowHTTP1?: boolean;
+19
View File
@@ -235,6 +235,25 @@ namespace fs_tests {
});
}
{
let listS: string[];
listS = fs.readdirSync('path');
listS = fs.readdirSync('path', { encoding: 'utf8' });
listS = fs.readdirSync('path', { encoding: null });
listS = fs.readdirSync('path', { encoding: undefined });
listS = fs.readdirSync('path', 'utf8');
listS = fs.readdirSync('path', null);
listS = fs.readdirSync('path', undefined);
let listB: Buffer[];
listB = fs.readdirSync('path', { encoding: 'buffer' });
listB = fs.readdirSync("path", 'buffer');
let enc = 'buffer';
fs.readdirSync('path', { encoding: enc }); // $ExpectType string[] | Buffer[]
fs.readdirSync('path', { }); // $ExpectType string[] | Buffer[]
}
{
fs.mkdtemp('/tmp/foo-', (err, folder) => {
console.log(folder);
+1 -1
View File
@@ -22,4 +22,4 @@
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
}
}
}
+3 -3
View File
@@ -1549,9 +1549,9 @@ declare module "net" {
destroy(): void;
pause(): void;
resume(): void;
setTimeout(timeout: number, callback?: Function): void;
setNoDelay(noDelay?: boolean): void;
setKeepAlive(enable?: boolean, initialDelay?: number): void;
setTimeout(timeout: number, callback?: Function): this;
setNoDelay(noDelay?: boolean): this;
setKeepAlive(enable?: boolean, initialDelay?: number): this;
address(): { port: number; family: string; address: string; };
unref(): void;
ref(): void;
+49 -5
View File
@@ -5,6 +5,7 @@
// Wilco Bakker <https://github.com/WilcoBakker>
// Thomas Bouldin <https://github.com/inlined>
// Sebastian Silbermann <https://github.com/eps1lon>
// Alorel <https://github.com/Alorel>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/************************************************
@@ -2093,9 +2094,9 @@ declare module "net" {
setEncoding(encoding?: string): void;
write(data: any, encoding?: string, callback?: Function): void;
destroy(): void;
setTimeout(timeout: number, callback?: Function): void;
setNoDelay(noDelay?: boolean): void;
setKeepAlive(enable?: boolean, initialDelay?: number): void;
setTimeout(timeout: number, callback?: Function): this;
setNoDelay(noDelay?: boolean): this;
setKeepAlive(enable?: boolean, initialDelay?: number): this;
address(): { port: number; family: string; address: string; };
unref(): void;
ref(): void;
@@ -2595,8 +2596,51 @@ declare module "fs" {
* @returns Returns the created folder path.
*/
export function mkdtempSync(prefix: string): string;
export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void;
export function readdirSync(path: string | Buffer): string[];
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdir(path: string | Buffer, options: { encoding: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdir(path: string | Buffer, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdir(path: string | Buffer, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file.
*/
export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void;
/**
* Synchronous readdir(3) - read a directory.
* @param path A path to a file.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdirSync(path: string | Buffer, options?: { encoding: BufferEncoding | null } | BufferEncoding | null): string[];
/**
* Synchronous readdir(3) - read a directory.
* @param path A path to a file.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdirSync(path: string | Buffer, options: { encoding: "buffer" } | "buffer"): Buffer[];
/**
* Synchronous readdir(3) - read a directory.
* @param path A path to a file.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdirSync(path: string | Buffer, options?: { encoding?: string | null } | string | null): string[] | Buffer[];
export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;
export function closeSync(fd: number): void;
export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void;
+19
View File
@@ -218,6 +218,25 @@ namespace fs_tests {
fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data);
}
{
fs.readdir('foo', (err: any, files: string[]) => {})
fs.readdir('foo', 'utf8', (err: any, files: string[]) => {});
fs.readdir('foo', {encoding: 'utf8'}, (err: any, files: string[]) => {});
fs.readdir('foo', 'buffer', (err: any, files: Buffer[]) => {});
fs.readdir('foo', {encoding: 'buffer'}, (err: any, files: Buffer[]) => {});
let fsStringOut: string[] = fs.readdirSync('utf8');
fsStringOut = fs.readdirSync('foo', 'utf8');
fsStringOut = fs.readdirSync('foo', {encoding: 'utf8'});
let fsBufferOut: Buffer[] = fs.readdirSync('utf8', 'buffer');
fsBufferOut = fs.readdirSync('foo', {encoding: 'buffer'});
let enc = 'buffer';
fs.readdirSync('path', { encoding: enc }); // $ExpectType string[] | Buffer[]
fs.readdirSync('path', { }); // $ExpectType string[] | Buffer[]
}
{
var errno: number;
fs.readFile('testfile', (err, data) => {
+3 -3
View File
@@ -2219,9 +2219,9 @@ declare module "net" {
destroy(err?: any): void;
pause(): this;
resume(): this;
setTimeout(timeout: number, callback?: Function): void;
setNoDelay(noDelay?: boolean): void;
setKeepAlive(enable?: boolean, initialDelay?: number): void;
setTimeout(timeout: number, callback?: Function): this;
setNoDelay(noDelay?: boolean): this;
setKeepAlive(enable?: boolean, initialDelay?: number): this;
address(): { port: number; family: string; address: string; };
unref(): void;
ref(): void;
+45 -66
View File
@@ -1,4 +1,4 @@
// Type definitions for Node.js 8.5.x
// Type definitions for Node.js 8.9.x
// Project: http://nodejs.org/
// Definitions by: Microsoft TypeScript <http://typescriptlang.org>
// DefinitelyTyped <https://github.com/DefinitelyTyped/DefinitelyTyped>
@@ -17,7 +17,9 @@
// Sebastian Silbermann <https://github.com/eps1lon>
// Hannes Magnusson <https://github.com/Hannes-Magnusson-CK>
// Alberto Schiabel <https://github.com/jkomyno>
// Huw <https://github.com/hoo29>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/** inspector module types */
/// <reference path="./inspector.d.ts" />
@@ -111,17 +113,22 @@ declare function clearImmediate(immediateId: any): void;
// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version.
interface NodeRequireFunction {
/* tslint:disable-next-line:callable-types */
/* tslint:disable-next-line:callable-types */
(id: string): any;
}
interface NodeRequire extends NodeRequireFunction {
resolve(id: string): string;
resolve: RequireResolve;
cache: any;
extensions: NodeExtensions;
main: NodeModule | undefined;
}
interface RequireResolve {
(id: string, options?: { paths?: string[]; }): string;
paths(request: string): string[] | null;
}
interface NodeExtensions {
'.js': (m: NodeModule, filename: string) => any;
'.json': (m: NodeModule, filename: string) => any;
@@ -1728,33 +1735,20 @@ declare module "https" {
import * as http from "http";
import { URL } from "url";
export interface ServerOptions {
pfx?: any;
key?: any;
passphrase?: string;
cert?: any;
ca?: any;
crl?: any;
ciphers?: string;
honorCipherOrder?: boolean;
requestCert?: boolean;
rejectUnauthorized?: boolean;
NPNProtocols?: any;
SNICallback?: (servername: string, cb: (err: Error | null, ctx: tls.SecureContext) => void) => void;
secureProtocol?: string;
}
export type ServerOptions = tls.SecureContextOptions & tls.TlsServerOptions;
export interface RequestOptions extends http.RequestOptions {
pfx?: any;
key?: any;
passphrase?: string;
cert?: any;
ca?: any;
ciphers?: string;
rejectUnauthorized?: boolean;
secureProtocol?: string;
servername?: string;
}
// see https://nodejs.org/docs/latest-v8.x/api/https.html#https_https_request_options_callback
type extendedRequestKeys = "pfx" |
"key" |
"passphrase" |
"cert" |
"ca" |
"ciphers" |
"rejectUnauthorized" |
"secureProtocol" |
"servername";
export type RequestOptions = http.RequestOptions & Pick<tls.ConnectionOptions, extendedRequestKeys>;
export interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
rejectUnauthorized?: boolean;
@@ -2609,9 +2603,9 @@ declare module "net" {
destroy(err?: any): void;
pause(): this;
resume(): this;
setTimeout(timeout: number, callback?: Function): void;
setNoDelay(noDelay?: boolean): void;
setKeepAlive(enable?: boolean, initialDelay?: number): void;
setTimeout(timeout: number, callback?: Function): this;
setNoDelay(noDelay?: boolean): this;
setKeepAlive(enable?: boolean, initialDelay?: number): this;
address(): { port: number; family: string; address: string; };
unref(): void;
ref(): void;
@@ -3693,7 +3687,7 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: Array<string | Buffer>) => void): void;
export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void): void;
/**
* Asynchronous readdir(3) - read a directory.
@@ -3722,7 +3716,7 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<Array<string | Buffer>>;
export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string[] | Buffer[]>;
}
/**
@@ -3744,7 +3738,7 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): Array<string | Buffer>;
export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): string[] | Buffer[];
/**
* Asynchronous close(2) - close a file descriptor.
@@ -4816,7 +4810,7 @@ declare module "tls" {
* An array of strings or a Buffer naming possible NPN protocols.
* (Protocols should be ordered by their priority.)
*/
NPNProtocols?: string[] | Buffer,
NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array,
/**
* An array of strings or a Buffer naming possible ALPN protocols.
* (Protocols should be ordered by their priority.) When the server
@@ -4824,7 +4818,7 @@ declare module "tls" {
* precedence over NPN and the server does not send an NPN extension
* to the client.
*/
ALPNProtocols?: string[] | Buffer,
ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array,
/**
* SNICallback(servername, cb) <Function> A function that will be
* called if the client supports SNI TLS extension. Two arguments
@@ -4900,7 +4894,7 @@ declare module "tls" {
* @param callback - callback(err) will be executed with null as err, once the renegotiation
* is successfully completed.
*/
renegotiate(options: TlsOptions, callback: (err: Error | null) => void): any;
renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): any;
/**
* Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512).
* Smaller fragment size decreases buffering latency on the client: large fragments are buffered by
@@ -4943,30 +4937,15 @@ declare module "tls" {
prependOnceListener(event: "secureConnect", listener: () => void): this;
}
export interface TlsOptions {
host?: string;
port?: number;
pfx?: string | Buffer[];
key?: string | string[] | Buffer | any[];
passphrase?: string;
cert?: string | string[] | Buffer | Buffer[];
ca?: string | string[] | Buffer | Buffer[];
crl?: string | string[];
ciphers?: string;
honorCipherOrder?: boolean;
export interface TlsServerOptions extends SecureContextOptions {
handshakeTimeout?: number;
requestCert?: boolean;
rejectUnauthorized?: boolean;
NPNProtocols?: string[] | Buffer;
NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array;
ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array;
SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void;
ecdhCurve?: string;
dhparam?: string | Buffer;
handshakeTimeout?: number;
ALPNProtocols?: string[] | Buffer;
sessionTimeout?: number;
ticketKeys?: Buffer;
sessionIdContext?: string;
secureProtocol?: string;
secureOptions?: number;
}
export interface ConnectionOptions extends SecureContextOptions {
@@ -4975,8 +4954,8 @@ declare module "tls" {
path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored.
socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket
rejectUnauthorized?: boolean; // Defaults to true
NPNProtocols?: Array<string | Buffer>;
ALPNProtocols?: Array<string | Buffer>;
NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array;
ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array;
checkServerIdentity?: typeof checkServerIdentity;
servername?: string; // SNI TLS Extension
session?: Buffer;
@@ -5093,7 +5072,7 @@ declare module "tls" {
* Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined.
*/
export function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined;
export function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server;
export function createServer(options: TlsServerOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server;
export function connect(options: ConnectionOptions, secureConnectionListener?: () => void): TLSSocket;
export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
@@ -5373,7 +5352,7 @@ declare module "stream" {
writable: boolean;
constructor(opts?: WritableOptions);
_write(chunk: any, encoding: string, callback: (err?: Error) => void): void;
_writev?(chunks: Array<{chunk: any, encoding: string}>, callback: (err?: Error) => void): void;
_writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void;
_destroy(err: Error, callback: Function): void;
_final(callback: Function): void;
write(chunk: any, cb?: Function): boolean;
@@ -5464,7 +5443,7 @@ declare module "stream" {
writable: boolean;
constructor(opts?: DuplexOptions);
_write(chunk: any, encoding: string, callback: (err?: Error) => void): void;
_writev?(chunks: Array<{chunk: any, encoding: string}>, callback: (err?: Error) => void): void;
_writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void;
_destroy(err: Error, callback: Function): void;
_final(callback: Function): void;
write(chunk: any, cb?: Function): boolean;
@@ -5544,9 +5523,9 @@ declare module "util" {
export function callbackify<T1, T2>(fn: (arg1: T1, arg2: T2) => Promise<void>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2) => Promise<TResult>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, T4>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, T3, T4, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, T4, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, T4, T5>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void;
export function callbackify<T1, T2, T3, T4, T5, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void;
export function callbackify<T1, T2, T3, T4, T5, T6>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void;
@@ -6141,7 +6120,7 @@ declare module "http2" {
}
export interface ServerStreamFileResponseOptions {
statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void|boolean;
statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean;
getTrailers?: (trailers: OutgoingHttpHeaders) => void;
offset?: number;
length?: number;
@@ -6487,7 +6466,7 @@ declare module "http2" {
export type ServerSessionOptions = SessionOptions;
export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { }
export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { }
export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsServerOptions { }
export interface ServerOptions extends ServerSessionOptions {
allowHTTP1?: boolean;
+19
View File
@@ -235,6 +235,25 @@ namespace fs_tests {
});
}
{
let listS: string[];
listS = fs.readdirSync('path');
listS = fs.readdirSync('path', { encoding: 'utf8' });
listS = fs.readdirSync('path', { encoding: null });
listS = fs.readdirSync('path', { encoding: undefined });
listS = fs.readdirSync('path', 'utf8');
listS = fs.readdirSync('path', null);
listS = fs.readdirSync('path', undefined);
let listB: Buffer[];
listB = fs.readdirSync('path', { encoding: 'buffer' });
listB = fs.readdirSync("path", 'buffer');
let enc = 'buffer';
fs.readdirSync('path', { encoding: enc }); // $ExpectType string[] | Buffer[]
fs.readdirSync('path', { }); // $ExpectType string[] | Buffer[]
}
{
fs.mkdtemp('/tmp/foo-', (err, folder) => {
console.log(folder);
+1 -1
View File
@@ -21,7 +21,7 @@ declare namespace fetch {
userAgent?: string;
body?: Buffer | string | { [key: string]: string };
contentType?: string | false;
tls?: tls.TlsOptions;
tls?: tls.TlsServerOptions;
timeout?: ms;
allowErrorResponse?: boolean;
}
+2 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for object-hash v1.1.8
// Type definitions for object-hash v1.2.0
// Project: https://github.com/puleos/object-hash
// Definitions by: Michael Zabka <https://github.com/misak113>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -18,6 +18,7 @@ declare namespace ObjectHash {
respectFunctionNames?: boolean;
unorderedArrays?: boolean;
unorderedSets?: boolean;
excludeKeys?: (key: string) => boolean;
}
interface HashTableItem {

Some files were not shown because too many files have changed in this diff Show More