
Research
Namastex.ai npm Packages Hit with TeamPCP-Style CanisterWorm Malware
Malicious Namastex.ai npm packages appear to replicate TeamPCP-style Canister Worm tradecraft, including exfiltration and self-propagation.
@xylabs/sdk-js
Advanced tools
Base functionality used throughout XY Labs TypeScript/JavaScript libraries
Base functionality used throughout XY Labs TypeScript/JavaScript libraries
Using npm:
npm install {{name}}
Using yarn:
yarn add {{name}}
Using pnpm:
pnpm add {{name}}
Using bun:
bun add {{name}}
See the LICENSE file for license rights and limitations (LGPL-3.0-only).
### .temp-typedoc
### classes
### <a id="AbstractCreatable"></a>AbstractCreatable
Base class for objects that follow an asynchronous creation and lifecycle pattern.
Instances must be created via the static create method rather than direct construction.
Provides start/stop lifecycle management with status tracking and telemetry support.
BaseEmitter<Partial<TParams & RequiredCreatableParams>, TEventData>TParams extends CreatableParams = CreatableParams
TEventData extends EventData = EventData
new AbstractCreatable<TParams, TEventData>(key, params): AbstractCreatable<TParams, TEventData>;
unknown
Partial<TParams & RequiredCreatableParams>
AbstractCreatable<TParams, TEventData>
static optional defaultLogger?: Logger;
readonly static globalInstances: Record<BaseClassName, WeakRef<Base>[]>;
readonly static globalInstancesCountHistory: Record<BaseClassName, number[]>;
BaseEmitter.globalInstancesCountHistory
optional defaultLogger?: Logger;
Optional default logger for this instance.
protected _startPromise: Promisable<boolean> | undefined;
eventData: TEventData;
Type-level reference to the event data shape for external type queries.
get static historyInterval(): number;
number
set static historyInterval(value): void;
number
void
get static historyTime(): number;
number
set static historyTime(value): void;
number
void
get static maxGcFrequency(): number;
number
set static maxGcFrequency(value): void;
number
void
get static maxHistoryDepth(): number;
number
get logger(): Logger | undefined;
Logger | undefined
get meter(): Meter | undefined;
Meter | undefined
get tracer(): Tracer | undefined;
Tracer | undefined
get name(): CreatableName;
The name identifier for this creatable instance.
get params(): TParams & RequiredCreatableParams<void>;
The validated and merged parameters for this instance.
TParams & RequiredCreatableParams<void>
get startable(): boolean;
Whether this instance can be started (must be in 'created' or 'stopped' status).
boolean
get status(): CreatableStatus | null;
The current lifecycle status of this instance, or null if not yet initialized.
CreatableStatus | null
get statusReporter():
| CreatableStatusReporter<void>
| undefined;
The status reporter used to broadcast lifecycle changes.
| CreatableStatusReporter<void>
| undefined
static gc(force?): void;
boolean
void
static gc(className): void;
void
static instanceCount(className): number;
number
static instanceCounts(): Record<BaseClassName, number>;
Record<BaseClassName, number>
static startHistory(): void;
void
static stopHistory(): void;
void
static create<T>(this, inParams?): Promise<T>;
Asynchronously creates a new instance by processing params, constructing, and running both static and instance createHandlers.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
Partial<T["params"]>
Optional partial parameters to configure the instance
Promise<T>
The fully initialized instance
static createHandler<T>(this, instance): Promisable<T>;
Static hook called during creation to perform additional initialization. Override in subclasses to customize post-construction setup.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
T
The newly constructed instance
Promisable<T>
The instance, potentially modified
static paramsHandler<T>(this, params?): Promisable<T["params"]>;
Static hook called during creation to validate and transform params. Override in subclasses to add default values or validation.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
Partial<T["params"]>
The raw partial params provided to create
Promisable<T["params"]>
The processed params ready for construction
createHandler(): Promisable<void>;
Instance-level creation hook. Override in subclasses to perform setup after construction.
Promisable<void>
paramsValidator(params): TParams & RequiredCreatableParams<void>;
Validates and returns the merged params, ensuring required fields are present. Override in subclasses to add custom validation logic.
Partial<TParams & RequiredCreatableParams>
The raw partial params to validate
TParams & RequiredCreatableParams<void>
The validated params
span<T>(name, fn): T;
Executes a function within a telemetry span.
T
string
The span name
() => T
The function to execute within the span
T
spanAsync<T>(
name,
fn,
config?): Promise<T>;
Executes an async function within a telemetry span.
T
string
The span name
() => Promise<T>
The async function to execute within the span
Optional span configuration
Promise<T>
start(): Promise<boolean>;
Starts the instance, transitioning through 'starting' to 'started' status. Thread-safe via mutex. Returns true if already started or started successfully.
Promise<boolean>
started(notStartedAction?): boolean;
Checks whether this instance is currently started. Takes an action if not started, based on the notStartedAction parameter.
"error" | "throw" | "warn" | "log" | "none"
What to do if not started: 'error'/'throw' throws, 'warn'/'log' logs, 'none' is silent
boolean
True if started, false otherwise
startedAsync(notStartedAction?, tryStart?): Promise<boolean>;
Async version of started that can optionally auto-start the instance.
"error" | "throw" | "warn" | "log" | "none"
What to do if not started and auto-start is disabled
boolean
If true, attempts to start the instance automatically
Promise<boolean>
True if the instance is or becomes started
stop(): Promise<boolean>;
Stops the instance, transitioning through 'stopping' to 'stopped' status. Thread-safe via mutex. Returns true if already stopped or stopped successfully.
Promise<boolean>
protected _noOverride(functionName?): void;
Asserts that the given function has not been overridden in a subclass.
Used to enforce the handler pattern (override startHandler not start).
string
void
protected setStatus(value, progress?): void;
Sets the lifecycle status and reports it via the status reporter.
"creating" | "created" | "starting" | "started" | "stopping" | "stopped"
number
void
protected setStatus(value, error?): void;
Sets the lifecycle status and reports it via the status reporter.
"error"
Error
void
protected startHandler(): Promisable<void>;
Override in subclasses to define start behavior. Throw an error on failure.
Promisable<void>
protected stopHandler(): Promisable<void>;
Override in subclasses to define stop behavior. Throw an error on failure.
Promisable<void>
clearListeners(eventNames): this;
Removes all listeners for the specified event name(s).
keyof TEventData | keyof TEventData[]
One or more event names to clear listeners for.
this
This instance for chaining.
emit<TEventName, TEventArgs>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners concurrently.
TEventName extends string | number | symbol = keyof TEventData
TEventArgs extends EventArgs = TEventData[TEventName]
TEventName
The event to emit.
TEventArgs
The data to pass to listeners.
Promise<void>
emitSerial<TEventName, TEventArgs>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners sequentially in order.
TEventName extends string | number | symbol = keyof TEventData
TEventArgs extends EventArgs = TEventData[TEventName]
TEventName
The event to emit.
TEventArgs
The data to pass to listeners.
Promise<void>
listenerCount(eventNames): number;
Returns the total number of listeners registered for the specified event name(s).
keyof TEventData | keyof TEventData[]
One or more event names to count listeners for.
number
The total listener count.
off<TEventName>(eventNames, listener): void;
Removes a specific listener from the specified event name(s).
TEventName extends string | number | symbol
TEventName | TEventName[]
One or more event names to unsubscribe from.
EventListener<TEventData[TEventName]>
The listener to remove.
void
offAny(listener): void;
Removes a wildcard listener that was receiving all events.
The wildcard listener to remove.
void
on<TEventName>(eventNames, listener): () => void;
Subscribes a listener to the specified event name(s).
TEventName extends string | number | symbol
TEventName | TEventName[]
One or more event names to listen for.
EventListener<TEventData[TEventName]>
The callback to invoke when the event fires.
An unsubscribe function.
() => void
onAny(listener): () => void;
Subscribes a wildcard listener that receives all events.
The callback to invoke for any event.
An unsubscribe function.
() => void
once<TEventName>(eventName, listener): () => void;
Subscribes a listener that will be invoked only once for the specified event, then automatically removed.
TEventName extends string | number | symbol
TEventName
The event to listen for.
EventListener<TEventData[TEventName]>
The callback to invoke once.
An unsubscribe function.
() => void
### <a id="AbstractCreatableWithFactory"></a>AbstractCreatableWithFactory
Extends AbstractCreatable with a static factory method for creating
pre-configured CreatableFactory instances.
AbstractCreatable<TParams, TEventData>TParams extends CreatableParams = CreatableParams
TEventData extends EventData = EventData
new AbstractCreatableWithFactory<TParams, TEventData>(key, params): AbstractCreatableWithFactory<TParams, TEventData>;
unknown
Partial<TParams & RequiredCreatableParams>
AbstractCreatableWithFactory<TParams, TEventData>
static optional defaultLogger?: Logger;
AbstractCreatable.defaultLogger
readonly static globalInstances: Record<BaseClassName, WeakRef<Base>[]>;
AbstractCreatable.globalInstances
readonly static globalInstancesCountHistory: Record<BaseClassName, number[]>;
AbstractCreatable.globalInstancesCountHistory
optional defaultLogger?: Logger;
Optional default logger for this instance.
AbstractCreatable.defaultLogger
protected _startPromise: Promisable<boolean> | undefined;
AbstractCreatable._startPromise
eventData: TEventData;
Type-level reference to the event data shape for external type queries.
get static historyInterval(): number;
number
set static historyInterval(value): void;
number
void
AbstractCreatable.historyInterval
get static historyTime(): number;
number
set static historyTime(value): void;
number
void
get static maxGcFrequency(): number;
number
set static maxGcFrequency(value): void;
number
void
AbstractCreatable.maxGcFrequency
get static maxHistoryDepth(): number;
number
AbstractCreatable.maxHistoryDepth
get logger(): Logger | undefined;
Logger | undefined
get meter(): Meter | undefined;
Meter | undefined
get tracer(): Tracer | undefined;
Tracer | undefined
get name(): CreatableName;
The name identifier for this creatable instance.
get params(): TParams & RequiredCreatableParams<void>;
The validated and merged parameters for this instance.
TParams & RequiredCreatableParams<void>
get startable(): boolean;
Whether this instance can be started (must be in 'created' or 'stopped' status).
boolean
get status(): CreatableStatus | null;
The current lifecycle status of this instance, or null if not yet initialized.
CreatableStatus | null
get statusReporter():
| CreatableStatusReporter<void>
| undefined;
The status reporter used to broadcast lifecycle changes.
| CreatableStatusReporter<void>
| undefined
AbstractCreatable.statusReporter
static gc(force?): void;
boolean
void
static gc(className): void;
void
static instanceCount(className): number;
number
AbstractCreatable.instanceCount
static instanceCounts(): Record<BaseClassName, number>;
Record<BaseClassName, number>
AbstractCreatable.instanceCounts
static startHistory(): void;
void
AbstractCreatable.startHistory
static stopHistory(): void;
void
static create<T>(this, inParams?): Promise<T>;
Asynchronously creates a new instance by processing params, constructing, and running both static and instance createHandlers.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
Partial<T["params"]>
Optional partial parameters to configure the instance
Promise<T>
The fully initialized instance
static createHandler<T>(this, instance): Promisable<T>;
Static hook called during creation to perform additional initialization. Override in subclasses to customize post-construction setup.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
T
The newly constructed instance
Promisable<T>
The instance, potentially modified
AbstractCreatable.createHandler
static paramsHandler<T>(this, params?): Promisable<T["params"]>;
Static hook called during creation to validate and transform params. Override in subclasses to add default values or validation.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
Partial<T["params"]>
The raw partial params provided to create
Promisable<T["params"]>
The processed params ready for construction
AbstractCreatable.paramsHandler
createHandler(): Promisable<void>;
Instance-level creation hook. Override in subclasses to perform setup after construction.
Promisable<void>
AbstractCreatable.createHandler
paramsValidator(params): TParams & RequiredCreatableParams<void>;
Validates and returns the merged params, ensuring required fields are present. Override in subclasses to add custom validation logic.
Partial<TParams & RequiredCreatableParams>
The raw partial params to validate
TParams & RequiredCreatableParams<void>
The validated params
AbstractCreatable.paramsValidator
span<T>(name, fn): T;
Executes a function within a telemetry span.
T
string
The span name
() => T
The function to execute within the span
T
spanAsync<T>(
name,
fn,
config?): Promise<T>;
Executes an async function within a telemetry span.
T
string
The span name
() => Promise<T>
The async function to execute within the span
Optional span configuration
Promise<T>
start(): Promise<boolean>;
Starts the instance, transitioning through 'starting' to 'started' status. Thread-safe via mutex. Returns true if already started or started successfully.
Promise<boolean>
started(notStartedAction?): boolean;
Checks whether this instance is currently started. Takes an action if not started, based on the notStartedAction parameter.
"error" | "throw" | "warn" | "log" | "none"
What to do if not started: 'error'/'throw' throws, 'warn'/'log' logs, 'none' is silent
boolean
True if started, false otherwise
startedAsync(notStartedAction?, tryStart?): Promise<boolean>;
Async version of started that can optionally auto-start the instance.
"error" | "throw" | "warn" | "log" | "none"
What to do if not started and auto-start is disabled
boolean
If true, attempts to start the instance automatically
Promise<boolean>
True if the instance is or becomes started
AbstractCreatable.startedAsync
stop(): Promise<boolean>;
Stops the instance, transitioning through 'stopping' to 'stopped' status. Thread-safe via mutex. Returns true if already stopped or stopped successfully.
Promise<boolean>
protected _noOverride(functionName?): void;
Asserts that the given function has not been overridden in a subclass.
Used to enforce the handler pattern (override startHandler not start).
string
void
protected setStatus(value, progress?): void;
Sets the lifecycle status and reports it via the status reporter.
"creating" | "created" | "starting" | "started" | "stopping" | "stopped"
number
void
protected setStatus(value, error?): void;
Sets the lifecycle status and reports it via the status reporter.
"error"
Error
void
protected startHandler(): Promisable<void>;
Override in subclasses to define start behavior. Throw an error on failure.
Promisable<void>
AbstractCreatable.startHandler
protected stopHandler(): Promisable<void>;
Override in subclasses to define stop behavior. Throw an error on failure.
Promisable<void>
static factory<T>(
this,
params?,
labels?): CreatableFactory<T>;
Creates a factory that produces instances of this class with pre-configured params and labels.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
Partial<T["params"]>
Default parameters for instances created by the factory
Labels to assign to created instances
clearListeners(eventNames): this;
Removes all listeners for the specified event name(s).
keyof TEventData | keyof TEventData[]
One or more event names to clear listeners for.
this
This instance for chaining.
AbstractCreatable.clearListeners
emit<TEventName, TEventArgs>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners concurrently.
TEventName extends string | number | symbol = keyof TEventData
TEventArgs extends EventArgs = TEventData[TEventName]
TEventName
The event to emit.
TEventArgs
The data to pass to listeners.
Promise<void>
emitSerial<TEventName, TEventArgs>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners sequentially in order.
TEventName extends string | number | symbol = keyof TEventData
TEventArgs extends EventArgs = TEventData[TEventName]
TEventName
The event to emit.
TEventArgs
The data to pass to listeners.
Promise<void>
listenerCount(eventNames): number;
Returns the total number of listeners registered for the specified event name(s).
keyof TEventData | keyof TEventData[]
One or more event names to count listeners for.
number
The total listener count.
AbstractCreatable.listenerCount
off<TEventName>(eventNames, listener): void;
Removes a specific listener from the specified event name(s).
TEventName extends string | number | symbol
TEventName | TEventName[]
One or more event names to unsubscribe from.
EventListener<TEventData[TEventName]>
The listener to remove.
void
offAny(listener): void;
Removes a wildcard listener that was receiving all events.
The wildcard listener to remove.
void
on<TEventName>(eventNames, listener): () => void;
Subscribes a listener to the specified event name(s).
TEventName extends string | number | symbol
TEventName | TEventName[]
One or more event names to listen for.
EventListener<TEventData[TEventName]>
The callback to invoke when the event fires.
An unsubscribe function.
() => void
onAny(listener): () => void;
Subscribes a wildcard listener that receives all events.
The callback to invoke for any event.
An unsubscribe function.
() => void
once<TEventName>(eventName, listener): () => void;
Subscribes a listener that will be invoked only once for the specified event, then automatically removed.
TEventName extends string | number | symbol
TEventName
The event to listen for.
EventListener<TEventData[TEventName]>
The callback to invoke once.
An unsubscribe function.
() => void
### <a id="ApiClient"></a>ApiClient
Abstract base class for API clients that provides stage and token configuration.
new ApiClient(token?, stage?): ApiClient;
string | null
ApiClient
protected optional stage?: ApiStage;
protected optional token?: string | null;
abstract endPoint(): string;
string
### <a id="ApiEndpoint"></a>ApiEndpoint
Generic REST API endpoint wrapper that supports fetching and inserting typed data.
T
The type of data returned by the endpoint
new ApiEndpoint<T>(config, path): ApiEndpoint<T>;
string
ApiEndpoint<T>
get value(): T | undefined;
T | undefined
fetch(): Promise<T>;
Promise<T>
get(): Promise<T | NonNullable<T>>;
Promise<T | NonNullable<T>>
insert(value): Promise<T>;
T
Promise<T>
### <a id="AxiosJson"></a>AxiosJson
use axiosJsonConfig instead
Axiosnew AxiosJson(config?): AxiosJson;
RawAxiosJsonRequestConfig
AxiosJson
Axios.constructor
static axiosConfig(config?): RawAxiosJsonRequestConfig;
RawAxiosJsonRequestConfig
RawAxiosJsonRequestConfig
static create(config?): Axios;
RawAxiosJsonRequestConfig
Axios
### <a id="Base"></a>Base
Abstract base class providing logging, telemetry, and global instance tracking with WeakRef-based GC.
TParams extends BaseParams = BaseParams
The parameter type, extending BaseParams
new Base<TParams>(params): Base<TParams>;
BaseParams<TParams>
Base<TParams>
static optional defaultLogger?: Logger;
readonly static globalInstances: Record<BaseClassName, WeakRef<Base>[]>;
readonly static globalInstancesCountHistory: Record<BaseClassName, number[]>;
get static historyInterval(): number;
number
set static historyInterval(value): void;
number
void
get static historyTime(): number;
number
set static historyTime(value): void;
number
void
get static maxGcFrequency(): number;
number
set static maxGcFrequency(value): void;
number
void
get static maxHistoryDepth(): number;
number
get logger(): Logger | undefined;
Logger | undefined
get meter(): Meter | undefined;
Meter | undefined
get params(): BaseParams<TParams>;
BaseParams<TParams>
get tracer(): Tracer | undefined;
Tracer | undefined
static gc(force?): void;
boolean
void
static gc(className): void;
void
static instanceCount(className): number;
number
static instanceCounts(): Record<BaseClassName, number>;
Record<BaseClassName, number>
static startHistory(): void;
void
static stopHistory(): void;
void
### <a id="BaseEmitter"></a>BaseEmitter
Base class that combines the Base utility class with typed event emission capabilities. Delegates all event operations to an internal Events instance.
Base<TParams>TParams extends BaseParams = BaseParams
TEventData extends EventData = EventData
EventEmitter<TEventData>new BaseEmitter<TParams, TEventData>(params): BaseEmitter<TParams, TEventData>;
BaseParams<TParams>
BaseEmitter<TParams, TEventData>
static optional defaultLogger?: Logger;
readonly static globalInstances: Record<BaseClassName, WeakRef<Base>[]>;
readonly static globalInstancesCountHistory: Record<BaseClassName, number[]>;
Base.globalInstancesCountHistory
eventData: TEventData;
Type-level reference to the event data shape for external type queries.
get static historyInterval(): number;
number
set static historyInterval(value): void;
number
void
get static historyTime(): number;
number
set static historyTime(value): void;
number
void
get static maxGcFrequency(): number;
number
set static maxGcFrequency(value): void;
number
void
get static maxHistoryDepth(): number;
number
get logger(): Logger | undefined;
Logger | undefined
get meter(): Meter | undefined;
Meter | undefined
get params(): BaseParams<TParams>;
BaseParams<TParams>
get tracer(): Tracer | undefined;
Tracer | undefined
static gc(force?): void;
boolean
void
static gc(className): void;
void
static instanceCount(className): number;
number
static instanceCounts(): Record<BaseClassName, number>;
Record<BaseClassName, number>
static startHistory(): void;
void
static stopHistory(): void;
void
clearListeners(eventNames): this;
Removes all listeners for the specified event name(s).
keyof TEventData | keyof TEventData[]
One or more event names to clear listeners for.
this
This instance for chaining.
emit<TEventName, TEventArgs>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners concurrently.
TEventName extends string | number | symbol = keyof TEventData
TEventArgs extends EventArgs = TEventData[TEventName]
TEventName
The event to emit.
TEventArgs
The data to pass to listeners.
Promise<void>
emitSerial<TEventName, TEventArgs>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners sequentially in order.
TEventName extends string | number | symbol = keyof TEventData
TEventArgs extends EventArgs = TEventData[TEventName]
TEventName
The event to emit.
TEventArgs
The data to pass to listeners.
Promise<void>
listenerCount(eventNames): number;
Returns the total number of listeners registered for the specified event name(s).
keyof TEventData | keyof TEventData[]
One or more event names to count listeners for.
number
The total listener count.
off<TEventName>(eventNames, listener): void;
Removes a specific listener from the specified event name(s).
TEventName extends string | number | symbol
TEventName | TEventName[]
One or more event names to unsubscribe from.
EventListener<TEventData[TEventName]>
The listener to remove.
void
offAny(listener): void;
Removes a wildcard listener that was receiving all events.
The wildcard listener to remove.
void
on<TEventName>(eventNames, listener): () => void;
Subscribes a listener to the specified event name(s).
TEventName extends string | number | symbol
TEventName | TEventName[]
One or more event names to listen for.
EventListener<TEventData[TEventName]>
The callback to invoke when the event fires.
An unsubscribe function.
() => void
onAny(listener): () => void;
Subscribes a wildcard listener that receives all events.
The callback to invoke for any event.
An unsubscribe function.
() => void
once<TEventName>(eventName, listener): () => void;
Subscribes a listener that will be invoked only once for the specified event, then automatically removed.
TEventName extends string | number | symbol
TEventName
The event to listen for.
EventListener<TEventData[TEventName]>
The callback to invoke once.
An unsubscribe function.
() => void
### <a id="ConsoleLogger"></a>ConsoleLogger
A LevelLogger that delegates to the global console object.
new ConsoleLogger(level?): ConsoleLogger;
ConsoleLogger
readonly level: LogLevelValue;
readonly logger: Logger;
get debug(): LogFunction;
get error(): LogFunction;
get info(): LogFunction;
get log(): LogFunction;
get trace(): LogFunction;
get warn(): LogFunction;
### <a id="EthAddressWrapper"></a>EthAddressWrapper
Wrapper around an Ethereum address providing parsing, formatting, validation, and checksum support.
protected new EthAddressWrapper(address): EthAddressWrapper;
bigint
EthAddressWrapper
static fromString(value?, base?): EthAddressWrapper | undefined;
string
number
EthAddressWrapper | undefined
static parse(value, base?): EthAddressWrapper | undefined;
unknown
number
EthAddressWrapper | undefined
static validate(address): boolean;
string
boolean
equals(address?): boolean;
string | EthAddressWrapper | null
boolean
toBigNumber(): bigint;
bigint
toHex(): string;
string
toJSON(): string;
string
toLowerCaseString(): string;
string
toShortString(length?): string;
number
string
toString(checksum?, chainId?): string;
boolean
string
string
validate(): boolean;
boolean
### <a id="Events"></a>Events
Core typed event emitter implementation supporting named events, wildcard listeners, serial and concurrent emission, listener filtering, and debug logging.
TEventData extends EventData = EventData
EventEmitter<TEventData>new Events<TEventData>(params?): Events<TEventData>;
Events<TEventData>
static optional defaultLogger?: Logger;
readonly static globalInstances: Record<BaseClassName, WeakRef<Base>[]>;
readonly static globalInstancesCountHistory: Record<BaseClassName, number[]>;
Base.globalInstancesCountHistory
protected static anyMap: WeakMap<object, Set<EventAnyListener>>;
protected static eventsMap: WeakMap<object, Map<PropertyKey, Set<EventListenerInfo<EventArgs>>>>;
eventData: TEventData;
Type-level reference to the event data shape for external type queries.
get static historyInterval(): number;
number
set static historyInterval(value): void;
number
void
get static historyTime(): number;
number
set static historyTime(value): void;
number
void
get static maxGcFrequency(): number;
number
set static maxGcFrequency(value): void;
number
void
get static maxHistoryDepth(): number;
number
get logger(): Logger | undefined;
Logger | undefined
get meter(): Meter | undefined;
Meter | undefined
get params(): BaseParams<TParams>;
BaseParams<TParams>
get tracer(): Tracer | undefined;
Tracer | undefined
get static isDebugEnabled(): boolean;
Whether debug mode is enabled globally or via the DEBUG environment variable.
boolean
set static isDebugEnabled(newValue): void;
boolean
void
get debug(): DebugOptions | undefined;
The debug configuration for this instance, if provided.
DebugOptions | undefined
static gc(force?): void;
boolean
void
static gc(className): void;
void
static instanceCount(className): number;
number
static instanceCounts(): Record<BaseClassName, number>;
Record<BaseClassName, number>
static startHistory(): void;
void
static stopHistory(): void;
void
clearListeners(eventNames): void;
Removes all listeners for the specified event name(s).
keyof TEventData | keyof TEventData[]
One or more event names to clear listeners for.
void
emit<TEventName>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners concurrently.
TEventName extends string | number | symbol
TEventName
The event to emit.
TEventData[TEventName]
The data to pass to listeners.
Promise<void>
emitMetaEvent<TEventName>(eventName, eventArgs): Promise<boolean | undefined>;
Emits an internal meta event (listenerAdded or listenerRemoved).
TEventName extends keyof MetaEventData<TEventData>
TEventName
The meta event name.
MetaEventData<TEventData>[TEventName]
The meta event data containing listener and event information.
Promise<boolean | undefined>
True if the meta event was emitted successfully.
emitSerial<TEventName>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners sequentially in order.
TEventName extends string | number | symbol
TEventName
The event to emit.
TEventData[TEventName]
The data to pass to listeners.
Promise<void>
listenerCount(eventNames?): number;
Returns the total number of listeners registered for the specified event name(s).
keyof TEventData | keyof TEventData[]
One or more event names to count listeners for.
number
The total listener count.
logIfDebugEnabled<TEventName>(
type,
eventName?,
eventArgs?): void;
Logs debug information if debug mode is enabled.
TEventName extends PropertyKey
string
The type of operation being logged.
TEventName
The event name, if applicable.
The event data, if applicable.
void
off<TEventName, TEventListener>(eventNames, listener): void;
Removes a specific listener from the specified event name(s).
TEventName extends string | number | symbol
TEventListener = EventListener<TEventData[TEventName]>
TEventName | TEventName[]
One or more event names to unsubscribe from.
TEventListener
The listener to remove.
void
offAny(listener): void;
Removes a wildcard listener that was receiving all events.
The wildcard listener to remove.
void
on<TEventName>(
eventNames,
listener,
filter?): () => void;
Subscribes a listener to the specified event name(s).
TEventName extends string | number | symbol = keyof TEventData
TEventName | TEventName[]
One or more event names to listen for.
EventListener<TEventData[TEventName]>
The callback to invoke when the event fires.
TEventData[TEventName]
Optional filter to selectively invoke the listener based on event data.
An unsubscribe function.
() => void
onAny(listener): () => void;
Subscribes a wildcard listener that receives all events.
The callback to invoke for any event.
An unsubscribe function.
() => void
once<TEventName>(eventName, listener): () => void;
Subscribes a listener that will be invoked only once for the specified event, then automatically removed.
TEventName extends string | number | symbol
TEventName
The event to listen for.
EventListener<TEventData[TEventName]>
The callback to invoke once.
An unsubscribe function.
() => void
### <a id="Factory"></a>Factory
A concrete factory that wraps a Creatable class with default parameters and labels. Instances are created by merging caller-provided params over the factory defaults.
T extends CreatableInstance = CreatableInstance
new Factory<T>(
creatable,
params?,
labels?): Factory<T>;
Creatable<T>
Partial<T["params"]>
Factory<T>
creatable: Creatable<T>;
The Creatable class this factory delegates creation to.
optional defaultParams?: Partial<T["params"]>;
Default parameters merged into every create call.
optional labels?: Labels;
Labels identifying resources created by this factory.
static withParams<T>(
creatableModule,
params?,
labels?): Factory<T>;
Creates a new Factory instance with the given default params and labels.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
The Creatable class to wrap
Partial<T["params"]>
Default parameters for new instances
Labels to assign to created instances
Factory<T>
create(params?): Promise<T>;
Creates a new instance, merging the provided params over the factory defaults.
Partial<T["params"]>
Optional parameters to override the factory defaults
Promise<T>
### <a id="ForgetPromise"></a>ForgetPromise
Node.js extension of ForgetPromise that can terminate the process on exceptions or timeouts.
ForgetPromisenew ForgetPromise(): ForgetPromiseNode;
ForgetPromiseNode
ForgetPromise.constructor
static activeForgets: number;
Number of currently active (unresolved) forgotten promises.
ForgetPromise.activeForgets
static exceptedForgets: number;
Number of forgotten promises that threw exceptions.
ForgetPromise.exceptedForgets
static logger: Logger;
Logger instance used for error and warning output.
ForgetPromise.logger
get static active(): boolean;
Whether any forgotten promises are still active.
boolean
ForgetPromise.active
static awaitInactive(interval?, timeout?): Promise<number>;
Waits until all forgotten promises have completed.
number
Polling interval in milliseconds.
number
Optional maximum wait time in milliseconds.
Promise<number>
The number of remaining active forgets (0 if all completed).
ForgetPromise.awaitInactive
static exceptionHandler(
error,
config,
externalStackTrace?): void;
Handles exceptions, optionally terminating the process based on config.
Error
string
void
ForgetPromise.exceptionHandler
static forget<T>(promise, config?): void;
Forgets a promise using Node.js-specific configuration with process termination support.
T
Promisable<T>
void
ForgetPromise.forget
static timeoutHandler(
time,
config,
externalStackTrace?): void;
Handles timeouts, optionally terminating the process based on config.
number
string
void
ForgetPromise.timeoutHandler
### <a id="IdLogger"></a>IdLogger
A logger wrapper that prefixes every log message with a bracketed identifier. Useful for distinguishing log output from different components or instances.
new IdLogger(logger, id?): IdLogger;
() => string
IdLogger
set id(id): void;
string
void
debug(...data): void;
...unknown[]
void
Logger.debug
error(...data): void;
...unknown[]
void
Logger.error
info(...data): void;
...unknown[]
void
Logger.info
log(...data): void;
...unknown[]
void
Logger.log
trace(...data): void;
...unknown[]
void
Logger.trace
warn(...data): void;
...unknown[]
void
Logger.warn
### <a id="IsObjectFactory"></a>IsObjectFactory
Factory class for creating type-guard functions that validate objects against a given shape and optional additional checks.
T extends TypedObject
new IsObjectFactory<T>(): IsObjectFactory<T>;
IsObjectFactory<T>
create(shape?, additionalChecks?): TypeCheck<T>;
Creates a type-guard function that validates an object matches the given shape and passes additional checks.
An optional map of property names to expected types.
Optional extra type-check functions to run after shape validation.
TypeCheck<T>
A type-guard function for type T.
### <a id="LevelLogger"></a>LevelLogger
A logger that filters messages based on a configured log level. Methods for levels above the configured threshold return a no-op function.
new LevelLogger(logger, level?): LevelLogger;
LevelLogger
readonly level: LogLevelValue;
readonly logger: Logger;
get debug(): LogFunction;
get error(): LogFunction;
get info(): LogFunction;
get log(): LogFunction;
get trace(): LogFunction;
get warn(): LogFunction;
### <a id="ObjectWrapper"></a>ObjectWrapper
Abstract base class that wraps an object and provides typed access to it.
T extends EmptyObject = EmptyObject
new ObjectWrapper<T>(obj): ObjectWrapper<T>;
T
ObjectWrapper<T>
readonly obj: T;
get protected stringKeyObj(): StringKeyObject;
### <a id="PromiseEx"></a>PromiseEx
An extended Promise that carries an optional attached value and supports cancellation.
The value can be inspected via the then or value methods to conditionally cancel.
Promise<T>T
V = void
new PromiseEx<T, V>(func, value?): PromiseEx<T, V>;
V
PromiseEx<T, V>
Promise<T>.constructor
optional cancelled?: boolean;
Whether the promise has been cancelled via a value callback.
then<TResult1, TResult2>(
onfulfilled?,
onrejected?,
onvalue?): Promise<TResult1 | TResult2>;
Attaches callbacks for the resolution and/or rejection of the Promise.
TResult1 = T
TResult2 = never
((value) => TResult1 | PromiseLike<TResult1>) | null
The callback to execute when the Promise is resolved.
((reason) => TResult2 | PromiseLike<TResult2>) | null
The callback to execute when the Promise is rejected.
(value?) => boolean
Promise<TResult1 | TResult2>
A Promise for the completion of which ever callback is executed.
Promise.then
value(onvalue?): this;
Inspects the attached value via the callback; if it returns true, marks the promise as cancelled.
(value?) => boolean
A callback that receives the attached value and returns whether to cancel.
this
This instance for chaining.
### <a id="SilentLogger"></a>SilentLogger
A logger that does not log anything.
This is useful when you want to disable logging
like when running unit tests or in silent mode.
It implements the Logger interface but all methods
are no-op functions.
new SilentLogger(): SilentLogger;
SilentLogger
readonly debug: (..._data) => undefined;
...unknown[]
undefined
readonly error: (..._data) => undefined;
...unknown[]
undefined
readonly info: (..._data) => undefined;
...unknown[]
undefined
readonly log: (..._data) => undefined;
...unknown[]
undefined
readonly trace: (..._data) => undefined;
...unknown[]
undefined
readonly warn: (..._data) => undefined;
...unknown[]
undefined
### <a id="UniqueBase"></a>UniqueBase
Base class that registers itself as globally unique, preventing duplicate module instances.
Base<TParams>TParams extends BaseParams = BaseParams
new UniqueBase<TParams>(params): UniqueBase<TParams>;
BaseParams<TParams>
UniqueBase<TParams>
static optional defaultLogger?: Logger;
readonly static globalInstances: Record<BaseClassName, WeakRef<Base>[]>;
readonly static globalInstancesCountHistory: Record<BaseClassName, number[]>;
Base.globalInstancesCountHistory
readonly static uniqueDomain: "xy" = "xy";
readonly static uniqueName: string;
readonly static uniqueNameXyo: string;
get static historyInterval(): number;
number
set static historyInterval(value): void;
number
void
get static historyTime(): number;
number
set static historyTime(value): void;
number
void
get static maxGcFrequency(): number;
number
set static maxGcFrequency(value): void;
number
void
get static maxHistoryDepth(): number;
number
get logger(): Logger | undefined;
Logger | undefined
get meter(): Meter | undefined;
Meter | undefined
get params(): BaseParams<TParams>;
BaseParams<TParams>
get tracer(): Tracer | undefined;
Tracer | undefined
static gc(force?): void;
boolean
void
static gc(className): void;
void
static instanceCount(className): number;
number
static instanceCounts(): Record<BaseClassName, number>;
Record<BaseClassName, number>
static startHistory(): void;
void
static stopHistory(): void;
void
### <a id="ValidatorBase"></a>ValidatorBase
Abstract base class for validators that wraps a partial object and provides a validation method.
ObjectWrapper<Partial<T>>T extends EmptyObject = AnyObject
Validator<T>new ValidatorBase<T>(obj): ValidatorBase<T>;
T
ValidatorBase<T>
readonly obj: T;
get protected stringKeyObj(): StringKeyObject;
abstract validate(payload): Promisable<Error[]>;
T
Promisable<Error[]>
### <a id="XyConsoleSpanExporter"></a>XyConsoleSpanExporter
A console span exporter that formats spans with color-coded durations using chalk. Spans are filtered by a configurable log level based on their duration.
ConsoleSpanExporternew XyConsoleSpanExporter(logLevel?, logger?): XyConsoleSpanExporter;
number
XyConsoleSpanExporter
ConsoleSpanExporter.constructor
readonly static durationToLogLevel: number[];
Duration thresholds (in ms) that map to increasing log levels.
readonly static logLevelToChalkColor: ChalkInstance[];
Chalk color functions corresponding to each log level.
logger: Logger;
get logLevel(): number;
The minimum log level required for a span to be exported.
number
export(spans): void;
Export spans.
ReadableSpan[]
void
ConsoleSpanExporter.export
logColor(level): ChalkInstance;
Returns the chalk color function for the given log level.
number
The log level index.
ChalkInstance
A chalk color function.
spanLevel(span): number;
Determines the log level of a span based on its duration.
ReadableSpan
The span to evaluate.
number
The numeric log level (index into durationToLogLevel).
### functions
### <a id="asAddress"></a>asAddress
function asAddress(value?): BrandedAddress | undefined;
Attempts to coerce a value into an Address type, returning undefined or throwing based on the assert config.
unknown
The value to coerce (must be a string)
BrandedAddress | undefined
The value as Address, or undefined if coercion fails and assert is not set
function asAddress(value, assert): BrandedAddress;
Attempts to coerce a value into an Address type, returning undefined or throwing based on the assert config.
unknown
The value to coerce (must be a string)
If provided, throws on failure instead of returning undefined
BrandedAddress
The value as Address, or undefined if coercion fails and assert is not set
### <a id="asAddressV2"></a>asAddressV2
function asAddressV2(value?, assert?): BrandedAddress | undefined;
Alpha
unknown
boolean
BrandedAddress | undefined
### <a id="asEthAddress"></a>asEthAddress
function asEthAddress(value): EthAddress | undefined;
Attempts to coerce a value into an EthAddress, returning undefined or throwing based on the assert config.
unknown
The value to coerce (must be a string)
EthAddress | undefined
The value as EthAddress, or undefined if coercion fails and assert is not set
function asEthAddress(value, assert): EthAddress;
Attempts to coerce a value into an EthAddress, returning undefined or throwing based on the assert config.
unknown
The value to coerce (must be a string)
If provided, throws on failure instead of returning undefined
The value as EthAddress, or undefined if coercion fails and assert is not set
### <a id="asHash"></a>asHash
function asHash(value): BrandedHash | undefined;
Attempts to coerce a value into a Hash type, returning undefined or throwing based on the assert config.
unknown
The value to coerce (must be a string)
BrandedHash | undefined
The value as Hash, or undefined if coercion fails and assert is not set
function asHash(value, assert): BrandedHash;
Attempts to coerce a value into a Hash type, returning undefined or throwing based on the assert config.
unknown
The value to coerce (must be a string)
If provided, throws on failure instead of returning undefined
The value as Hash, or undefined if coercion fails and assert is not set
### <a id="asHex"></a>asHex
function asHex(value): BrandedHex | undefined;
Attempts to coerce a value into a Hex type, returning undefined or throwing based on the assert config.
unknown
The value to coerce (must be a string)
BrandedHex | undefined
The value as Hex, or undefined if coercion fails and assert is not set
function asHex(value, assert): BrandedHex;
Attempts to coerce a value into a Hex type, returning undefined or throwing based on the assert config.
unknown
The value to coerce (must be a string)
If provided, throws on failure instead of returning undefined
The value as Hex, or undefined if coercion fails and assert is not set
### <a id="assertDefinedEx"></a>assertDefinedEx
function assertDefinedEx<T>(expr, messageFunc?): T;
Asserts that a value is defined (not undefined) and returns the value. Throws an error if the value is undefined.
T
The type of value to check
T | undefined
Expression to be evaluated for being defined
AssertExMessageFunc<T>
Function that returns a message for the error if expression is undefined
T
The value of the expression (guaranteed to be defined)
Error with the message returned by messageFunc
// Simple usage with a message function
const value = assertDefinedEx(possiblyUndefined, () => 'Value must be defined')
// Using with type narrowing
const config: Config | undefined = loadConfig()
const safeConfig = assertDefinedEx(config, () => 'Config failed to load')
// safeConfig is now type Config (not Config | undefined)
function assertDefinedEx<T, R>(expr, errorFunc?): T;
Asserts that a value is defined (not undefined) and returns the value. Throws a custom error if the value is undefined.
T
The type of value to check
R extends Error
The type of error to throw
T | undefined
Expression to be evaluated for being defined
AssertExErrorFunc<T, R>
Function that returns a custom error instance if expression is undefined
T
The value of the expression (guaranteed to be defined)
Custom error returned by errorFunc
// Using with a custom error
const user = assertDefinedEx(getUser(), () => new UserNotFoundError('User not found'))
### <a id="assertEx"></a>assertEx
function assertEx<T>(expr, messageFunc?): T;
Asserts that an expression is truthy and returns the value. Throws an error if the expression is falsy.
T
The type of value to check
T | null | undefined
Expression to be evaluated for truthiness
AssertExMessageFunc<T>
Function that returns a message for the error if expression is falsy
T
The value of the expression (guaranteed to be truthy)
Error with the message returned by messageFunc
// Simple usage with a message function
const value = assertEx(possiblyFalsy, () => 'Value must be truthy')
// Using with type narrowing
const config: Config | null = loadConfig()
const safeConfig = assertEx(config, () => 'Config failed to load')
// safeConfig is now type Config (not Config | null)
function assertEx<T, R>(expr, errorFunc?): T;
Asserts that an expression is truthy and returns the value. Throws a custom error if the expression is falsy.
T
The type of value to check
R extends Error
The type of error to throw
T | null | undefined
Expression to be evaluated for truthiness
AssertExErrorFunc<T, R>
Function that returns a custom error instance if expression is falsy
T
The value of the expression (guaranteed to be truthy)
Custom error returned by errorFunc
// Using with a custom error
const user = assertEx(getUser(), () => new UserNotFoundError('User not found'))
### <a id="axiosJsonConfig"></a>axiosJsonConfig
function axiosJsonConfig(config?): RawAxiosJsonRequestConfig;
Creates an Axios config preconfigured for JSON requests with optional gzip compression.
Request bodies exceeding compressLength (default 1024 bytes) are automatically gzip-compressed.
RawAxiosJsonRequestConfig<any>
Base Axios config, optionally including a compressLength threshold
RawAxiosJsonRequestConfig
A fully configured Axios request config with JSON transforms
### <a id="cloneContextWithoutSpan"></a>cloneContextWithoutSpan
function cloneContextWithoutSpan(activeCtx, configKeys?): Context;
Creates a new OpenTelemetry context that preserves baggage and custom keys but has no active span.
Context
The context to clone from.
symbol[]
Additional context keys to copy.
Context
A new context with baggage but no parent span.
### <a id="creatable"></a>creatable
function creatable<T>(): <U>(constructor) => void;
Class annotation to be used to decorate Modules which support an asynchronous creation pattern
T extends CreatableInstance<CreatableParams, EventData>
The decorated Module requiring it implement the members of the CreatableModule as statics properties/methods
<U>(constructor) => void
### <a id="creatableFactory"></a>creatableFactory
function creatableFactory(): <U>(constructor) => void;
Class annotation to be used to decorate Modules which support an asynchronous creation factory pattern
The decorated Module requiring it implement the members of the CreatableModule as statics properties/methods
<U>(constructor) => void
### <a id="createDeepMerge"></a>createDeepMerge
function createDeepMerge(options): <T>(...objects) => MergeAll<T>;
Creates a deep merge function with the specified options.
MergeOptions
Options for merging.
A deep merge function configured for the specified options.
<T>(...objects) => MergeAll<T>
### <a id="fetchCompress"></a>fetchCompress
function fetchCompress(url, options?): Promise<Response>;
Drop-in replacement for native fetch that optionally gzip-compresses the request body.
When compressLength is set and the body string exceeds that threshold, the body is
gzip-compressed via pako and Content-Encoding: gzip is added to the headers.
Returns a standard Response — identical to what native fetch returns.
string | URL
Promise<Response>
### <a id="fetchJson"></a>fetchJson
function fetchJson<T>(url, options?): Promise<FetchJsonResponse<T>>;
JSON-configured fetch with optional gzip compression on request bodies.
Request bodies exceeding compressMinLength bytes are gzip-compressed via pako.
T
string
Promise<FetchJsonResponse<T>>
### <a id="fetchJsonDelete"></a>fetchJsonDelete
function fetchJsonDelete<T>(url, options?): Promise<FetchJsonResponse<T>>;
JSON DELETE request.
T
string
Promise<FetchJsonResponse<T>>
### <a id="fetchJsonGet"></a>fetchJsonGet
function fetchJsonGet<T>(url, options?): Promise<FetchJsonResponse<T>>;
JSON GET request.
T
string
Promise<FetchJsonResponse<T>>
### <a id="fetchJsonPatch"></a>fetchJsonPatch
function fetchJsonPatch<T>(
url,
data?,
options?): Promise<FetchJsonResponse<T>>;
JSON PATCH request with a body.
T
string
unknown
Promise<FetchJsonResponse<T>>
### <a id="fetchJsonPost"></a>fetchJsonPost
function fetchJsonPost<T>(
url,
data?,
options?): Promise<FetchJsonResponse<T>>;
JSON POST request with a body.
T
string
unknown
Promise<FetchJsonResponse<T>>
### <a id="fetchJsonPut"></a>fetchJsonPut
function fetchJsonPut<T>(
url,
data?,
options?): Promise<FetchJsonResponse<T>>;
JSON PUT request with a body.
T
string
unknown
Promise<FetchJsonResponse<T>>
### <a id="hexToBigInt"></a>hexToBigInt
function hexToBigInt(hex): bigint;
Converts a Hex string to a BigInt.
The hex string to convert
bigint
The BigInt representation of the hex value
### <a id="isAddressV2"></a>isAddressV2
function isAddressV2(value?): value is BrandedAddress;
Alpha
unknown
value is BrandedAddress
### <a id="isArray"></a>isArray
function isArray(value): value is readonly unknown[];
Type guard that checks whether a value is an array.
unknown
value is readonly unknown[]
function isArray<T>(value): value is Extract<T, readonly unknown[]>;
Type guard that checks whether a value is an array.
T
T
value is Extract<T, readonly unknown[]>
### <a id="isArrayBuffer"></a>isArrayBuffer
function isArrayBuffer(value): value is ArrayBuffer;
Type guard that checks if a value is an ArrayBuffer instance.
unknown
value is ArrayBuffer
function isArrayBuffer<T>(value): value is Extract<T, ArrayBuffer>;
Type guard that checks if a value is an ArrayBuffer instance.
T extends ArrayBuffer
T
value is Extract<T, ArrayBuffer>
### <a id="isArrayBufferLike"></a>isArrayBufferLike
function isArrayBufferLike(value): value is ArrayBufferLike;
Type guard that checks if a value conforms to the ArrayBufferLike interface (has byteLength and slice).
unknown
value is ArrayBufferLike
function isArrayBufferLike<T>(value): value is Extract<T, ArrayBufferLike>;
Type guard that checks if a value conforms to the ArrayBufferLike interface (has byteLength and slice).
T extends ArrayBufferLike
T
value is Extract<T, ArrayBufferLike>
### <a id="isArrayBufferView"></a>isArrayBufferView
function isArrayBufferView(value): value is ArrayBufferView<ArrayBufferLike>;
Type guard that checks whether a value is an ArrayBufferView (e.g., TypedArray or DataView).
unknown
value is ArrayBufferView<ArrayBufferLike>
function isArrayBufferView<T>(value): value is Extract<T, ArrayBufferView<ArrayBufferLike>>;
Type guard that checks whether a value is an ArrayBufferView (e.g., TypedArray or DataView).
T extends ArrayBufferView<ArrayBufferLike>
T
value is Extract<T, ArrayBufferView<ArrayBufferLike>>
### <a id="isBigInt"></a>isBigInt
function isBigInt(value): value is bigint;
Type guard that checks whether a value is a bigint.
unknown
value is bigint
function isBigInt<T>(value): value is Extract<T, bigint>;
Type guard that checks whether a value is a bigint.
T extends bigint
T
value is Extract<T, bigint>
### <a id="isBlob"></a>isBlob
function isBlob(value): value is Blob;
Type guard that checks whether a value is a Blob instance.
unknown
value is Blob
function isBlob<T>(value): value is Extract<T, Blob>;
Type guard that checks whether a value is a Blob instance.
T extends Blob
T
value is Extract<T, Blob>
### <a id="isBoolean"></a>isBoolean
function isBoolean(value): value is boolean;
Type guard that checks whether a value is a boolean.
unknown
value is boolean
function isBoolean<T>(value): value is Extract<T, boolean>;
Type guard that checks whether a value is a boolean.
T extends boolean
T
value is Extract<T, boolean>
### <a id="isDataView"></a>isDataView
function isDataView(value): value is DataView<ArrayBufferLike>;
Type guard that checks whether a value is a DataView instance.
unknown
value is DataView<ArrayBufferLike>
function isDataView<T>(value): value is Extract<T, DataView<ArrayBufferLike>>;
Type guard that checks whether a value is a DataView instance.
T
T
value is Extract<T, DataView<ArrayBufferLike>>
### <a id="isDate"></a>isDate
function isDate(value): value is Date;
Type guard that checks whether a value is a Date instance.
unknown
value is Date
function isDate<T>(value): value is Extract<T, Date>;
Type guard that checks whether a value is a Date instance.
T
T
value is Extract<T, Date>
### <a id="isDateString"></a>isDateString
function isDateString(value): value is string;
Type guard that checks whether a value is a string that can be parsed as a valid date.
unknown
value is string
function isDateString<T>(value): value is Extract<T, string>;
Type guard that checks whether a value is a string that can be parsed as a valid date.
T
T
value is Extract<T, string>
### <a id="isDefined"></a>isDefined
function isDefined<T>(value): value is Exclude<T, undefined>;
Type guard that checks whether a value is not undefined.
T
T
value is Exclude<T, undefined>
### <a id="isDefinedNotNull"></a>isDefinedNotNull
function isDefinedNotNull<T>(value): value is Exclude<T, null | undefined>;
Type guard that checks whether a value is neither undefined nor null.
T
T
value is Exclude<T, null | undefined>
### <a id="isEmpty"></a>isEmpty
function isEmpty<T>(value): value is T;
Type guard that checks whether a value is empty (empty string, empty array, or empty object).
T
unknown
value is T
function isEmpty<K, V, T>(value): value is Extract<T, Record<K, never>>;
Type guard that checks whether a value is empty (empty string, empty array, or empty object).
K extends RecordKey
V
T extends Record<K, V>
T
value is Extract<T, Record<K, never>>
function isEmpty<T>(value): value is Extract<T, never[]>;
Type guard that checks whether a value is empty (empty string, empty array, or empty object).
T extends unknown[]
T
value is Extract<T, never[]>
### <a id="isEmptyArray"></a>isEmptyArray
function isEmptyArray(value): value is [];
Type guard that checks whether a value is an empty array.
unknown
value is []
function isEmptyArray<T>(value): value is Extract<T, unknown[]>;
Type guard that checks whether a value is an empty array.
T extends unknown[]
T
value is Extract<T, unknown[]>
### <a id="isEmptyObject"></a>isEmptyObject
function isEmptyObject(value): value is {};
Type guard that checks whether a value is an object with no own keys.
unknown
value is {}
function isEmptyObject<K, V, T>(value): value is Extract<T, Record<K, never>>;
Type guard that checks whether a value is an object with no own keys.
K extends RecordKey
V
T extends Record<K, V>
T
value is Extract<T, Record<K, never>>
### <a id="isEmptyString"></a>isEmptyString
function isEmptyString(value): value is "";
Type guard that checks whether a value is an empty string.
unknown
value is ""
function isEmptyString<T>(value): value is Extract<T, "">;
Type guard that checks whether a value is an empty string.
T extends string
T
value is Extract<T, "">
### <a id="isError"></a>isError
function isError(value): value is Error;
Type guard that checks whether a value is an Error instance.
unknown
value is Error
function isError<T>(value): value is Extract<T, Error>;
Type guard that checks whether a value is an Error instance.
T
T
value is Extract<T, Error>
### <a id="isFalsy"></a>isFalsy
function isFalsy<T>(value): value is Extract<T, false | "" | 0 | 0n | null | undefined>;
Type guard that checks whether a value is falsy (0, null, undefined, false, '', or 0n).
T
T
value is Extract<T, false | "" | 0 | 0n | null | undefined>
function isFalsy<T>(value): value is Extract<T, false>;
Type guard that checks whether a value is falsy (0, null, undefined, false, '', or 0n).
T extends boolean
T
value is Extract<T, false>
function isFalsy<T>(value): value is Extract<T, 0>;
Type guard that checks whether a value is falsy (0, null, undefined, false, '', or 0n).
T extends number
T
value is Extract<T, 0>
function isFalsy<T>(value): value is Extract<T, 0n>;
Type guard that checks whether a value is falsy (0, null, undefined, false, '', or 0n).
T extends bigint
T
value is Extract<T, 0n>
function isFalsy<T>(value): value is Extract<T, null>;
Type guard that checks whether a value is falsy (0, null, undefined, false, '', or 0n).
T extends null
T
value is Extract<T, null>
function isFalsy<T>(value): value is Extract<T, undefined>;
Type guard that checks whether a value is falsy (0, null, undefined, false, '', or 0n).
T extends undefined
T
value is Extract<T, undefined>
function isFalsy<T>(value): value is Extract<T, "">;
Type guard that checks whether a value is falsy (0, null, undefined, false, '', or 0n).
T extends string
T
value is Extract<T, "">
### <a id="isFile"></a>isFile
function isFile(value): value is File;
Type guard that checks whether a value is a File instance.
unknown
value is File
function isFile<T>(value): value is Extract<T, File>;
Type guard that checks whether a value is a File instance.
T extends File
T
value is Extract<T, File>
### <a id="isFunction"></a>isFunction
function isFunction(value): value is AnyFunction;
Type guard that checks whether a value is a function.
unknown
value is AnyFunction
function isFunction<T>(value): value is Extract<T, AnyFunction>;
Type guard that checks whether a value is a function.
T extends AnyFunction
T
value is Extract<T, AnyFunction>
### <a id="isMap"></a>isMap
function isMap(value): value is Map<unknown, unknown>;
Type guard that checks whether a value is a Map instance.
unknown
value is Map<unknown, unknown>
function isMap<K, V, T>(value): value is Extract<T, Map<K, V>>;
Type guard that checks whether a value is a Map instance.
K
V
T extends Map<K, V>
T
value is Extract<T, Map<K, V>>
### <a id="isNull"></a>isNull
function isNull(value): value is null;
Type guard that checks whether a value is null.
unknown
value is null
function isNull<T>(value): value is Extract<T, null>;
Type guard that checks whether a value is null.
T
T
value is Extract<T, null>
### <a id="isNumber"></a>isNumber
function isNumber(value): value is number;
Type guard that checks whether a value is a number.
unknown
value is number
function isNumber<T>(value): value is Extract<T, number>;
Type guard that checks whether a value is a number.
T extends number
T
value is Extract<T, number>
### <a id="isObject"></a>isObject
function isObject(value): value is object;
Type guard that checks whether a value is a plain object (not null and not an array).
unknown
value is object
function isObject<T>(value): value is Extract<T, object>;
Type guard that checks whether a value is a plain object (not null and not an array).
T extends object
T
value is Extract<T, object>
### <a id="isPopulatedArray"></a>isPopulatedArray
function isPopulatedArray(value): value is readonly unknown[];
Type guard that checks whether a value is a non-empty array.
unknown
value is readonly unknown[]
function isPopulatedArray<T>(value): value is Extract<T, readonly unknown[]>;
Type guard that checks whether a value is a non-empty array.
T extends unknown[]
T
value is Extract<T, readonly unknown[]>
### <a id="isPromise"></a>isPromise
function isPromise(value): value is Promise<unknown>;
Type guard that checks whether a value is a Promise instance.
unknown
value is Promise<unknown>
function isPromise<T>(value): value is Extract<T, Promise<unknown>>;
Type guard that checks whether a value is a Promise instance.
T
T
value is Extract<T, Promise<unknown>>
### <a id="isPromiseLike"></a>isPromiseLike
function isPromiseLike(value): value is Promise<unknown>;
Type guard that checks whether a value is promise-like (has a then method).
unknown
value is Promise<unknown>
function isPromiseLike<T>(value): value is Extract<T, Promise<unknown>>;
Type guard that checks whether a value is promise-like (has a then method).
T
T
value is Extract<T, Promise<unknown>>
### <a id="isRegExp"></a>isRegExp
function isRegExp(value): value is RegExp;
Type guard that checks whether a value is a RegExp instance.
unknown
value is RegExp
function isRegExp<T>(value): value is Extract<T, RegExp>;
Type guard that checks whether a value is a RegExp instance.
T extends RegExp
T
value is Extract<T, RegExp>
### <a id="isSet"></a>isSet
function isSet(value): value is Set<unknown>;
Type guard that checks whether a value is a Set instance.
unknown
value is Set<unknown>
function isSet<T>(value): value is Extract<T, Set<unknown>>;
Type guard that checks whether a value is a Set instance.
T extends Set<unknown>
unknown
value is Extract<T, Set<unknown>>
### <a id="isString"></a>isString
function isString(value): value is string;
Type guard that checks whether a value is a string.
unknown
value is string
function isString<T>(value): value is Extract<T, string>;
Type guard that checks whether a value is a string.
T extends string
T
value is Extract<T, string>
### <a id="isSymbol"></a>isSymbol
function isSymbol(value): value is symbol;
Type guard that checks whether a value is a symbol.
unknown
value is symbol
function isSymbol<T>(value): value is Extract<T, symbol>;
Type guard that checks whether a value is a symbol.
T extends symbol
T
value is Extract<T, symbol>
### <a id="isTruthy"></a>isTruthy
function isTruthy<T>(value): value is Exclude<T, false | "" | 0 | 0n | null | undefined>;
Type guard that checks whether a value is truthy (not 0, null, undefined, false, '', or 0n).
T
T
value is Exclude<T, false | "" | 0 | 0n | null | undefined>
function isTruthy<T>(value): value is Extract<T, true>;
Type guard that checks whether a value is truthy (not 0, null, undefined, false, '', or 0n).
T extends boolean
T
value is Extract<T, true>
function isTruthy<T>(value): value is Extract<T, number>;
Type guard that checks whether a value is truthy (not 0, null, undefined, false, '', or 0n).
T extends number
T
value is Extract<T, number>
function isTruthy<T>(value): value is Extract<T, bigint>;
Type guard that checks whether a value is truthy (not 0, null, undefined, false, '', or 0n).
T extends bigint
T
value is Extract<T, bigint>
function isTruthy<T>(value): value is Extract<T, null>;
Type guard that checks whether a value is truthy (not 0, null, undefined, false, '', or 0n).
T extends null
T
value is Extract<T, null>
function isTruthy<T>(value): value is Extract<T, undefined>;
Type guard that checks whether a value is truthy (not 0, null, undefined, false, '', or 0n).
T extends undefined
T
value is Extract<T, undefined>
function isTruthy<T>(value): value is Extract<T, string>;
Type guard that checks whether a value is truthy (not 0, null, undefined, false, '', or 0n).
T extends string
T
value is Extract<T, string>
### <a id="isUndefined"></a>isUndefined
function isUndefined(value): value is undefined;
Type guard that checks whether a value is undefined.
unknown
value is undefined
function isUndefined<T>(value): value is Extract<T, undefined>;
Type guard that checks whether a value is undefined.
T
T
value is Extract<T, undefined>
### <a id="isUndefinedOrNull"></a>isUndefinedOrNull
function isUndefinedOrNull(value): value is null | undefined;
Type guard that checks whether a value is undefined or null.
unknown
value is null | undefined
function isUndefinedOrNull<T>(value): value is Extract<T, null | undefined>;
Type guard that checks whether a value is undefined or null.
T
T
value is Extract<T, null | undefined>
### <a id="isWeakMap"></a>isWeakMap
function isWeakMap(value): value is WeakMap<WeakKey, unknown>;
Type guard that checks whether a value is a WeakMap instance.
unknown
value is WeakMap<WeakKey, unknown>
function isWeakMap<K, V, T>(value): value is Extract<T, WeakMap<K, V>>;
Type guard that checks whether a value is a WeakMap instance.
K extends WeakKey
V
T extends WeakMap<K, V>
T
value is Extract<T, WeakMap<K, V>>
### <a id="isWeakSet"></a>isWeakSet
function isWeakSet(value): value is WeakSet<WeakKey>;
Type guard that checks whether a value is a WeakSet instance.
unknown
value is WeakSet<WeakKey>
function isWeakSet<K, T>(value): value is Extract<T, WeakSet<K>>;
Type guard that checks whether a value is a WeakSet instance.
K extends WeakKey
T extends WeakSet<K>
T
value is Extract<T, WeakSet<K>>
### <a id="span"></a>span
function span<T>(
name,
fn,
traceProvider?): T;
Executes a synchronous function within an OpenTelemetry span, recording status and exceptions.
T
string
The span name.
() => T
The function to execute.
TracerProvider
T
The return value of fn.
### <a id="spanAsync"></a>spanAsync
function spanAsync<T>(
name,
fn,
config?): Promise<T>;
Executes an async function within an OpenTelemetry span, with optional time budget monitoring.
T
string
The span name.
() => Promise<T>
The async function to execute.
Optional span configuration (tracer, logger, time budget).
Promise<T>
The resolved value of fn.
### <a id="spanDurationInMillis"></a>spanDurationInMillis
function spanDurationInMillis(span): number;
Calculates the duration of a span in milliseconds from its high-resolution time tuple.
ReadableSpan
The span to measure.
number
The span duration in milliseconds.
### <a id="spanRoot"></a>spanRoot
function spanRoot<T>(
name,
fn,
tracer?): T;
Executes a synchronous function within a new root span that has no parent, even if a span is already active.
T
string
The span name.
() => T
The function to execute.
Tracer
Optional tracer to use.
T
The return value of fn.
### <a id="spanRootAsync"></a>spanRootAsync
function spanRootAsync<T>(
name,
fn,
config?): Promise<T>;
Executes an async function within a new root span (no parent), with optional time budget monitoring.
T
string
The span name.
() => Promise<T>
The async function to execute.
Optional span configuration (tracer, logger, time budget).
Promise<T>
The resolved value of fn.
### <a id="staticImplements"></a>staticImplements
function staticImplements<T>(): <U>(constructor) => void;
Annotation to decorate classes which implement static methods
T
The decorated class requiring it to implement the members of the the type as static properties/methods
<U>(constructor) => void
### <a id="timeBudget"></a>timeBudget
function timeBudget<TResult>(
name,
logger,
func,
budget,
status?): Promise<TResult>;
Executes an async function and logs a warning if it exceeds the given time budget.
TResult
string
A label for the function, used in warning messages.
Logger | undefined
The logger to use for budget-exceeded warnings.
() => Promise<TResult>
The async function to execute.
number
The time budget in milliseconds.
boolean
If true, logs periodic warnings while the function is still running.
Promise<TResult>
The result of the executed function.
### <a id="toAddressV2"></a>toAddressV2
function toAddressV2(value, assert?): BrandedAddress | undefined;
Alpha
unknown
boolean
BrandedAddress | undefined
### <a id="toArrayBuffer"></a>toArrayBuffer
function toArrayBuffer(
value,
padLength?,
base?): undefined;
Converts a string, bigint, or ArrayBufferLike to an ArrayBufferLike, with optional zero-padding.
undefined
The value to convert (hex string, bigint, or existing buffer)
number
Minimum byte length, left-padded with zeros if needed
number
Numeric base for string parsing (default 16)
undefined
The resulting ArrayBufferLike, or undefined if value is undefined
function toArrayBuffer(
value,
padLength?,
base?): ArrayBufferLike;
Converts a string, bigint, or ArrayBufferLike to an ArrayBufferLike, with optional zero-padding.
string | bigint | ArrayBufferLike
The value to convert (hex string, bigint, or existing buffer)
number
Minimum byte length, left-padded with zeros if needed
number
Numeric base for string parsing (default 16)
ArrayBufferLike
The resulting ArrayBufferLike, or undefined if value is undefined
function toArrayBuffer(
value,
padLength?,
base?): ArrayBufferLike | undefined;
Converts a string, bigint, or ArrayBufferLike to an ArrayBufferLike, with optional zero-padding.
string | bigint | ArrayBufferLike | undefined
The value to convert (hex string, bigint, or existing buffer)
number
Minimum byte length, left-padded with zeros if needed
number
Numeric base for string parsing (default 16)
ArrayBufferLike | undefined
The resulting ArrayBufferLike, or undefined if value is undefined
### <a id="toPromise"></a>toPromise
function toPromise<T>(value): Promise<T>;
Wraps a value in a Promise if it is not already one.
T
Promisable<T>
A value that may or may not be a Promise.
Promise<T>
A Promise resolving to the value.
### <a id="toUint8Array"></a>toUint8Array
function toUint8Array(
value,
padLength?,
base?): undefined;
Converts a string, bigint, or ArrayBufferLike to a Uint8Array, with optional zero-padding.
undefined
The value to convert
number
Minimum byte length, left-padded with zeros if needed
number
Numeric base for string parsing (default 16)
undefined
The resulting Uint8Array, or undefined if value is undefined
function toUint8Array(
value,
padLength?,
base?): Uint8Array;
Converts a string, bigint, or ArrayBufferLike to a Uint8Array, with optional zero-padding.
string | bigint | ArrayBufferLike
The value to convert
number
Minimum byte length, left-padded with zeros if needed
number
Numeric base for string parsing (default 16)
Uint8Array
The resulting Uint8Array, or undefined if value is undefined
function toUint8Array(
value,
padLength?,
base?): Uint8Array<ArrayBufferLike> | undefined;
Converts a string, bigint, or ArrayBufferLike to a Uint8Array, with optional zero-padding.
string | bigint | ArrayBufferLike | undefined
The value to convert
number
Minimum byte length, left-padded with zeros if needed
number
Numeric base for string parsing (default 16)
Uint8Array<ArrayBufferLike> | undefined
The resulting Uint8Array, or undefined if value is undefined
### <a id="zodAllFactory"></a>zodAllFactory
function zodAllFactory<T, TName>(zod, name): object;
Alpha
Creates a bundle of is, as, and to factory functions for a given zod schema.
T
TName extends string
ZodType<T>
The zod schema to validate against
TName
The name used to suffix the generated function names (e.g. 'Address' produces isAddress, asAddress, toAddress)
object
An object containing is<Name>, as<Name>, and to<Name> functions
### <a id="zodAsAsyncFactory"></a>zodAsAsyncFactory
function zodAsAsyncFactory<TZod>(zod, name): {
<T> (value): Promise<T & TZod | undefined>;
<T> (value, assert): Promise<T & TZod>;
};
Creates an async function that validates a value against a zod schema and returns it with a narrowed type.
Uses safeParseAsync for schemas with async refinements. When called without an assert config, returns undefined on failure.
TZod
ZodType<TZod>
The zod schema to validate against
string
A name used in error messages for identification
An async function that validates and narrows the type of a value
{
<T> (value): Promise<T & TZod | undefined>;
<T> (value, assert): Promise<T & TZod>;
}
### <a id="zodAsFactory"></a>zodAsFactory
function zodAsFactory<TZod>(zod, name): {
<T> (value): T & TZod | undefined;
<T> (value, assert): T & TZod;
};
Creates a function that validates a value against a zod schema and returns it with a narrowed type. When called without an assert config, returns undefined on failure. When called with an assert config, throws on failure.
TZod
ZodType<TZod>
The zod schema to validate against
string
A name used in error messages for identification
A function that validates and narrows the type of a value
{
<T> (value): T & TZod | undefined;
<T> (value, assert): T & TZod;
}
### <a id="zodIsFactory"></a>zodIsFactory
function zodIsFactory<TZod>(zod): <T>(value) => value is T & TZod;
Creates a type guard function that checks if a value matches a zod schema.
TZod
ZodType<TZod>
The zod schema to validate against
A type guard function that returns true if the value passes validation
<T>(value) => value is T & TZod
### <a id="zodToAsyncFactory"></a>zodToAsyncFactory
function zodToAsyncFactory<TZod>(zod, name): {
<T> (value): Promise<T & TZod | undefined>;
<T> (value, assert): Promise<T & TZod>;
};
Creates an async function that converts a value to the zod schema type, delegating to zodAsAsyncFactory internally.
Provides overloads for optional assertion: without assert config resolves to undefined on failure, with assert config throws on failure.
TZod
ZodType<TZod>
The zod schema to validate against
string
A name used in error messages for identification
An async function that validates and converts a value to the schema type
{
<T> (value): Promise<T & TZod | undefined>;
<T> (value, assert): Promise<T & TZod>;
}
### <a id="zodToFactory"></a>zodToFactory
function zodToFactory<TZod>(zod, name): {
<T> (value): T & TZod | undefined;
<T> (value, assert): T & TZod;
};
Creates a function that converts a value to the zod schema type, delegating to zodAsFactory internally.
Provides overloads for optional assertion: without assert config returns undefined on failure, with assert config throws on failure.
TZod
ZodType<TZod>
The zod schema to validate against
string
A name used in error messages for identification
A function that validates and converts a value to the schema type
{
<T> (value): T & TZod | undefined;
<T> (value, assert): T & TZod;
}
### interfaces
### <a id="ApiConfig"></a>ApiConfig
Configuration for connecting to an API, including domain, authentication, and user identification.
apiDomain: string;
optional apiKey?: string;
optional jwtToken?: string;
optional userid?: string;
### <a id="AsTypeFunction"></a>AsTypeFunction
A type-narrowing function that attempts to cast a value to T, with optional assertion and configuration overloads.
T extends AnyNonPromise = AnyNonPromise
AsTypeFunction<TType>(value): TType | undefined;
A type-narrowing function that attempts to cast a value to T, with optional assertion and configuration overloads.
TType extends AnyNonPromise
TType | undefined
AsTypeFunction<TType>(value, config): TType;
A type-narrowing function that attempts to cast a value to T, with optional assertion and configuration overloads.
TType extends AnyNonPromise
TType
AsTypeFunction<TType>(value, config): TType | undefined;
A type-narrowing function that attempts to cast a value to T, with optional assertion and configuration overloads.
TType extends AnyNonPromise
| TypeCheckConfig
| TypeCheckOptionalConfig
TType | undefined
AsTypeFunction<TType>(value, assert): TType | undefined;
A type-narrowing function that attempts to cast a value to T, with optional assertion and configuration overloads.
TType extends AnyNonPromise
StringOrAlertFunction<TType>
TType | undefined
AsTypeFunction<TType>(
value,
assert,
config): TType;
A type-narrowing function that attempts to cast a value to T, with optional assertion and configuration overloads.
TType extends AnyNonPromise
StringOrAlertFunction<TType>
TType
AsTypeFunction<TType>(
value,
assert,
config): TType | undefined;
A type-narrowing function that attempts to cast a value to T, with optional assertion and configuration overloads.
TType extends AnyNonPromise
StringOrAlertFunction<TType>
| TypeCheckConfig
| TypeCheckOptionalConfig
TType | undefined
### <a id="BaseEmitterParamsFields"></a>BaseEmitterParamsFields
Fields specific to BaseEmitter configuration parameters.
### <a id="BaseParamsFields"></a>BaseParamsFields
Common parameter fields available to all Base instances (logger, meter, tracer).
optional logger?: Logger;
optional meterProvider?: MeterProvider;
optional traceProvider?: TracerProvider;
### <a id="Creatable"></a>Creatable
Static interface for classes that support asynchronous creation.
Provides the create, createHandler, and paramsHandler static methods
used to construct instances through the creatable lifecycle.
T extends CreatableInstance = CreatableInstance
new Creatable(key, params): T & AbstractCreatable<T["params"], EventData>;
Constructs a new raw instance. Should not be called directly; use create instead.
unknown
Partial<CreatableParams>
T & AbstractCreatable<T["params"], EventData>
optional defaultLogger?: Logger;
Optional default logger shared across instances created by this class.
create<T>(this, params?): Promise<T>;
Asynchronously creates and initializes a new instance with the given params.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
Partial<T["params"]>
Promise<T>
createHandler<T>(this, instance): Promisable<T>;
Hook called after construction to perform additional initialization on the instance.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
T
Promisable<T>
paramsHandler<T>(this, params?): Promisable<T["params"] & RequiredCreatableParams<void>>;
Hook called to validate and transform params before instance construction.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
Partial<T["params"]>
Promisable<T["params"] & RequiredCreatableParams<void>>
### <a id="CreatableFactory"></a>CreatableFactory
A factory interface for creating instances of a Creatable with pre-configured parameters.
Unlike the full Creatable, this only exposes the create method.
Omit<Creatable<T>,
| "create"
| "createHandler"
| "paramsHandler"
| "defaultLogger"
| "factory">T extends CreatableInstance = CreatableInstance
create(this, params?): Promise<T>;
Creates a new instance, merging the provided params with the factory's defaults.
CreatableFactory<T>
Partial<T["params"]>
Promise<T>
### <a id="CreatableInstance"></a>CreatableInstance
Represents a created instance with a managed lifecycle (start/stop) and event emission.
EventEmitter<TEventData>TParams extends CreatableParams = CreatableParams
TEventData extends EventData = EventData
eventData: TEventData;
The event data type associated with this instance.
name: CreatableName;
The name identifier for this instance.
params: TParams;
The parameters used to configure this instance.
start: () => Promise<boolean>;
Starts the instance. Resolves to true if started successfully.
Promise<boolean>
stop: () => Promise<boolean>;
Stops the instance. Resolves to true if stopped successfully.
Promise<boolean>
clearListeners(eventNames): void;
Removes all listeners for the specified event name(s).
keyof TEventData | keyof TEventData[]
void
emit<TEventName>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners concurrently.
TEventName extends string | number | symbol
TEventName
TEventData[TEventName]
Promise<void>
emitSerial<TEventName>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners sequentially in order.
TEventName extends string | number | symbol
TEventName
TEventData[TEventName]
Promise<void>
listenerCount(eventNames): number;
Returns the total number of listeners registered for the specified event name(s).
keyof TEventData | keyof TEventData[]
number
off<TEventName>(eventNames, listener): void;
Removes a specific listener from the specified event name(s).
TEventName extends string | number | symbol
TEventName | TEventName[]
EventListener<TEventData[TEventName]>
void
offAny(listener): void;
Removes a wildcard listener that was receiving all events.
| Promise<void>
| EventAnyListener
void
on<TEventName>(eventNames, listener): EventUnsubscribeFunction;
Subscribes a listener to the specified event name(s) and returns an unsubscribe function.
TEventName extends string | number | symbol
TEventName | TEventName[]
EventListener<TEventData[TEventName]>
onAny(listener): EventUnsubscribeFunction;
Subscribes a wildcard listener that receives all events and returns an unsubscribe function.
once<TEventName>(eventName, listener): EventUnsubscribeFunction;
Subscribes a listener that will be invoked only once for the specified event, then automatically removed.
TEventName extends string | number | symbol
TEventName
EventListener<TEventData[TEventName]>
### <a id="CreatableParams"></a>CreatableParams
Parameters for creating a creatable instance, combining required params with emitter params.
optional logger?: Logger;
RequiredCreatableParams.logger
optional meterProvider?: MeterProvider;
RequiredCreatableParams.meterProvider
optional traceProvider?: TracerProvider;
RequiredCreatableParams.traceProvider
optional name?: CreatableName;
Optional name identifying this creatable instance.
optional statusReporter?: CreatableStatusReporter<void>;
Optional reporter for broadcasting status changes.
RequiredCreatableParams.statusReporter
### <a id="CreatableStatusReporter"></a>CreatableStatusReporter
Reports status changes for a creatable, supporting progress tracking and error reporting.
TAdditionalStatus extends void | string = void
report(
name,
status,
progress): void;
Report a non-error status with a numeric progress value.
| "creating"
| "created"
| "starting"
| "started"
| "stopping"
| "stopped"
| Exclude<TAdditionalStatus extends void ? StandardCreatableStatus : TAdditionalStatus, "error">
number
void
report(
name,
status,
error): void;
Report an error status with the associated Error.
| "error"
| Extract<TAdditionalStatus extends void ? StandardCreatableStatus : TAdditionalStatus, "error">
Error
void
report(name, status): void;
Report a status change without progress or error details.
CreatableStatus<TAdditionalStatus>
void
### <a id="CreatableWithFactory"></a>CreatableWithFactory
Extends Creatable with a factory method that produces pre-configured CreatableFactory instances.
Creatable<T>T extends CreatableInstance = CreatableInstance
new CreatableWithFactory(key, params): T & AbstractCreatable<T["params"], EventData>;
Constructs a new raw instance. Should not be called directly; use create instead.
unknown
Partial<CreatableParams>
T & AbstractCreatable<T["params"], EventData>
optional defaultLogger?: Logger;
Optional default logger shared across instances created by this class.
create<T>(this, params?): Promise<T>;
Asynchronously creates and initializes a new instance with the given params.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
Partial<T["params"]>
Promise<T>
createHandler<T>(this, instance): Promisable<T>;
Hook called after construction to perform additional initialization on the instance.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
T
Promisable<T>
paramsHandler<T>(this, params?): Promisable<T["params"] & RequiredCreatableParams<void>>;
Hook called to validate and transform params before instance construction.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
Partial<T["params"]>
Promisable<T["params"] & RequiredCreatableParams<void>>
factory<T>(
this,
params?,
labels?): CreatableFactory<T>;
Creates a factory with the given default params and labels.
T extends CreatableInstance<CreatableParams, EventData>
Creatable<T>
Partial<T["params"]>
### <a id="DebugOptions"></a>DebugOptions
Configure debug options of an instance.
optional enabled?: boolean;
optional logger?: DebugLogger;
readonly name: string;
### <a id="EventEmitter"></a>EventEmitter
Interface for a typed event emitter that supports subscribing, unsubscribing, and emitting events.
T extends EventData
eventData: T;
Type-level reference to the event data shape for external type queries.
clearListeners(eventNames): void;
Removes all listeners for the specified event name(s).
keyof T | keyof T[]
void
emit<TEventName>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners concurrently.
TEventName extends string | number | symbol
TEventName
T[TEventName]
Promise<void>
emitSerial<TEventName>(eventName, eventArgs): Promise<void>;
Emits an event, invoking all registered listeners sequentially in order.
TEventName extends string | number | symbol
TEventName
T[TEventName]
Promise<void>
listenerCount(eventNames): number;
Returns the total number of listeners registered for the specified event name(s).
keyof T | keyof T[]
number
off<TEventName>(eventNames, listener): void;
Removes a specific listener from the specified event name(s).
TEventName extends string | number | symbol
TEventName | TEventName[]
EventListener<T[TEventName]>
void
offAny(listener): void;
Removes a wildcard listener that was receiving all events.
| Promise<void>
| EventAnyListener
void
on<TEventName>(eventNames, listener): EventUnsubscribeFunction;
Subscribes a listener to the specified event name(s) and returns an unsubscribe function.
TEventName extends string | number | symbol
TEventName | TEventName[]
EventListener<T[TEventName]>
onAny(listener): EventUnsubscribeFunction;
Subscribes a wildcard listener that receives all events and returns an unsubscribe function.
once<TEventName>(eventName, listener): EventUnsubscribeFunction;
Subscribes a listener that will be invoked only once for the specified event, then automatically removed.
TEventName extends string | number | symbol
TEventName
EventListener<T[TEventName]>
### <a id="EventListenerInfo"></a>EventListenerInfo
Information about a registered event listener, including an optional filter for selective invocation.
TEventArgs extends EventArgs = EventArgs
optional filter?: TEventArgs;
listener: EventListener<TEventArgs>;
### <a id="FetchCompressOptions"></a>FetchCompressOptions
RequestInitoptional compressMinLength?: number;
Gzip payloads larger than this byte count. Requires pako to be installed.
### <a id="FetchJsonResponse"></a>FetchJsonResponse
Structured response from a fetchJson call.
T
data: T | null;
headers: Headers;
response: Response;
status: number;
statusText: string;
### <a id="ForgetNodeConfig"></a>ForgetNodeConfig
Node.js-specific forget configuration that extends ForgetConfig with process termination options.
ForgetConfig<T>T = any
optional name?: string;
Optional name for identifying the forgotten promise in logs.
ForgetConfig.name
optional onCancel?: () => void;
Called when the promise is cancelled due to timeout.
void
ForgetConfig.onCancel
optional onComplete?: (result) => void;
Called when the promise completes, with a tuple of [result, error].
[T | undefined, Error | undefined]
void
ForgetConfig.onComplete
optional onException?: (error) => void;
Called when an exception occurs outside the promise itself.
Error
void
ForgetConfig.onException
optional timeout?: number;
Timeout in milliseconds after which the promise is considered timed out.
ForgetConfig.timeout
optional terminateOnException?: boolean;
Terminate the process on an exception that happens outside of the promise being forgotten.
optional terminateOnTimeout?: boolean;
Terminate the process if the promise times out.
### <a id="HexConfig"></a>HexConfig
Configuration of validation and output format
optional bitLength?: number;
optional byteSize?: number;
optional prefix?: boolean;
### <a id="KeyValueStore"></a>KeyValueStore
A read/write storage device.
ReadonlyKeyValueStore<TValue, TKey>TValue
TKey = string
get(key): Promisable<TValue | undefined>;
Returns a promise that resolves to the value for the given key.
TKey
The key to get the value for.
Promisable<TValue | undefined>
optional keys(): Promisable<TKey[]>;
The keys an array of keys.
Promisable<TKey[]>
optional clear(): Promisable<void>;
Removes all entries from the store.
Promisable<void>
delete(key): Promisable<void>;
Deletes the entry with the given key.
TKey
The key of the entry to delete
Promisable<void>
set(key, value): Promisable<void>;
Sets a value for the given key, creating or updating the entry.
TKey
The key to set
TValue
The value to store
Promisable<void>
### <a id="Logger"></a>Logger
Interface to handle overlap between Winston &
console with as much congruency as possible.
debug: LogFunction;
error: LogFunction;
info: LogFunction;
log: LogFunction;
trace: LogFunction;
warn: LogFunction;
### <a id="MetaEventData"></a>MetaEventData
Data shape for internal meta events that fire when listeners are added or removed.
TEventData extends EventData
listenerAdded: object;
optional eventName?: keyof TEventData;
listener:
| EventListener<TEventData[keyof TEventData]>
| EventAnyListener<TEventData[keyof TEventData]>;
listenerRemoved: object;
optional eventName?: keyof TEventData;
listener:
| EventListener<TEventData[keyof TEventData]>
| EventAnyListener<TEventData[keyof TEventData]>;
### <a id="ObjectTypeConfig"></a>ObjectTypeConfig
Configuration options for object type checking.
optional log?: boolean | Logger;
### <a id="PromiseType"></a>PromiseType
An interface representing any thenable (promise-like) object.
then: () => unknown;
unknown
### <a id="ReadonlyKeyValueStore"></a>ReadonlyKeyValueStore
A readonly storage device.
TValue
TKey = string
get(key): Promisable<TValue | undefined>;
Returns a promise that resolves to the value for the given key.
TKey
The key to get the value for.
Promisable<TValue | undefined>
optional keys(): Promisable<TKey[]>;
The keys an array of keys.
Promisable<TKey[]>
### <a id="RequiredCreatableParams"></a>RequiredCreatableParams
The minimum required parameters for constructing a creatable.
TAdditionalStatus extends CreatableStatus | void = void
optional logger?: Logger;
BaseEmitterParams.logger
optional meterProvider?: MeterProvider;
BaseEmitterParams.meterProvider
optional traceProvider?: TracerProvider;
BaseEmitterParams.traceProvider
optional name?: CreatableName;
Optional name identifying this creatable instance.
optional statusReporter?: CreatableStatusReporter<TAdditionalStatus>;
Optional reporter for broadcasting status changes.
### <a id="RetryConfig"></a>RetryConfig
Configuration for retry behavior.
optional backoff?: number;
Multiplier applied to the interval after each retry. Defaults to 2.
optional interval?: number;
Initial delay in milliseconds between retries. Defaults to 100.
optional retries?: number;
Maximum number of retry attempts. Defaults to 0 (no retries).
### <a id="RetryConfigWithComplete"></a>RetryConfigWithComplete
Retry configuration extended with a custom completion check.
T = unknown
optional backoff?: number;
Multiplier applied to the interval after each retry. Defaults to 2.
optional interval?: number;
Initial delay in milliseconds between retries. Defaults to 100.
optional retries?: number;
Maximum number of retry attempts. Defaults to 0 (no retries).
optional complete?: (result?) => boolean;
Determines whether the result is considered complete. Defaults to checking for a defined value.
T
boolean
### <a id="SpanConfig"></a>SpanConfig
Configuration options for span creation and execution.
optional logger?: Logger | null;
Optional logger for time budget warnings. Falls back to console if not provided.
optional timeBudgetLimit?: number;
Maximum allowed execution time in milliseconds before logging a warning.
optional tracer?: Tracer;
OpenTelemetry tracer to use. Defaults to a tracer named after the span.
### <a id="TypeCheck"></a>TypeCheck
A type guard function that checks whether a value conforms to type T, with optional configuration.
T extends TypedValue
TypeCheck(obj): obj is T;
A type guard function that checks whether a value conforms to type T, with optional configuration.
obj is T
TypeCheck(obj, config): obj is T;
A type guard function that checks whether a value conforms to type T, with optional configuration.
obj is T
TypeCheck(obj, config): obj is T;
A type guard function that checks whether a value conforms to type T, with optional configuration.
number | TypeCheckConfig | undefined
obj is T
### <a id="TypeCheckConfig"></a>TypeCheckConfig
Configuration options for type check functions, with optional logging.
optional log?: boolean | Logger;
### <a id="TypeCheckOptionalConfig"></a>TypeCheckOptionalConfig
Type check configuration that marks the value as optional, returning undefined on failure.
optional log?: boolean | Logger;
required: false;
### <a id="TypeCheckRequiredConfig"></a>TypeCheckRequiredConfig
Type check configuration that marks the value as required, causing assertions on failure.
optional log?: boolean | Logger;
required: true;
### <a id="Validator"></a>Validator
Interface for validating objects and returning any errors found.
T extends EmptyObject = AnyObject
validate(payload): Promisable<Error[]>;
T
Promisable<Error[]>
### <a id="WithLabels"></a>WithLabels
Interface for objects that have labels.
labels: T;
### <a id="WithOptionalLabels"></a>WithOptionalLabels
Interface for objects that have labels.
optional labels?: T;
### <a id="ZodFactoryConfigObject"></a>ZodFactoryConfigObject
Configuration object for zod factory functions, providing a name for error messages.
name: string;
### type-aliases
### <a id="Address"></a>Address
type Address = z.infer<typeof AddressZod>;
A validated 20-byte address string type, inferred from the AddressZod schema.
### <a id="AddressTransformZodType"></a>AddressTransformZodType
type AddressTransformZodType = z.infer<typeof AddressTransformZod>;
The output type of AddressTransformZod after parsing and transformation.
### <a id="AddressValidationZodType"></a>AddressValidationZodType
type AddressValidationZodType = z.infer<typeof AddressValidationZod>;
The output type of AddressValidationZod after parsing.
### <a id="AllZodFactories"></a>AllZodFactories
type AllZodFactories<TType, TName> = Record<`is${TName}`, ReturnType<typeof zodIsFactory>> & Record<`as${TName}`, ReturnType<typeof zodAsFactory>> & Record<`to${TName}`, ReturnType<typeof zodToFactory>>;
Alpha
TType
TName extends string
### <a id="AnyFunction"></a>AnyFunction
type AnyFunction = (...args) => unknown;
A function type that accepts any arguments and returns unknown.
...unknown[]
unknown
### <a id="AnyNonPromise"></a>AnyNonPromise
type AnyNonPromise = Exclude<TypedValue, PromiseType>;
Any non-promise typed value, excluding thenables.
### <a id="AnyObject"></a>AnyObject
type AnyObject = EmptyObject & Partial<Record<TypedKey, unknown>>;
Any object, which means that it does not enforce the set of fields that it has. Extending from AnyObject will result in a type that includes the universal set of field names
### <a id="ApiStage"></a>ApiStage
type ApiStage = EnumValue<typeof ApiStage>;
A valid API stage value ('prod', 'beta', or 'local').
### <a id="AsOptionalTypeFunction"></a>AsOptionalTypeFunction
type AsOptionalTypeFunction<T> = <TType>(value) => TType | undefined;
A simplified type-narrowing function that returns T or undefined, without assertion support.
T extends AnyNonPromise = AnyNonPromise
TType extends T
TType | undefined
### <a id="AssertConfig"></a>AssertConfig
type AssertConfig = string | AssertCallback | boolean;
Configuration for assertion behavior: a static message string, a boolean toggle, or a callback.
### <a id="AsyncMutex"></a>AsyncMutex
type AsyncMutex<T> = Promise<T>;
T
Used to document promises that are being used as Mutexes
### <a id="BaseClassName"></a>BaseClassName
type BaseClassName = string & object;
Branded string type representing a class name used for global instance tracking.
__baseClassName: true;
### <a id="BaseEmitterParams"></a>BaseEmitterParams
type BaseEmitterParams<T> = BaseParams<T & BaseEmitterParamsFields & T>;
Parameters type for configuring a BaseEmitter instance.
T extends EmptyObject = EmptyObject
### <a id="BaseParams"></a>BaseParams
type BaseParams<TAdditionalParams> = TAdditionalParams & BaseParamsFields;
Parameters for constructing a Base instance, combining BaseParamsFields with optional additional params.
TAdditionalParams extends EmptyObject = EmptyObject
### <a id="Brand"></a>Brand
type Brand<T, B> = T & { [K in keyof B]: B[K] };
Creates a branded type by intersecting base type T with brand type B, enabling nominal typing in TypeScript.
T
B
### <a id="BrandedHash"></a>BrandedHash
type BrandedHash = Brand<Hex, {
__hash: true;
}>;
Branded type representing a validated hash hex string.
### <a id="BrandedHex"></a>BrandedHex
type BrandedHex = Brand<Lowercase<string>, {
__hex: true;
}>;
Branded type representing a validated lowercase hex string.
### <a id="Compare"></a>Compare
type Compare<T> = (a, b) => number;
A comparator function that returns a negative number if a < b, zero if a == b, and a positive number if a > b.
T
T
T
number
### <a id="CreatableName"></a>CreatableName
type CreatableName = Exclude<string, "creatable-name-reserved-32546239486"> & BaseClassName;
A branded string type used as the name identifier for creatables.
### <a id="CreatableStatus"></a>CreatableStatus
type CreatableStatus<TAdditionalStatus> =
| StandardCreatableStatus
| TAdditionalStatus extends void ? StandardCreatableStatus : TAdditionalStatus;
A creatable's status, optionally extended with additional custom status values.
TAdditionalStatus extends void | string = void
### <a id="DebugLogger"></a>DebugLogger
type DebugLogger = (type, debugName, eventName?, eventData?) => void;
Emittery can collect and log debug information.
To enable this feature set the DEBUG environment variable to emittery or *. Additionally, you can set the static isDebugEnabled variable to true
on the Emittery class, or myEmitter.debug.enabled on an instance of it for debugging a single instance.
See API for more information on how debugging works.
string
string
void
### <a id="DeepOmitStartsWith"></a>DeepOmitStartsWith
type DeepOmitStartsWith<T, Prefix> = T extends infer U[] ? DeepOmitStartsWith<U, Prefix>[] : T extends object ? { [K in keyof T as K extends string ? K extends `${Prefix}${string}` ? never : K : K]: DeepOmitStartsWith<T[K], Prefix> } : T;
Recursively omits keys that start with the given prefix, including in nested objects and arrays.
T
Prefix extends string
### <a id="DeepPickStartsWith"></a>DeepPickStartsWith
type DeepPickStartsWith<T, Prefix> = T extends infer U[] ? DeepPickStartsWith<U, Prefix>[] : T extends object ? { [K in keyof T as K extends string ? K extends `${Prefix}${string}` ? K : never : K]: DeepPickStartsWith<T[K], Prefix> } : T;
Recursively picks only the keys that start with the given prefix, including in nested objects and arrays.
T
Prefix extends string
### <a id="DeepRestrictToJson"></a>DeepRestrictToJson
type DeepRestrictToJson<T> = { [K in keyof T as K extends string ? K : never]: T[K] extends (infer U)[] ? DeepRestrictToJson<U>[] : T[K] extends object ? DeepRestrictToJson<T[K]> : T[K] extends JsonValue ? T[K] : never };
Recursively restricts an object type to only JSON-compatible values, excluding non-serializable types.
T
### <a id="DeepRestrictToStringKeys"></a>DeepRestrictToStringKeys
type DeepRestrictToStringKeys<T> = { [K in keyof T as K extends string ? K : never]: T[K] extends (infer U)[] ? DeepRestrictToStringKeys<U>[] : T[K] extends object ? DeepRestrictToStringKeys<T[K]> : T[K] };
Recursively removes all non-string keys from an object type, including in nested objects and arrays.
T
### <a id="EmptyObject"></a>EmptyObject
type EmptyObject<T> = Exclude<{ [K in keyof T]?: never }, unknown[] | ((...args) => unknown) | null>;
An empty object, which means that it does enforce the set of field names, defaulting to an empty set until extended from, which then adds only those additional fields
T extends object = object
### <a id="Enum"></a>Enum
type Enum<T> = { readonly [K in keyof T]: T[K] };
A utility type that, given a Record<string, unknown>, returns a readonly version
of that record. This results in a type where all properties of T are readonly.
T extends Readonly<Record<string | number | symbol, unknown>>
The record type to make readonly.
// Given a record:
export const DnsRecordType = Enum({
A: 1,
AAAA: 28,
CAA: 257,
CNAME: 5,
DNAME: 39,
MX: 15,
NS: 2,
PTR: 12,
SOA: 6,
SPF: 99,
SRV: 33,
TXT: 16,
})
// Now the type inference will preserve the literal types:
export type DnsRecordType = Enum<typeof DnsRecordType>
### <a id="EnumKey"></a>EnumKey
type EnumKey<T, K> = keyof K;
A utility type that, given an Enum object, returns the union of its keys.
T extends Record<string | number | symbol, unknown>
K = Enum<T>
### <a id="EnumValue"></a>EnumValue
type EnumValue<T, K> = K[keyof K];
A utility type that, given an Enum object, returns the union of its values.
T extends Record<string | number | symbol, unknown>
K = Enum<T>
### <a id="EthAddress"></a>EthAddress
type EthAddress = Brand<string, {
__eth_address: true;
}>;
Branded type representing a validated Ethereum address with 0x prefix.
### <a id="EventAnyListener"></a>EventAnyListener
type EventAnyListener<TEventArgs> = (eventName, eventData) => Promisable<void>;
A listener that receives all events regardless of name.
TEventArgs extends EventArgs = EventArgs
The name of the emitted event.
TEventArgs
The data associated with the event.
Promisable<void>
### <a id="EventArgs"></a>EventArgs
type EventArgs = string | number | object;
The allowed types for event argument payloads.
### <a id="EventData"></a>EventData
type EventData = Record<EventName, EventArgs>;
A mapping of event names to their corresponding event argument types.
### <a id="EventListener"></a>EventListener
type EventListener<TEventArgs> = (eventData) => Promisable<void>;
A listener for a specific event type.
TEventArgs extends EventArgs = EventArgs
TEventArgs
The data associated with the event.
Promisable<void>
### <a id="EventName"></a>EventName
type EventName = PropertyKey;
A valid event name, which can be any property key (string, number, or symbol).
### <a id="EventUnsubscribeFunction"></a>EventUnsubscribeFunction
type EventUnsubscribeFunction = () => void;
A function returned by event subscription methods that unsubscribes the listener when called.
void
### <a id="EventsParams"></a>EventsParams
type EventsParams = BaseParams<{
debug?: DebugOptions;
}>;
Parameters for constructing an Events instance, with optional debug configuration.
### <a id="FetchJsonOptions"></a>FetchJsonOptions
type FetchJsonOptions = FetchCompressOptions;
Fetch request options extended with an optional gzip compression threshold.
### <a id="FieldType"></a>FieldType
type FieldType =
| "string"
| "number"
| "object"
| "symbol"
| "undefined"
| "null"
| "array"
| "function";
Union of string literals representing the possible types of an object field.
### <a id="Hash"></a>Hash
type Hash = z.infer<typeof HashZod>;
A validated hash string type, inferred from the HashZod schema.
### <a id="HashBitLength"></a>HashBitLength
type HashBitLength = 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096;
Valid bit lengths for hash values.
### <a id="Hex"></a>Hex
type Hex = z.infer<typeof HexZod>;
A validated hex string type, inferred from the HexZod schema.
### <a id="IdentityFunction"></a>IdentityFunction
type IdentityFunction<T> = (value) => value is T;
A type guard function that narrows an unknown value to type T.
T
unknown
value is T
### <a id="JsonArray"></a>JsonArray
type JsonArray = z.infer<typeof JsonArrayZod>;
A JSON array containing JSON values.
### <a id="JsonObject"></a>JsonObject
type JsonObject = z.infer<typeof JsonObjectZod>;
A JSON object with string keys and JSON values.
### <a id="JsonValue"></a>JsonValue
type JsonValue = z.infer<typeof JsonValueZod>;
A recursive JSON value: string, number, boolean, null, array, or object.
### <a id="Labels"></a>Labels
type Labels = Record<string, string | undefined>;
Object used to represent labels identifying a resource.
### <a id="LogFunction"></a>LogFunction
type LogFunction = (...data) => void;
A generic logging function that accepts any number of arguments.
...unknown[]
void
### <a id="LogLevelKey"></a>LogLevelKey
type LogLevelKey = EnumKey<typeof LogLevel>;
String key for a log level (e.g. 'error', 'warn', 'info').
### <a id="LogLevelValue"></a>LogLevelValue
type LogLevelValue = EnumValue<typeof LogLevel>;
Numeric value of a log level (1 through 6).
### <a id="LogVerbosity"></a>LogVerbosity
type LogVerbosity = LogLevelKey;
Alias for LogLevelKey, representing the verbosity setting as a string.
### <a id="NullablePromisable"></a>NullablePromisable
type NullablePromisable<T, V> = Promisable<T | null, V>;
A Promisable that may resolve to null.
T
V = never
### <a id="NullablePromisableArray"></a>NullablePromisableArray
type NullablePromisableArray<T, V> = PromisableArray<T | null, V>;
A Promisable array where elements may be null.
T
V = never
### <a id="ObjectTypeShape"></a>ObjectTypeShape
type ObjectTypeShape = Record<string | number | symbol, FieldType>;
Describes the expected shape of an object by mapping each key to its expected field type.
### <a id="OmitByPredicate"></a>OmitByPredicate
type OmitByPredicate<T> = (value, key) => boolean;
A predicate function used to determine which properties to omit from an object.
T extends EmptyObject = Record<string, unknown>
T[keyof T]
keyof T
boolean
### <a id="OmitStartsWith"></a>OmitStartsWith
type OmitStartsWith<T, Prefix> = { [K in keyof T as K extends `${Prefix}${string}` ? never : K]: T[K] };
Omits the keys of T that start with the given prefix.
T
Prefix extends string
### <a id="Optional"></a>Optional
type Optional<T, F> = Omit<T, F> & Partial<Pick<T, F>>;
Makes the specified fields of T optional while keeping the rest required.
T extends object
F extends keyof T
### <a id="OptionalPromisable"></a>OptionalPromisable
type OptionalPromisable<T, V> = Promisable<T | undefined, V>;
A Promisable that may resolve to undefined.
T
V = never
### <a id="OptionalPromisableArray"></a>OptionalPromisableArray
type OptionalPromisableArray<T, V> = PromisableArray<T | undefined, V>;
A Promisable array where elements may be undefined.
T
V = never
### <a id="Override"></a>Override
type Override<T1, T2> = Omit<T1, keyof T2> & T2;
Overrides properties of T1 with those from T2.
T1
T2
### <a id="PartialRecord"></a>PartialRecord
type PartialRecord<K, T> = Partial<Record<K, T>>;
K extends keyof any
T
use Partial<Record<>> instead
### <a id="PickByPredicate"></a>PickByPredicate
type PickByPredicate<T> = (value, key) => boolean;
A predicate function used to determine which properties to pick from an object.
T extends EmptyObject = Record<string, unknown>
T[keyof T]
keyof T
boolean
### <a id="PickStartsWith"></a>PickStartsWith
type PickStartsWith<T, Prefix> = { [K in keyof T as K extends `${Prefix}${string}` ? K : never]: T[K] };
Picks only the keys of T that start with the given prefix.
T
Prefix extends string
### <a id="Profiler"></a>Profiler
type Profiler = Record<string, number[]>;
A record of named timing entries, where each key maps to an array of timestamps.
### <a id="Promisable"></a>Promisable
type Promisable<T, V> = PromiseEx<T, V> | Promise<T> | T;
A value that may be a Promise, PromiseEx, or a plain synchronous value.
T
V = never
### <a id="PromisableArray"></a>PromisableArray
type PromisableArray<T, V> = Promisable<T[], V>;
A Promisable that resolves to an array.
T
V = never
### <a id="PromiseExFunc"></a>PromiseExFunc
type PromiseExFunc<T> = (resolve?, reject?) => void;
The executor function passed to the PromiseEx constructor.
T
PromiseExSubFunc<T, void>
PromiseExSubFunc<T, void>
void
### <a id="PromiseExSubFunc"></a>PromiseExSubFunc
type PromiseExSubFunc<T, TResult> = (value) => TResult;
A resolve/reject callback used within PromiseEx.
T
TResult = T
T
TResult
### <a id="PromiseExValueFunc"></a>PromiseExValueFunc
type PromiseExValueFunc<V> = (value?) => boolean;
A callback that inspects the attached value and returns whether to cancel the promise.
V
V
boolean
### <a id="RecordKey"></a>RecordKey
type RecordKey = string | number | symbol;
A union of valid object key types.
### <a id="Simplify"></a>Simplify
type Simplify<T> = { [K in keyof T]: T[K] } & object;
Flattens an intersection or complex mapped type into a single object type for better readability.
T
### <a id="StandardCreatableStatus"></a>StandardCreatableStatus
type StandardCreatableStatus =
| "creating"
| "created"
| "starting"
| "started"
| "stopping"
| "stopped"
| "error";
The standard lifecycle statuses a creatable can transition through.
### <a id="StringKeyObject"></a>StringKeyObject
type StringKeyObject<T> = Record<string, T>;
An object type with string keys and values of type T.
T = unknown
### <a id="StringOrAlertFunction"></a>StringOrAlertFunction
type StringOrAlertFunction<T> = string | AssertExMessageFunc<T>;
A string message or function that produces an assertion error message for a failed type check.
T extends AnyNonPromise
### <a id="TypeOfTypes"></a>TypeOfTypes
type TypeOfTypes =
| "string"
| "number"
| "object"
| "array"
| "buffer"
| "null"
| "undefined"
| "bigint"
| "boolean"
| "function"
| "symbol";
Union of string literals representing the possible results of the extended typeOf function.
### <a id="TypedArray"></a>TypedArray
type TypedArray = TypedValue[];
An array of TypedValue elements.
### <a id="TypedKey"></a>TypedKey
type TypedKey<T> = T extends string ? T : string | number | symbol;
A valid key for a typed object. Defaults to string | number | symbol unless narrowed by T.
T extends string | void = void
### <a id="TypedObject"></a>TypedObject
type TypedObject =
| {
[key: string | number | symbol]: TypedValue;
}
| object;
An object whose keys are TypedKey and whose values are TypedValue.
### <a id="TypedValue"></a>TypedValue
type TypedValue =
| bigint
| string
| number
| boolean
| null
| TypedObject
| TypedArray
| Function
| symbol
| undefined;
A value that can appear in a typed object tree (primitives, objects, arrays, functions, and symbols).
### <a id="WithAdditional"></a>WithAdditional
type WithAdditional<T, TAdditional> = TAdditional extends EmptyObject ? T & TAdditional : T;
Intersects T with TAdditional if TAdditional is an object, otherwise returns T unchanged.
T extends EmptyObject | void
TAdditional extends EmptyObject | void = void
### <a id="ZodFactoryConfig"></a>ZodFactoryConfig
type ZodFactoryConfig =
| AssertConfig
| ZodFactoryConfigObject;
Configuration for zod factory assertion behavior, either an AssertConfig or a named config object.
### variables
### <a id="ADDRESS_LENGTH"></a>ADDRESS_LENGTH
const ADDRESS_LENGTH: 40;
The character length of an address hex string (40 hex characters / 20 bytes).
### <a id="AddressRegEx"></a>AddressRegEx
const AddressRegEx: RegExp;
Regular expression matching a 20-byte (40 hex character) address string.
### <a id="AddressTransformZod"></a>AddressTransformZod
const AddressTransformZod: z.ZodPipe<z.ZodPipe<z.ZodUnion<readonly [z.ZodString, z.ZodBigInt, z.ZodNumber]>, z.ZodTransform<string, string | number | bigint>>, z.ZodTransform<Lowercase<string> & object & object, string>>;
Zod schema that accepts a string, bigint, or number and transforms it into a validated Address.
### <a id="AddressValidationZod"></a>AddressValidationZod
const AddressValidationZod: z.ZodPipe<z.ZodString, z.ZodTransform<Lowercase<string> & object & object, string>>;
Zod schema that validates a string is a properly formatted 40-character hex address.
### <a id="AddressZod"></a>AddressZod
const AddressZod: z.ZodPipe<z.ZodString, z.ZodTransform<BrandedAddress, string>>;
Zod schema that validates and transforms a string into a branded Address type.
### <a id="ApiStage"></a>ApiStage
const ApiStage: Enum<{
Beta: "beta";
Local: "local";
Prod: "prod";
}>;
Deployment stage identifiers for API environments.
### <a id="AsObjectFactory"></a>AsObjectFactory
const AsObjectFactory: object;
Factory for creating type-narrowing functions for TypedObject types.
create: <T>(typeCheck) => AsTypeFunction;
T extends TypedObject
TypeCheck<T>
createOptional: <T>(typeCheck) => (value) => T | undefined;
T extends TypedObject
TypeCheck<T>
(value) => T | undefined
### <a id="AsTypeFactory"></a>AsTypeFactory
const AsTypeFactory: object;
Factory for creating type-narrowing 'as' functions that cast a value to T or return undefined. Supports optional assertion messages and configuration for required/optional behavior.
create: <T>(typeCheck) => AsTypeFunction<T>;
T extends AnyNonPromise
TypeCheck<T>
createOptional: <T>(typeCheck) => (value) => T | undefined;
T extends AnyNonPromise
TypeCheck<T>
(value) => T | undefined
### <a id="BigIntToJsonZod"></a>BigIntToJsonZod
const BigIntToJsonZod: z.ZodPipe<z.ZodBigInt, z.ZodTransform<BrandedHex, bigint>>;
Zod schema that transforms a non-negative BigInt into a hex string for JSON serialization.
### <a id="Buffer"></a>Buffer
const Buffer: BufferConstructor;
### <a id="ETH_ZERO_ADDRESS"></a>ETH_ZERO_ADDRESS
const ETH_ZERO_ADDRESS: EthAddress;
The zero Ethereum address constant (0x followed by 40 zero characters).
### <a id="Enum"></a>Enum
const Enum: <T>(obj) => Enum<T>;
Transforms a given record object into a readonly "enum-like" structure while preserving the literal types of its values. This allows you to use the returned object both at runtime (for lookups) and at compile time (for strongly typed values).
To maintain literal types (i.e., prevent them from being widened to string, number, etc.),
ensure you annotate your object with as const before passing it to Enum.
T extends Record<string | number | symbol, unknown>
A record type with string keys and any kind of values.
Readonly<T>
A readonly record object annotated with as const.
Enum<T>
A readonly version of the provided record, preserving exact literal value types.
// Defining a record with literal types using as const:
const DnsRecordType = Enum({
A: 1,
AAAA: 28,
CAA: 257,
CNAME: 5,
DNAME: 39,
MX: 15,
NS: 2,
PTR: 12,
SOA: 6,
SPF: 99,
SRV: 33,
TXT: 16,
} as const);
// DnsRecordType is now a readonly object:
// {
// readonly A: 1;
// readonly AAAA: 28;
// readonly CAA: 257;
// readonly CNAME: 5;
// readonly DNAME: 39;
// readonly MX: 15;
// readonly NS: 2;
// readonly PTR: 12;
// readonly SOA: 6;
// readonly SPF: 99;
// readonly SRV: 33;
// readonly TXT: 16;
// }
### <a id="EthAddressFromStringSchema"></a>EthAddressFromStringSchema
const EthAddressFromStringSchema: z.ZodPipe<z.ZodString, z.ZodTransform<EthAddress, string>>;
use EthAddressFromStringZod
### <a id="EthAddressFromStringZod"></a>EthAddressFromStringZod
const EthAddressFromStringZod: z.ZodPipe<z.ZodString, z.ZodTransform<EthAddress, string>>;
Zod schema that validates and transforms a string into an EthAddress type.
### <a id="EthAddressRegEx"></a>EthAddressRegEx
const EthAddressRegEx: RegExp;
Regular expression matching a 20-byte Ethereum address with 0x prefix (mixed case).
### <a id="EthAddressToStringSchema"></a>EthAddressToStringSchema
const EthAddressToStringSchema: z.ZodString;
use EthAddressToStringZod
### <a id="EthAddressToStringZod"></a>EthAddressToStringZod
const EthAddressToStringZod: z.ZodString;
Zod schema that validates a string is a properly formatted Ethereum address.
### <a id="EthAddressZod"></a>EthAddressZod
const EthAddressZod: z.ZodString & z.ZodType<EthAddress, string, z.core.$ZodTypeInternals<EthAddress, string>>;
Zod schema that validates a string as a properly formatted Ethereum address using regex and type guard.
### <a id="HASH_LENGTH"></a>HASH_LENGTH
const HASH_LENGTH: 32;
The byte length of a standard hash (32 bytes / 256 bits).
### <a id="HashBitLength"></a>HashBitLength
HashBitLength: HashBitLength[];
Array of all valid hash bit lengths for runtime validation.
### <a id="HashRegEx"></a>HashRegEx
const HashRegEx: RegExp;
Regular expression matching a 32-byte (64 hex character) hash string.
### <a id="HashToJsonZod"></a>HashToJsonZod
const HashToJsonZod: z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<BrandedHash, string>>, z.ZodTransform<string, BrandedHash>>;
Zod schema that transforms a Hash to a plain string for JSON serialization.
### <a id="HashZod"></a>HashZod
const HashZod: z.ZodPipe<z.ZodString, z.ZodTransform<BrandedHash, string>>;
Zod schema that validates and transforms a string into a branded Hash type.
### <a id="HexRegEx"></a>HexRegEx
const HexRegEx: RegExp;
Regular expression matching a lowercase hex string without prefix.
### <a id="HexRegExMinMax"></a>HexRegExMinMax
const HexRegExMinMax: (minBytes?, maxBytes?) => RegExp;
Creates a RegExp matching lowercase hex strings with a byte length in the given range.
number
Minimum number of bytes (default 0)
number
Maximum number of bytes
RegExp
A RegExp for validating hex strings within the byte range
### <a id="HexRegExMinMaxMixedCaseWithPrefix"></a>HexRegExMinMaxMixedCaseWithPrefix
const HexRegExMinMaxMixedCaseWithPrefix: (minBytes?, maxBytes?) => RegExp;
Creates a RegExp matching mixed-case hex strings with a 0x prefix and a byte length in the given range.
number
Minimum number of bytes (default 0)
number
Maximum number of bytes
RegExp
A RegExp for validating prefixed hex strings within the byte range
### <a id="HexRegExWithPrefix"></a>HexRegExWithPrefix
const HexRegExWithPrefix: RegExp;
Regular expression matching a lowercase hex string with a 0x prefix.
### <a id="HexZod"></a>HexZod
const HexZod: z.ZodPipe<z.ZodString, z.ZodTransform<BrandedHex, string>>;
Zod schema that validates and transforms a string into a branded Hex type.
### <a id="JsonObjectZod"></a>JsonObjectZod
const JsonObjectZod: z.ZodRecord<z.ZodString, z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>;
Zod schema for a JSON object with string keys and recursive JSON values.
### <a id="JsonToBigIntZod"></a>JsonToBigIntZod
const JsonToBigIntZod: z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<BrandedHex, string>>, z.ZodTransform<bigint, BrandedHex>>;
Zod schema that parses a JSON hex string into a BigInt.
### <a id="JsonToHashZod"></a>JsonToHashZod
const JsonToHashZod: z.ZodPipe<z.ZodString, z.ZodTransform<BrandedHash, string>>;
Zod schema that parses a JSON string into a validated Hash, throwing on invalid input.
### <a id="LogLevel"></a>LogLevel
const LogLevel: Enum<{
error: 1;
warn: 2;
info: 3;
log: 4;
debug: 5;
trace: 6;
}>;
Numeric log level values, from least verbose (error=1) to most verbose (trace=6).
### <a id="NoOpLogFunction"></a>NoOpLogFunction
const NoOpLogFunction: (..._data) => undefined;
A log function that silently discards all arguments.
...unknown[]
undefined
### <a id="URL"></a>URL
const URL: {
(url, base?): URL;
prototype: URL;
canParse: boolean;
createObjectURL: string;
parse: URL | null;
revokeObjectURL: void;
};
Node.js-specific URL class, imported from the node:url module.
string | URL
string | URL
URL
prototype: URL;
canParse(input, base?): boolean;
string | URL
string | URL
boolean
createObjectURL(blob): string;
Blob
string
parse(input, base?): URL | null;
string | URL
string | URL
URL | null
revokeObjectURL(id): void;
string
void
### <a id="ZERO_ADDRESS"></a>ZERO_ADDRESS
const ZERO_ADDRESS: Address;
A 160-bit zero address constant.
### <a id="ZERO_HASH"></a>ZERO_HASH
const ZERO_HASH: Hash;
A 256-bit zero hash constant.
### <a id="asAnyObject"></a>asAnyObject
const asAnyObject: AsTypeFunction;
Type-narrowing function that casts a value to AnyObject if it is a plain object, or returns undefined.
### <a id="asJsonArray"></a>asJsonArray
const asJsonArray: {
<T> (value): T & unknown[] | undefined;
<T> (value, assert): T & unknown[];
};
Casts a value to JsonArray or returns undefined if it does not conform.
<T>(value): T & unknown[] | undefined;
T
T
T & unknown[] | undefined
<T>(value, assert): T & unknown[];
T
T
T & unknown[]
### <a id="asJsonObject"></a>asJsonObject
const asJsonObject: {
<T> (value): T & Record<string, unknown> | undefined;
<T> (value, assert): T & Record<string, unknown>;
};
Casts a value to JsonObject or returns undefined if it does not conform.
<T>(value): T & Record<string, unknown> | undefined;
T
T
T & Record<string, unknown> | undefined
<T>(value, assert): T & Record<string, unknown>;
T
T
T & Record<string, unknown>
### <a id="asJsonValue"></a>asJsonValue
const asJsonValue: {
<T> (value): T | undefined;
<T> (value, assert): T;
};
Casts a value to JsonValue or returns undefined if it does not conform.
<T>(value): T | undefined;
T
T
T | undefined
<T>(value, assert): T;
T
T
T
### <a id="assertError"></a>assertError
const assertError: (value, assert, defaultMessage) => undefined;
Throws an Error based on the assert configuration when a value fails validation.
unknown
The value being validated
AssertConfig | undefined
Assertion config controlling the error message
string
Fallback message if no custom message is provided
undefined
### <a id="axios"></a>axios
const axios: Axios;
use axiosJson instead
### <a id="axiosJson"></a>axiosJson
const axiosJson: Axios;
### <a id="bitsToNibbles"></a>bitsToNibbles
const bitsToNibbles: (value) => number;
Converts a bit count to the equivalent number of hex nibbles (4 bits each).
number
The number of bits (must be a multiple of 4)
number
The number of nibbles
### <a id="bufferPolyfill"></a>bufferPolyfill
const bufferPolyfill: () => void;
void
### <a id="clearTimeoutEx"></a>clearTimeoutEx
const clearTimeoutEx: (id) => void;
Cancels a timeout previously created with setTimeoutEx.
string
The timeout ID returned by setTimeoutEx.
void
### <a id="containsAll"></a>containsAll
const containsAll: <T>(source, target) => boolean;
Checks whether the source array contains every element in the target array.
T
T[]
The array to search within
T[]
The elements that must all be present
boolean
True if every target element exists in source
### <a id="createProfiler"></a>createProfiler
const createProfiler: () => Profiler;
Creates a new empty profiler instance.
### <a id="deepMerge"></a>deepMerge
const deepMerge: <T>(...objects) => MergeAll<T>;
Deeply merges multiple objects into a new object.
T extends AnyObject[]
...T
Multiple objects to merge deeply. The function merges properties from all objects into a new object. If a property exists in multiple objects, the last object's value will be used. If a property is an object, it will be merged recursively. If a property is an array, it will be overwritten by the last object's value. If a property is a primitive value, it will be overwritten by the last object's value. If a property is undefined in the source, it will be skipped. If a property is a symbol, it will be merged as well.
MergeAll<T>
A new object with the merged properties.
### <a id="defaultForgetNodeConfig"></a>defaultForgetNodeConfig
const defaultForgetNodeConfig: ForgetNodeConfig<unknown>;
Default Node.js forget configuration with termination disabled.
### <a id="delay"></a>delay
const delay: (ms) => Promise<unknown>;
Returns a promise that resolves after the specified number of milliseconds.
number
The number of milliseconds to delay.
Promise<unknown>
A promise that resolves after the delay.
### <a id="difference"></a>difference
const difference: <TKey>(a, b) => Set<TKey>;
Returns a new set containing elements in a that are not in b.
TKey
Set<TKey>
The source set
Set<TKey>
The set of elements to exclude
Set<TKey>
A new set representing the difference of a and b
### <a id="disableGloballyUnique"></a>disableGloballyUnique
const disableGloballyUnique: () => void;
Disables global uniqueness checks, allowing duplicate registrations without throwing.
void
### <a id="distinct"></a>distinct
const distinct: <T>(value, index, array) => boolean;
Array filter callback that removes duplicate values, with correct NaN handling.
Use with array.filter(distinct).
T
T
number
T[]
boolean
### <a id="ellipsize"></a>ellipsize
const ellipsize: (value, length?) => string;
Truncates a string to show the first and last length characters separated by an ellipsis.
string
The string to ellipsize
number
Number of characters to keep at each end (default 2)
string
The ellipsized string
### <a id="equalArrayBuffers"></a>equalArrayBuffers
const equalArrayBuffers: (a1, a2) => boolean;
Compares two ArrayBuffers for byte-level equality.
ArrayBufferLike
First buffer
ArrayBufferLike
Second buffer
boolean
True if the buffers have the same length and identical bytes
### <a id="exists"></a>exists
const exists: <T>(x?) => x is NonNullable<T>;
Used to type narrow an object which is possibly null or undefined. Works well with functional Array methods. For example:
T
T | null
The object which is potentially undefined or null
x is NonNullable<T>
False if the object is null/undefined, true otherwise
const payloads: XyoPayload[] = boundWitness._payloads?.filter(exists) || []
### <a id="filterAs"></a>filterAs
const filterAs: <In, Out>(x, predicate) => NonNullable<Out>[];
Maps each element using the predicate and filters out nullish results.
In
Out
In[]
The input array
(a) => Out
Transform function applied to each element
NonNullable<Out>[]
Array of non-nullish transformed values
### <a id="filterAsync"></a>filterAsync
const filterAsync: <T>(array, predicate) => Promise<T[]>;
Returns the elements of an array that meet the condition specified in a callback function.
T
T[]
The array to filter.
(value, index, array) => Promise<boolean>
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
Promise<T[]>
The elements of an array that meet the condition specified in a callback function.
### <a id="findAs"></a>findAs
const findAs: <In, Out>(x, predicate) => NonNullable<Out> | undefined;
Maps each element using the predicate and returns the first non-nullish result.
In
Out
In[]
The input array
(a) => Out
Transform function applied to each element
NonNullable<Out> | undefined
The first non-nullish transformed value, or undefined
### <a id="findLastAs"></a>findLastAs
const findLastAs: <In, Out>(x, predicate) => NonNullable<Out> | undefined;
Maps each element using the predicate and returns the last non-nullish result.
In
Out
In[]
The input array
(a) => Out
Transform function applied to each element
NonNullable<Out> | undefined
The last non-nullish transformed value, or undefined
### <a id="flatten"></a>flatten
const flatten: <T>(a?, b?) => T[];
Concatenates two values or arrays into a single flat array, filtering out nullish entries.
T
T | ConcatArray<T>
First value or array
T | ConcatArray<T>
Second value or array
T[]
A flat array of non-nullish elements
### <a id="forget"></a>forget
const forget: <T>(promise, config?) => void;
Node.js variant of forget that can optionally terminate the process on exceptions or timeouts.
T
Promisable<T>
The promise or promisable value to forget.
Optional Node.js-specific configuration including process termination options.
void
### <a id="fromFixedPoint"></a>fromFixedPoint
const fromFixedPoint: (value, places?) => bigint;
Converts a fixed-point bigint back to a whole-number bigint by dividing out the decimal places.
bigint
The fixed-point bigint value to convert
number
Number of decimal places (default 18)
bigint
The whole-number bigint result
### <a id="fulfilled"></a>fulfilled
const fulfilled: <T>(val) => val is PromiseFulfilledResult<T>;
For use with Promise.allSettled to filter only successful results
T
PromiseSettledResult<T>
val is PromiseFulfilledResult<T>
### <a id="fulfilledValues"></a>fulfilledValues
const fulfilledValues: <T>(previousValue, currentValue) => T[];
For use with Promise.allSettled to reduce to only successful result values
T
T[]
PromiseSettledResult<T>
T[]
const resolved = Promise.resolve('resolved')
const rejected = Promise.reject('rejected')
const settled = await Promise.allSettled([resolved, rejected])
const results = settled.reduce(fulfilledValues, [] as string[])
// results === [ 'resolved' ]
const resolved = Promise.resolve('resolved')
const rejected = Promise.reject('rejected')
const settled = await Promise.allSettled([resolved, rejected])
const results = settled.reduce<string[]>(fulfilledValues, [])
// results === [ 'resolved' ]
### <a id="functionName"></a>functionName
const functionName: (depth?) => string;
Returns the name of the calling function by inspecting the stack trace.
number
The stack frame depth to read the function name from (default: 2).
string
The function name, or '' if it cannot be determined.
### <a id="getApiStage"></a>getApiStage
const getApiStage: (hostname) => "beta" | "local" | "prod";
Determines the API stage based on the hostname.
string
The hostname to evaluate
"beta" | "local" | "prod"
The corresponding ApiStage (Local, Beta, or Prod)
### <a id="getFunctionName"></a>getFunctionName
const getFunctionName: (depth?) => string;
Retrieves the name of the calling function by inspecting the stack trace.
number
The stack frame depth to inspect (default: 2, the caller's caller).
string
The function name, or '' if it cannot be determined.
### <a id="globallyUnique"></a>globallyUnique
const globallyUnique: (name, value, domain?) => string;
Registers a value as globally unique under the given name and domain. Throws if a different value is already registered under the same key.
string | symbol
The unique name or symbol
unknown
The value to register
string
The namespace domain (default 'global')
string
The fully qualified unique name
### <a id="handleError"></a>handleError
const handleError: <T>(error, handler) => T;
Invokes the handler if the value is an Error, otherwise re-throws it.
T
any
The caught value to inspect
(error) => T
Callback invoked with the Error if it is one
T
The handler's return value
### <a id="handleErrorAsync"></a>handleErrorAsync
const handleErrorAsync: <T>(error, handler) => Promise<T>;
Async version of handleError. Invokes the async handler if the value is an Error, otherwise re-throws it.
T
any
The caught value to inspect
(error) => Promise<T>
Async callback invoked with the Error if it is one
Promise<T>
The handler's resolved return value
### <a id="hasAllLabels"></a>hasAllLabels
const hasAllLabels: (source?, required?) => boolean;
Returns true if the source object has all the labels from the required set
Source object to check against
Set of labels to check for in source
boolean
True of the source object has all the labels from the required set
### <a id="hexFrom"></a>hexFrom
const hexFrom: (value, config?) => Hex;
Takes unknown value and tries our best to convert it to a hex string
string | number | bigint | ArrayBufferLike
### <a id="hexFromArrayBuffer"></a>hexFromArrayBuffer
const hexFromArrayBuffer: (buffer, config?) => Hex;
Convert an ArrayBuffer to a hex string
ArrayBufferLike
### <a id="hexFromBigInt"></a>hexFromBigInt
const hexFromBigInt: (value, config?) => Hex;
Convert a bigint to a hex string
bigint
### <a id="hexFromHexString"></a>hexFromHexString
const hexFromHexString: (value, config?) => Hex;
Normalizes a hex string by stripping an optional 0x prefix, lowercasing, and padding to byte/bit boundaries.
string
The hex string to normalize (with or without 0x prefix)
Configuration for prefix, byteSize, and bitLength padding
The normalized Hex string
### <a id="hexFromNumber"></a>hexFromNumber
const hexFromNumber: (value, config?) => Hex;
Converts a number to a hex string by converting to BigInt first.
number
The number to convert
Optional hex output configuration
The hex string representation
### <a id="ifDefined"></a>ifDefined
const ifDefined: <T>(value, func) => T | undefined;
Invokes the callback only if the value is neither null nor undefined.
T
T
The value to check.
(value) => void
The callback to invoke with the value if it is defined.
T | undefined
The value if defined, or undefined otherwise.
### <a id="ifTypeOf"></a>ifTypeOf
const ifTypeOf: <T, R>(typeName, value, trueFunc, isFunc?) => R | undefined;
Invokes the callback if the value matches the specified type, with an optional additional predicate.
T
R
The expected type name to match against.
unknown
The value to check.
(value) => R
The callback to invoke if the type matches.
(value) => boolean
Optional additional predicate that must also return true.
R | undefined
The result of trueFunc if the type matches (and isFunc passes), or undefined.
### <a id="intersection"></a>intersection
const intersection: <TKey>(a, b) => Set<TKey>;
Returns a new set containing only elements present in both a and b.
TKey
Set<TKey>
The first set
Set<TKey>
The second set
Set<TKey>
A new set representing the intersection of a and b
### <a id="isAddress"></a>isAddress
const isAddress: (value?, config?) => value is Address;
Type guard that checks whether a value is a valid 160-bit address.
unknown
The value to check
Optional hex config (defaults to 160-bit, no prefix)
value is Address
True if the value is a valid Address
### <a id="isBrowser"></a>isBrowser
const isBrowser: () => boolean;
Returns whether the current environment is a browser. Always returns false in Node.js.
boolean
### <a id="isEthAddress"></a>isEthAddress
const isEthAddress: (value?, config?) => value is EthAddress;
Type guard that checks whether a value is a valid 0x-prefixed Ethereum address.
unknown
The value to check
Optional hex config (defaults to 160-bit with prefix)
value is EthAddress
True if the value is a valid EthAddress
### <a id="isEthAddressWrapper"></a>isEthAddressWrapper
const isEthAddressWrapper: (obj) => obj is { type: string } & EthAddressWrapper;
Type guard that checks if the given object is an instance of EthAddressWrapper.
string
obj is { type: string } & EthAddressWrapper
### <a id="isHash"></a>isHash
const isHash: (value, bitLength?) => value is Hash;
Type guard that checks whether a value is a valid hash of the specified bit length.
unknown
The value to check
The expected bit length of the hash (defaults to 256)
value is Hash
True if the value is a valid Hash
### <a id="isHashBitLength"></a>isHashBitLength
const isHashBitLength: (value) => value is HashBitLength;
Type guard that checks whether a value is a valid hash bit length.
unknown
The value to check
value is HashBitLength
True if the value is one of the supported HashBitLength values
### <a id="isHex"></a>isHex
const isHex: (value, config?) => value is Hex;
Type guard that checks whether a value is a valid hex string.
unknown
The value to check
Optional configuration for prefix and bit length validation
value is Hex
True if the value is a valid Hex string
### <a id="isHexZero"></a>isHexZero
const isHexZero: (value?) => boolean | undefined;
Checks whether a hex string represents a zero value.
string
The hex string to check
boolean | undefined
True if zero, false if non-zero, or undefined if the input is not a string
### <a id="isJsonArray"></a>isJsonArray
const isJsonArray: <T>(value) => value is T & unknown[];
Type guard that checks if a value is a valid JSON array.
T
T
value is T & unknown[]
### <a id="isJsonObject"></a>isJsonObject
const isJsonObject: <T>(value) => value is T & Record<string, unknown>;
Type guard that checks if a value is a valid JSON object.
T
T
value is T & Record<string, unknown>
### <a id="isJsonValue"></a>isJsonValue
const isJsonValue: <T>(value) => value is T;
Type guard that checks if a value is a valid JSON value.
T
T
value is T
### <a id="isLocalhost"></a>isLocalhost
const isLocalhost: (hostname) => boolean;
Checks whether a hostname refers to the local machine (localhost, 127.0.0.1, ::1, or *.localhost).
string
The hostname to check
boolean
true if the hostname is a localhost address
### <a id="isNode"></a>isNode
const isNode: () => boolean;
Returns whether the current environment is Node.js. Always returns true in this entry point.
boolean
### <a id="isType"></a>isType
const isType: (value, expectedType) => boolean;
Checks whether a value matches the expected field type, with correct handling for arrays and nulls.
unknown
The value to check.
The expected type string.
boolean
True if the value matches the expected type.
### <a id="isTypedArray"></a>isTypedArray
const isTypedArray: (value) => value is TypedArray;
Type guard that checks whether a value is a TypedArray (an array where every element is a TypedValue).
unknown
The value to check.
value is TypedArray
True if the value is an array of TypedValue elements.
### <a id="isTypedKey"></a>isTypedKey
const isTypedKey: (value) => value is TypedKey;
Type guard that checks whether a value is a valid TypedKey (string, bigint, number, or symbol).
unknown
The value to check.
value is TypedKey
True if the value is a valid TypedKey.
### <a id="isTypedObject"></a>isTypedObject
const isTypedObject: (value) => value is TypedObject;
Type guard that checks whether a value is a TypedObject (an object with TypedKey keys and TypedValue values).
unknown
The value to check.
value is TypedObject
True if the value is a valid TypedObject.
### <a id="isTypedValue"></a>isTypedValue
const isTypedValue: (value) => value is TypedValue;
Type guard that checks whether a value is a valid TypedValue.
unknown
The value to check.
value is TypedValue
True if the value is a string, number, boolean, null, TypedObject, or TypedArray.
### <a id="isValidTypedFieldPair"></a>isValidTypedFieldPair
const isValidTypedFieldPair: (pair) => pair is [key: TypedKey, value: TypedValue];
Type guard that checks whether a key-value pair has a valid TypedKey and TypedValue.
[unknown, unknown]
A tuple of [key, value] to validate.
pair is [key: TypedKey, value: TypedValue]
True if the key is a TypedKey and the value is a TypedValue.
### <a id="isWebworker"></a>isWebworker
const isWebworker: () => boolean;
Returns whether the current environment is a web worker. Always returns false in Node.js.
boolean
### <a id="nibblesToBits"></a>nibblesToBits
const nibblesToBits: (value) => number;
Converts a nibble count to the equivalent number of bits.
number
The number of nibbles
number
The number of bits
### <a id="omitBy"></a>omitBy
const omitBy: <T>(obj, predicate, maxDepth?) => Partial<T>;
Creates a new object excluding properties that satisfy the predicate, with optional recursive depth.
T extends EmptyObject
T
The source object to omit properties from.
A function that returns true for properties to exclude.
number
Maximum recursion depth for nested objects.
Partial<T>
A partial copy of the object without matching properties.
### <a id="omitByPrefix"></a>omitByPrefix
const omitByPrefix: <T, P>(payload, prefix, maxDepth?) => DeepOmitStartsWith<T, P>;
Omits all properties whose keys start with the given prefix, recursively through nested objects.
T extends EmptyObject
P extends string
T
The source object.
P
The string prefix to match keys against.
number
Maximum recursion depth.
DeepOmitStartsWith<T, P>
A new object without properties that have matching prefixed keys.
### <a id="padHex"></a>padHex
const padHex: (hex, byteCount?) => string;
string
number
string
### <a id="pickBy"></a>pickBy
const pickBy: <T>(obj, predicate, maxDepth?) => Partial<T>;
Creates a new object containing only the properties that satisfy the predicate, with optional recursive depth.
T extends EmptyObject
T
The source object to pick properties from.
A function that returns true for properties to include.
number
Maximum recursion depth for nested objects.
Partial<T>
A partial copy of the object with only matching properties.
### <a id="pickByPrefix"></a>pickByPrefix
const pickByPrefix: <T, P>(payload, prefix, maxDepth?) => DeepPickStartsWith<T, P>;
Picks all properties whose keys start with the given prefix, recursively through nested objects.
T extends EmptyObject
P extends string
T
The source object.
P
The string prefix to match keys against.
number
Maximum recursion depth.
DeepPickStartsWith<T, P>
A new object containing only properties with matching prefixed keys.
### <a id="profile"></a>profile
const profile: (profiler, name) => void;
Records a timestamp for the given profile name.
The profiler instance to record into.
string
The name of the timing entry.
void
### <a id="profileReport"></a>profileReport
const profileReport: (profiler) => Record<string, number>;
Generates a report of elapsed times for each profiled entry.
The profiler instance to report on.
Record<string, number>
A record mapping each profile name to its elapsed time in milliseconds, plus a '-all-' total.
### <a id="rejected"></a>rejected
const rejected: <T>(val) => val is PromiseRejectedResult;
For use with Promise.allSettled to filter only rejected results
T
PromiseSettledResult<T>
val is PromiseRejectedResult
### <a id="removeFields"></a>removeFields
const removeFields: <T, K>(obj, fields) => Omit<T, K>;
Returns a shallow copy of the object with the specified fields removed.
T extends EmptyObject
K extends keyof T
T
The source object.
K[]
An array of keys to remove.
Omit<T, K>
A new object without the specified fields.
### <a id="retry"></a>retry
const retry: <T>(func, config?) => Promise<T | undefined>;
Retries an async function with exponential backoff until it completes or retries are exhausted.
T = unknown
() => Promisable<T | undefined>
The function to retry.
Optional retry configuration including backoff, interval, retries, and completion check.
Promise<T | undefined>
The result of the function, or undefined if all retries were exhausted.
### <a id="setTimeoutEx"></a>setTimeoutEx
const setTimeoutEx: (func, delay) => string;
Sets a timeout using an optimized internal timer that coalesces multiple timeouts into a single native timer.
Function
The function to call after the delay.
number
The delay in milliseconds (must be >= 0).
string
A unique string ID that can be used with clearTimeoutEx to cancel the timeout.
### <a id="toAddress"></a>toAddress
const toAddress: (value, config?) => Address;
Converts a value to a 160-bit Address hex string.
string | number | bigint | ArrayBufferLike
The value to convert (string, number, bigint, or ArrayBuffer)
Optional hex config (defaults to 160-bit, no prefix)
The value as an Address
### <a id="toDecimalPrecision"></a>toDecimalPrecision
const toDecimalPrecision: (value, digits) => string;
Formats a number to the specified number of significant digits, returning a string with minimal trailing zeros.
number
The number to format
number
The number of significant digits
string
A string representation of the number with the specified precision
### <a id="toEthAddress"></a>toEthAddress
const toEthAddress: (value, config?) => EthAddress;
Converts a value to a 0x-prefixed Ethereum address string.
string | number | bigint | ArrayBufferLike
The value to convert (string, number, bigint, or ArrayBuffer)
Optional hex config (defaults to 160-bit, no inner prefix)
The value as an EthAddress
### <a id="toFixedPoint"></a>toFixedPoint
const toFixedPoint: (value, places?) => bigint;
Converts a bigint or decimal string to a fixed-point bigint representation.
bigint | string
The value to convert (bigint or string with optional decimal point)
number
Number of decimal places (default 18)
bigint
A bigint representing the value scaled by 10^places
### <a id="toHex"></a>toHex
const toHex: (value, config?) => BrandedHex;
takes any value and tries our best to convert it to a hex string
string | number | bigint | ArrayBufferLike
### <a id="toHexLegacy"></a>toHexLegacy
const toHexLegacy: (buffer) => string;
Converts an ArrayBuffer to a hex string without padding or normalization.
ArrayBuffer
The ArrayBuffer to convert
string
A lowercase hex string representation of the buffer
### <a id="toJsonArray"></a>toJsonArray
const toJsonArray: {
<T> (value): T & unknown[] | undefined;
<T> (value, assert): T & unknown[];
};
Parses a value into a JsonArray, throwing if it does not conform.
<T>(value): T & unknown[] | undefined;
T
T
T & unknown[] | undefined
<T>(value, assert): T & unknown[];
T
T
T & unknown[]
### <a id="toJsonObject"></a>toJsonObject
const toJsonObject: {
<T> (value): T & Record<string, unknown> | undefined;
<T> (value, assert): T & Record<string, unknown>;
};
Parses a value into a JsonObject, throwing if it does not conform.
<T>(value): T & Record<string, unknown> | undefined;
T
T
T & Record<string, unknown> | undefined
<T>(value, assert): T & Record<string, unknown>;
T
T
T & Record<string, unknown>
### <a id="toJsonValue"></a>toJsonValue
const toJsonValue: {
<T> (value): T | undefined;
<T> (value, assert): T;
};
Parses a value into a JsonValue, throwing if it does not conform.
<T>(value): T | undefined;
T
T
T | undefined
<T>(value, assert): T;
T
T
T
### <a id="toSafeJson"></a>toSafeJson
const toSafeJson: (value, maxDepth?) => JsonValue;
Converts a value to a JSON-safe representation, handling circular references and non-serializable types.
unknown
The value to convert.
number
Maximum recursion depth.
A JSON-safe value.
### <a id="toSafeJsonArray"></a>toSafeJsonArray
const toSafeJsonArray: (value, cycleList?, maxDepth?) => any[];
Converts an array to a JSON-safe array, handling circular references and depth limits.
unknown[]
The array to convert.
unknown[]
Tracks visited objects to detect circular references.
number
Maximum recursion depth before truncating.
any[]
A JSON-safe array representation.
### <a id="toSafeJsonObject"></a>toSafeJsonObject
const toSafeJsonObject: (value, cycleList?, maxDepth?) => JsonObject;
Converts an object to a JSON-safe object, handling circular references and depth limits.
object
The object to convert.
unknown[]
Tracks visited objects to detect circular references.
number
Maximum recursion depth before truncating.
A JSON-safe object representation.
### <a id="toSafeJsonString"></a>toSafeJsonString
const toSafeJsonString: (value, maxDepth?) => string;
Converts a value to a pretty-printed JSON string, safely handling circular references and non-JSON types.
unknown
The value to serialize.
number
Maximum recursion depth.
string
A formatted JSON string.
### <a id="toSafeJsonValue"></a>toSafeJsonValue
const toSafeJsonValue: (value, cycleList?, maxDepth?) => JsonValue;
Converts an unknown value to a JSON-safe value, replacing circular references with '[Circular]' and non-JSON types with descriptive placeholder strings.
unknown
The value to convert.
unknown[]
Tracks visited objects to detect circular references.
number
Maximum recursion depth before truncating with '[MaxDepth]'.
A JSON-safe representation of the value.
### <a id="typeOf"></a>typeOf
const typeOf: <T>(item) => TypeOfTypes;
Extended typeof that distinguishes arrays from objects (unlike native typeof).
T
T
The value to check.
The type of the item as a TypeOfTypes string.
### <a id="union"></a>union
const union: <TKey>(a, b) => Set<TKey>;
Returns a new set containing all elements from both a and b.
TKey
Set<TKey>
The first set
Set<TKey>
The second set
Set<TKey>
A new set representing the union of a and b
### <a id="uniq"></a>uniq
const uniq: <T>(arr) => T[];
Returns a new array with duplicate values removed.
T
T[]
The input array
T[]
A deduplicated array
### <a id="uniqBy"></a>uniqBy
const uniqBy: <T, I>(arr, iteratee) => T[];
Returns a new array with duplicates removed, using a key function for comparison.
T
I
T[]
The input array
(item) => I
Function that returns the key to compare by
T[]
A deduplicated array keeping the first occurrence of each key
### <a id="validateType"></a>validateType
const validateType: <T>(typeName, value, optional?) => [T | undefined, Error[]];
Validates that a value matches the expected type, returning the value and any errors.
T
The expected type name.
T
The value to validate.
boolean
If true, undefined values are accepted without error.
[T | undefined, Error[]]
A tuple of [value or undefined, array of errors].
FAQs
Base functionality used throughout XY Labs TypeScript/JavaScript libraries
The npm package @xylabs/sdk-js receives a total of 3,768 weekly downloads. As such, @xylabs/sdk-js popularity was classified as popular.
We found that @xylabs/sdk-js demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Research
Malicious Namastex.ai npm packages appear to replicate TeamPCP-style Canister Worm tradecraft, including exfiltration and self-propagation.

Product
Explore exportable charts for vulnerabilities, dependencies, and usage with Reports, Socket’s new extensible reporting framework.

Product
Socket for Jira lets teams turn alerts into Jira tickets with manual creation, automated ticketing rules, and two-way sync.