43 lines
1.5 KiB
TypeScript
43 lines
1.5 KiB
TypeScript
import { normalizeStrategyName } from '../contracts/strategy-names';
|
|
import type { ModeManager } from '../core/ModeManager';
|
|
import type { ExecutionService } from '../services/ExecutionService';
|
|
import type { StrategyConfig } from '../types';
|
|
import type { BaseStrategy } from './BaseStrategy';
|
|
|
|
export interface StrategyDependencies {
|
|
modeManager: ModeManager;
|
|
execution: ExecutionService;
|
|
}
|
|
export type StrategyFactory = (
|
|
config: StrategyConfig,
|
|
dependencies: StrategyDependencies
|
|
) => BaseStrategy | Promise<BaseStrategy>;
|
|
|
|
/** Registration belongs to composition; strategy lifecycle belongs to the manager. */
|
|
export class StrategyRegistry {
|
|
private readonly factories = new Map<string, StrategyFactory>();
|
|
|
|
register(names: readonly string[], factory: StrategyFactory): this {
|
|
const keys = names.map(normalizeStrategyName);
|
|
if (!keys.length || keys.some(key => !key) || new Set(keys).size !== keys.length) {
|
|
throw new Error('Strategy aliases must be nonempty and distinct');
|
|
}
|
|
for (const key of keys) {
|
|
if (this.factories.has(key)) {
|
|
throw new Error(`Strategy alias already registered: ${key}`);
|
|
}
|
|
}
|
|
for (const key of keys) {
|
|
this.factories.set(key, factory);
|
|
}
|
|
return this;
|
|
}
|
|
|
|
async create(config: StrategyConfig, dependencies: StrategyDependencies): Promise<BaseStrategy> {
|
|
const factory = this.factories.get(normalizeStrategyName(config.name));
|
|
if (!factory) {
|
|
throw new Error(`Unknown strategy: ${config.name}`);
|
|
}
|
|
return factory(config, dependencies);
|
|
}
|
|
}
|