API @deepkit/core
npm install @deepkit/core
This lock mechanism works only for one process (worker). live-mutex: has horrible API and doesn't allow to check if an key is currently locked.
proper-filelock: No way to do a correct mutex locking with event-driven blocking acquire() method.
redislock: Very bad performance on high-load (when multiple locks on the same key Returns the class name either of the class definition or of the class of an instance. Note when code is minimized/uglified this output will change. You should disable in your compile the
className modification. Same as getClassName but appends the propertyName. Tries to identify the object by normalised result of Object.toString(obj). Returns the ClassType for a given instance. Returns a human-readable string representation from the given value. Changes the class of a given instance and returns the new object. Creates a shallow copy of given array. Checks whether given array or object is empty (no keys). If given object is falsy, returns false. Returns the size of given array or object. Returns the first key of a given object. Returns the last key of a given object. Returns the first value of given array or object. Returns the last value of given array or object. Returns the average of a number array. A better alternative to "new Promise()" that supports error handling and maintains the stack trace for Error.stack. When you use When you use When an API is called that returns a promise that loses the stack trace on error, you can use fixAsyncOperation(). Makes sure the given value is an error. If it's not an error, it creates a new error with the given value as message. Returns the human-readable byte representation. Returns the number of properties on Create a new class with the given name.
This is currently the only know way to make it workable in browsers too. Returns __filename, works in both cjs and esm. Returns the directory name of the current file (__dirname), works in both cjs and esm. Escape special characters in a regex string, so it can be used as a literal string. Returns an iterator of numbers from start (inclusive) to stop (exclusive) by step. Returns an array of numbers from start (inclusive) to stop (exclusive) by step. Works the same as python's range function. Returns a combined array of the given arrays. Works the same as python's zip function. Forwards the runtime type arguments from function x to function y.
This is necessary when a generic function is overridden and forwarded to something else. Note that generic.bind(this) will not work, as bind() creates a new function and forwarded type arguments can not
reach the original function anymore. This is a limitation of JavaScript. In this case you have to manually forward type arguments. Asserts that the given object is an instance of the given class. Asserts that the given value is defined (not null and not undefined). Logs every call to this method on stdout. Makes sure that calls to this async method are stacked up and are called one after another and not parallel. Makes sure that this async method is only running once at a time. When this method is running and it is tried
to call it another times, that call is "dropped" and it returns simply the result of the previous running call (waiting for it to complete first). Returns the enum label for a given enum value. Returns all possible enum labels. Returns all possible enum keys. Checks whether given enum value is valid. Wraps a function and calls it only This is handy to throttle all kind of rapid calls, like mouse move events or other kind of events. This functions returns a stack that is filled as long as the gate is not activated.
Once activated all recorded calls go to given callback and subsequent calls go directly to given callback. Clears the array so its empty. Returns the amount of removed items. Removes on particular item by reference of an array. Moves a particular item in an array up or down (move>0=down, move<0=up).
Changes the array itself. Concat multiple buffers into one. Convert a buffer to a string. Create a buffer of the given size (uninitialized, so it may contain random data). Note that the result is either Uin8Array or Buffer, depending on the environment.
Buffer from NodeJS works slightly different than Uint8Array. Converts a base64 string to a Uint8Array. Returns true if the given obj is a plain object, and no class instance. isPlainObject({}) === true
isPlainObject(new ClassXY) === false Returns true when target is a class instance. Returns true if given obj is a function. Returns true if given obj is a async function. Returns true if given obj is a promise like object. Note: There's no way to check if it's actually a Promise using instanceof since
there are a lot of different implementations around. Returns true if given obj is a ES6 class (ES5 fake classes are not supported). Returns true for real objects: object literals ({}) or class instances (new MyClass). Returns true if given obj is a plain object, and no Date, Array, Map, Set, etc. This is different to isObject and used in the type system to differentiate
between JS objects in general and what we define as ReflectionKind.objectLiteral.
Since we have Date, Set, Map, etc. in the type system, we need to differentiate
between them and all other object literals. Checks if obj is not null and not undefined. Check if it is a real number (not NaN/Infinite). Returns true if given value is strictly a numeric string value (or a number). Normalizes the given path.
Removes duplicate slashes, removes trailing slashes, adds a leading slash. Same as Returns the directory (dirname) of the given path. Returns the basename of the given path. Returns the extension of the given path. Type to use for custom type annotations. Adds runtime meta information to a type without influencing the type itself.
This is like an intrinsic type, but only for runtime. Runtime type is Classes
export class Timer {
setTimeout(cb: () => void, timeout: number): any;
/**
* Clears all timers at once.
*/
clear();
}
export class ProcessLock {
constructor(public readonly id: string);
async acquire(ttl: number = , timeout: number = );
isLocked();
tryLock(ttl: number = );
unlock();
}
wait
, since it loops)
mongodb lock: even worse performance than redis. Jesus.export class ProcessLocker {
/**
*
* @param id
* @param ttl optional defines when the times automatically unlocks.
* @param timeout if after `timeout` seconds the lock isn't acquired, it throws an error.
*/
async acquireLock(id: string, ttl: number = , timeout: number = ): Promise<ProcessLock>;
async tryLock(id: string, ttl: number = ): Promise<ProcessLock | undefined>;
isLocked(id: string): boolean;
}
export class Mutex {
unlock(): void;
async lock(): Promise<void>;
}
export class ParsedHost {
host: string;
port: number;
unixSocket: string;
get isUnixSocket(): boolean;
get isHostname(): boolean;
get hostWithIp(): string;
toString(): string;
getWebSocketUrl(secure: boolean = false);
getHttpUrl(secure: boolean = false);
}
export class CompilerContext {
readonly context;
maxReservedVariable: number;
/**
* Code that is executed in the context, but before the actual function is generated.
* This helps for example to initialize dynamically some context variables.
*/
preCode: string;
initialiseVariables: string[];
config: {
indent: boolean;
};
constructor(config: Partial<CompilerContext[]> = {});
reserveName(name: string): string;
set(values: {
[name: string]: any;
});
/**
* Returns always the same variable name for the same value.
* The variable name should not be set afterwards.
*/
reserveConst(value: any, name: string = ): string;
reserveVariable(name: string = , value?: any): string;
raw(functionCode: string): Function;
build(functionCode: string, ...args: string[]): any;
buildAsync(functionCode: string, ...args: string[]): Function;
}
export class EmitterEvent {
readonly id;
stopped;
propagationStopped;
/**
* Stop propagating the event to subsequent event listeners.
*/
stopPropagation();
/**
* Signal the emitter that you want to abort.
* Subsequent event listeners will still be called.
*/
stop();
}
export class EventEmitter<T extends EmitterEvent> {
constructor(protected parent?: EventEmitter<any>);
subscribe(callback: Subscriber<T>): EventSubscription;
emit(event: T): void;
hasSubscriptions(): boolean;
}
export class AsyncEventEmitter<T extends EmitterEvent> {
constructor(protected parent?: AsyncEventEmitter<any>);
subscribe(callback: AsyncSubscriber<T>): AsyncEventSubscription;
async emit(event: T): Promise<void>;
hasSubscriptions(): boolean;
}
Const
new (...args: string[]) => Function
Functions
<T>(classTypeOrInstance: ClassType<T> | Object): string
<T>(classType: ClassType<T> | Object, propertyName: string): string
<T>(classType: ClassType<T>, target: { [k: string]: any; }): T
(obj: any): any
<T>(target: T): ClassType<T>
(value: any, depth?: number): string
<T>(value: object, newClass: ClassType<T>): T
(object: object, depth?: number): string
<T>(array: T[], item: T): number
(seconds: number): Promise<void>
<T>(v: T[]): T[]
<T>(value?: T[] | object | {}): boolean
<T>(array: T[] | { [key: string]: T; }): number
(v: { [key: string]: any; } | object): string | undefined
(v: { [key: string]: any; } | object): string | undefined
<T>(v: { [key: string]: T; } | T[]): T | undefined
<T>(v: { [key: string]: T; } | T[]): T | undefined
(array: number[]): number
(o: { [k: string]: any; }, prependText: string): { [k: string]: any; }
(origin: { [k: string]: any; }, extend: { [k: string]: any; }, prependKeyName?: string): void
<T>(executor: (resolve: (value: T) => void, reject: (error: any) => void) => void | Promise<void>): Promise<T>
new Promise()
you need to wrap your code inside a try-catch to call reject
on error.
asyncOperation() does this automatically.new Promise()
you will lose the stack trace when reject(new Error())
is called.
asyncOperation() makes sure the error stack trace is the correct one.<T>(promise: Promise<T>): Promise<T>
cons storage = new BrokenPromiseStorage();
const files = await fixAsyncOperation(storage.files('/'));
<T>(promise: Promise<T>, stack?: string): Promise<T>
(removeCallee?: boolean): string
(error: Error, stack: string): void
(error?: any, classType?: ClassType): Error
<T>(callback: (args: T[]) => void): (arg: T) => void
(bag: { [field: string]: any; }, parameterPath: string, defaultValue?: any): any
(bag: object, parameterPath: string, value: any): void
(bag: object, parameterPath: string): void
(bytes: number, si?: boolean): string
(obj: object): number
obj
. This is 20x faster than Object.keys(obj).length.(classType: ClassType): ClassType | undefined
(classType: ClassType): ClassType[]
(): boolean
(name: string, base?: ClassType): ClassType
(value: Array<unknown> | Set<unknown> | Map<unknown, unknown>): number
(offset?: number): string
(): string
(string: string): string
(object: any, property: any): boolean
(startOrLength: number, stop?: number, step?: number): IterableIterator<number>
(startOrLength: number, stop?: number, step?: number): number[]
<T extends (readonly unknown[])[]>(...args: T): { [K in keyof T]: T[K] extends (infer V)[] ? V : never; }[]
(x: any, y: any): void
let generic = <T>(type?: ReceiveType<T>) => undefined;
let forwarded<T> = () => {
forwardTypeArguments(forwarded, generic); //all type arguments are forwarded to generic()
generic(); //call as usual
}
forwarded<any>(); //generic receives any in runtime.
let forwarded<T> = () => {
const bound = generic.bind(this);
forwardTypeArguments(forwarded, bound); //can not be forwarded anymore
bound(); //fails
}
let forwarded<T> = (type?: ReceiveType<T>) => {
const bound = generic.bind(this);
bound(type);
}
(error: any, withStack?: boolean): string
<T>(object: any, constructor: { new (...args: any[]): T; }): asserts object is T
<T>(value: T): asserts value is NonNullable<T>
(): (target: object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => PropertyDescriptor
(): (target: object, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any>>) => void
(): (target: object, propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any>>) => void
(enumType: { [field: string]: any; }, id: any): any
(enumDefinition: any): string[]
(enumDefinition: any): any[]
(enumDefinition: any): Map<any, string>
(enumDefinition: any, value: any, allowLabelsAsValue?: boolean): boolean
(enumDefinition: any, value: any, allowLabelsAsValue?: boolean): any
(hostWithIpOrUnixPath: string): ParsedHost
(obj: any): void
(indentation: number, prefix?: string): (str?: string) => string
(string: string): string
(call: Function, cps?: number): (...args: any[]) => void
cps
times per frame.<T>(callback: (arg: T) => any): { activate: () => void; call: (i: T) => void; }
(cb: () => void) => any
(id: any) => any
(fn: string | Function | ClassType): string[]
(classCode: string, name: string): string
(code: string): string
(...path: string[]): string
<T>(array: T[], item: T): boolean
<T>(array: T[]): number
<T>(array: T[], item: T): boolean
<A extends T[], T>(array: A, item: T, move: number): A
const array = ['a', 'b', 'c'];
arrayMoveItem(array, 'a', +1); //['b', 'a', 'c']
arrayMoveItem(array, 'a', -1); //['a', 'b', 'c']
arrayMoveItem(array, 'b', -1); //['b', 'a', 'c']
arrayMoveItem(array, 'b', +1); //['a', 'c', 'b']
arrayMoveItem(array, 'c', -1); //['b', 'c', 'b']
arrayMoveItem(array, 'c', +1); //['a', 'b', 'c']
(chunks: Uint8Array[], length?: number): Uint8Array
(buffer: string | Uint8Array): string
(base64: string): Uint8Array
(size: number) => Uint8Array<ArrayBufferLike>
(buffer: Uint8Array<ArrayBufferLike>) => any
(v: string) => Uint8Array<ArrayBufferLike>
(obj: any): obj is object
(target: any): boolean
(obj: any): obj is Function
(obj: any): obj is (...args: any[]) => Promise<any>
<T>(obj: any | Promise<T>): obj is Promise<T>
(obj: any): obj is AbstractClassType
(obj: any): obj is AbstractClassType
(obj: any): obj is { [key: string]: any; }
(obj: any): obj is { [key: string]: any; }
(obj: any): obj is null
(obj: any): obj is undefined
(obj: any): boolean
(obj: any): obj is number
(s: string | number): boolean
isNumeric(12); //true
isNumeric('12'); //true
isNumeric('12.3'); //true
isNumeric('12.3 '); //false
isNumeric('12px'); //false
(obj: any): obj is string
(fn: any): boolean
(prototype: AbstractClassType | undefined, base: ClassType): boolean
(value: any): boolean
(obj: any) => obj is any[]
(obj: any) => obj is number
(path: string): string
(path: string): string
pathNormalize
, but ensures the path is a directory (always ends with a slash).(path: string): string
(path: string): string
(path: string): string
(...paths: string[]): string
Types
interface ClassType<T = any> {
new(...args: any[]): T;
}
type AbstractClassType<T = any> = abstract new (...args: any[]) => T;
type ExtractClassType<T> = T extends AbstractClassType<infer K> ? K : never;
type AsyncEventSubscription = { unsubscribe: () => void };
type EventSubscription = { unsubscribe: () => void };
type TypeAnnotation<T extends string, Options = never> = unknown;
import { TypeAnnotation } from '@deepkit/core';
import { typeAnnotation } from '@deepkit/type';
type PrimaryKey = TypeAnnotation<'primaryKey'>;
type UserId = string & PrimaryKey;
const type = typeOf<UserId>();
const metaData = typeAnnotation.getType(type, 'primaryKey');
{ __meta?: never & [T, Options] };
type InjectMeta<T = never> = TypeAnnotation<'inject', T>;
type Inject<Type, Token = never> = Type & InjectMeta<Token>;