diff --git a/src/Instance.ts b/src/Instance.ts index e473e57..be4f684 100644 --- a/src/Instance.ts +++ b/src/Instance.ts @@ -26,10 +26,13 @@ export type Instance< _internal: _internal /** * Creates an instance. + * + * Note: This method is only available on instances created directly (not from a pool). + * When an instance is obtained from a pool via `pool.start()`, this method is not present. */ - create( + create?( parameters?: { port?: number | undefined } | undefined, - ): Omit, 'create'> + ): Instance<_internal> /** * Host the instance is running on. */ @@ -116,7 +119,7 @@ export function define< fn: define.DefineFn, ): define.ReturnType<_internal, parameters> { return (...[parametersOrOptions, options_]) => { - function create(createParameters: Parameters[0] = {}) { + function create(createParameters: { port?: number | undefined } = {}) { const parameters = parametersOrOptions as parameters const options = options_ || parametersOrOptions || {} diff --git a/src/Pool.ts b/src/Pool.ts index 82a449a..b4d35bb 100644 --- a/src/Pool.ts +++ b/src/Pool.ts @@ -2,14 +2,12 @@ import getPort from 'get-port' import type { Instance } from './Instance.js' -type Instance_ = Omit - export type Pool = Pick< - Map, + Map, 'entries' | 'keys' | 'forEach' | 'get' | 'has' | 'size' | 'values' > & { _internal: { - instance: Instance_ | ((key: key) => Instance_) + instance: Instance | ((key: key) => Instance) } destroy(key: key): Promise destroyAll(): Promise @@ -17,7 +15,7 @@ export type Pool = Pick< start( key: key, options?: { port?: number | undefined } | undefined, - ): Promise + ): Promise stop(key: key): Promise stopAll(): Promise } @@ -41,8 +39,7 @@ export function define( ): define.ReturnType { const { limit } = parameters - type Instance_ = Omit - const instances = new Map() + const instances = new Map() // Define promise instances for mutators to avoid race conditions, and return // identical instances of the promises (instead of duplicating them). @@ -52,7 +49,7 @@ export function define( destroy: new Map>(), destroyAll: undefined as Promise | undefined, restart: new Map>(), - start: new Map>(), + start: new Map>(), stop: new Map>(), stopAll: undefined as Promise | undefined, } @@ -117,7 +114,7 @@ export function define( const startPromise = promises.start.get(key) if (startPromise) return startPromise - const resolver = Promise.withResolvers() + const resolver = Promise.withResolvers() if (limit && instances.size >= limit) throw new Error(`Instance limit of ${limit} reached.`) @@ -130,7 +127,12 @@ export function define( : parameters.instance const { port = await getPort() } = options - const instance_ = instances.get(key) || instance.create({ port }) + const existingInstance = instances.get(key) + const instance_ = existingInstance || instance.create?.({ port }) + if (!instance_) + throw new Error( + `Instance "${instance.name}" does not have a create method.`, + ) instance_ .start() .then(() => {