@syntrojs/singleton
Version:
A simple, type-safe abstraction for the singleton pattern. Works in Node.js, Bun, browsers, and vanilla JavaScript
68 lines (66 loc) • 1.95 kB
TypeScript
/**
* Registry Entry interface
*/
interface RegistryEntry<T = unknown> {
name: string;
instance: T;
type: string;
constructor: new (...args: unknown[]) => unknown;
}
/**
* Registry - A simple dictionary for storing and retrieving instances by name
*/
declare class Registry {
#private;
/**
* Stores an instance in the dictionary under a unique name.
*
* @param name - Unique name for the instance
* @param instance - The instance to store
* @param type - Optional type label (e.g., 'Redis', 'Axios'). If omitted, inferred from constructor
* @throws Error if name is already registered
*/
register<T>(name: string, instance: T, type?: string): void;
/**
* Retrieves the instance from the dictionary by its name.
*
* @param name - Name of the instance to retrieve
* @returns The stored instance
* @throws Error if instance is not found
*/
get<T>(name: string): T;
/**
* Returns metadata about a registered entry, including its name and type.
*
* @param name - Name of the entry
* @returns Registry entry metadata or undefined if not found
*/
getEntry(name: string): RegistryEntry | undefined;
/**
* Checks if an entry is registered under the name.
*
* @param name - Name to check
* @returns true if registered, false otherwise
*/
has(name: string): boolean;
/**
* Returns a list of all registered entries with their metadata.
*
* @returns Array of {name, type} objects
*/
list(): Array<{
name: string;
type: string;
}>;
/**
* Clears all registered entries. Useful for testing environments.
*/
clear(): void;
}
/**
* Returns the global instance of the Registry.
*
* @returns The singleton Registry instance
*/
declare function getRegistry(): Registry;
export { Registry, type RegistryEntry, getRegistry };