This commit is contained in:
2025-12-09 23:22:37 +01:00
parent 8fd8999e9e
commit a4a732ddc5
10 changed files with 1939 additions and 1519 deletions

View File

@@ -0,0 +1,286 @@
import 'reflect-metadata';
import { container, Lifecycle } from 'tsyringe';
import { DI_TOKENS } from './di-tokens';
import * as path from 'path';
import * as os from 'os';
// Domain & Application
import type { SessionRepositoryPort } from '@gridpilot/automation/application/ports/SessionRepositoryPort';
import type { IBrowserAutomation } from '@gridpilot/automation/application/ports/ScreenAutomationPort';
import type { AutomationEnginePort } from '@gridpilot/automation/application/ports/AutomationEnginePort';
import type { AuthenticationServicePort } from '@gridpilot/automation/application/ports/AuthenticationServicePort';
import type { LoggerPort } from '@gridpilot/automation/application/ports/LoggerPort';
import type { OverlaySyncPort } from '@gridpilot/automation/application/ports/OverlaySyncPort';
import { StartAutomationSessionUseCase } from '@gridpilot/automation/application/use-cases/StartAutomationSessionUseCase';
import { CheckAuthenticationUseCase } from '@gridpilot/automation/application/use-cases/CheckAuthenticationUseCase';
import { InitiateLoginUseCase } from '@gridpilot/automation/application/use-cases/InitiateLoginUseCase';
import { ClearSessionUseCase } from '@gridpilot/automation/application/use-cases/ClearSessionUseCase';
import { ConfirmCheckoutUseCase } from '@gridpilot/automation/application/use-cases/ConfirmCheckoutUseCase';
import { OverlaySyncService } from '@gridpilot/automation/application/services/OverlaySyncService';
// Infrastructure
import { InMemorySessionRepository } from '@gridpilot/automation/infrastructure/repositories/InMemorySessionRepository';
import {
MockBrowserAutomationAdapter,
PlaywrightAutomationAdapter,
AutomationAdapterMode,
FixtureServer,
} from '@gridpilot/automation/infrastructure/adapters/automation';
import { MockAutomationEngineAdapter } from '@gridpilot/automation/infrastructure/adapters/automation/engine/MockAutomationEngineAdapter';
import { AutomationEngineAdapter } from '@gridpilot/automation/infrastructure/adapters/automation/engine/AutomationEngineAdapter';
import { PinoLogAdapter } from '@gridpilot/automation/infrastructure/adapters/logging/PinoLogAdapter';
import { NoOpLogAdapter } from '@gridpilot/automation/infrastructure/adapters/logging/NoOpLogAdapter';
import {
loadAutomationConfig,
getAutomationMode,
AutomationMode,
BrowserModeConfigLoader,
} from '@gridpilot/automation/infrastructure/config';
import { loadLoggingConfig } from '@gridpilot/automation/infrastructure/config/LoggingConfig';
// Electron app safe wrapper
let electronApp: {
getAppPath?: () => string;
getPath?: (name: string) => string;
isPackaged?: boolean;
} | undefined;
try {
const _electron = require('electron');
electronApp = _electron?.app;
} catch {
electronApp = undefined;
}
/**
* Resolve session data path with test-tolerance
*/
export function resolveSessionDataPath(): string {
const userDataPath =
electronApp?.getPath?.('userData') ?? path.join(process.cwd(), 'userData') ?? os.tmpdir();
return path.join(userDataPath, 'iracing-session');
}
/**
* Resolve template path with test-tolerance
*/
export function resolveTemplatePath(): string {
const appPath = electronApp?.getAppPath?.() ?? process.cwd();
const isPackaged = electronApp?.isPackaged ?? false;
if (isPackaged) {
return path.join(appPath, 'resources/templates/iracing');
}
return path.join(appPath, '../../resources/templates/iracing');
}
/**
* Determine adapter mode based on environment
*/
function getAdapterMode(envMode: AutomationMode): AutomationAdapterMode {
return envMode === 'test' ? 'mock' : 'real';
}
/**
* Check if running in fixture hosted mode
*/
function isFixtureHostedMode(): boolean {
return process.env.NODE_ENV === 'test' && process.env.COMPANION_FIXTURE_HOSTED === '1';
}
/**
* Configure the DI container with all bindings
*/
export function configureDIContainer(): void {
// Clear any existing registrations
container.clearInstances();
// Configuration values
const automationMode = getAutomationMode();
const config = loadAutomationConfig();
const loggingConfig = loadLoggingConfig();
const fixtureMode = isFixtureHostedMode();
container.registerInstance(DI_TOKENS.AutomationMode, automationMode);
// Logger (singleton)
const logger = process.env.NODE_ENV === 'test' ? new NoOpLogAdapter() : new PinoLogAdapter(loggingConfig);
container.registerInstance<LoggerPort>(DI_TOKENS.Logger, logger);
// Browser Mode Config Loader (singleton)
const browserModeConfigLoader = new BrowserModeConfigLoader();
if (process.env.NODE_ENV === 'development') {
browserModeConfigLoader.setDevelopmentMode('headed');
}
container.registerInstance(DI_TOKENS.BrowserModeConfigLoader, browserModeConfigLoader);
// Session Repository (singleton)
container.register<SessionRepositoryPort>(
DI_TOKENS.SessionRepository,
{ useClass: InMemorySessionRepository },
{ lifecycle: Lifecycle.Singleton }
);
// Browser Automation Adapter (singleton)
const browserModeConfig = browserModeConfigLoader.load();
const adapterMode = getAdapterMode(config.mode);
const absoluteTemplatePath = resolveTemplatePath();
const sessionDataPath = resolveSessionDataPath();
const safeAppPath = electronApp?.getAppPath?.() ?? process.cwd();
const safeIsPackaged = electronApp?.isPackaged ?? false;
logger.debug('Resolved paths', {
absoluteTemplatePath,
sessionDataPath,
appPath: safeAppPath,
isPackaged: safeIsPackaged,
cwd: process.cwd(),
});
logger.info('Creating browser automation adapter', {
envMode: config.mode,
adapterMode,
browserMode: browserModeConfig.mode,
browserModeSource: browserModeConfig.source,
});
let browserAutomation: PlaywrightAutomationAdapter | MockBrowserAutomationAdapter;
switch (config.mode) {
case 'production':
case 'development':
browserAutomation = new PlaywrightAutomationAdapter(
{
headless: browserModeConfig.mode === 'headless',
mode: adapterMode,
userDataDir: sessionDataPath,
baseUrl: fixtureMode ? 'http://localhost:3456' : '',
},
logger.child({ adapter: 'Playwright', mode: adapterMode }),
browserModeConfigLoader
);
break;
case 'test':
default:
if (fixtureMode) {
browserAutomation = new PlaywrightAutomationAdapter(
{
headless: browserModeConfig.mode === 'headless',
timeout: config.defaultTimeout ?? 10_000,
baseUrl: 'http://localhost:3456',
mode: 'real',
userDataDir: sessionDataPath,
},
logger.child({ adapter: 'Playwright', mode: 'real' }),
browserModeConfigLoader
);
} else {
browserAutomation = new MockBrowserAutomationAdapter();
}
break;
}
container.registerInstance<IBrowserAutomation>(
DI_TOKENS.BrowserAutomation,
browserAutomation
);
// Automation Engine (singleton)
const sessionRepository = container.resolve<SessionRepositoryPort>(DI_TOKENS.SessionRepository);
let automationEngine: AutomationEnginePort;
if (fixtureMode) {
automationEngine = new AutomationEngineAdapter(
browserAutomation as any,
sessionRepository
);
} else {
automationEngine = new MockAutomationEngineAdapter(
browserAutomation,
sessionRepository
);
}
container.registerInstance<AutomationEnginePort>(
DI_TOKENS.AutomationEngine,
automationEngine
);
// Fixture Server (singleton, nullable)
if (fixtureMode) {
container.registerInstance(DI_TOKENS.FixtureServer, new FixtureServer());
}
// Use Cases - create singleton instance directly
const startAutomationUseCase = new StartAutomationSessionUseCase(
automationEngine,
browserAutomation,
sessionRepository
);
container.registerInstance(DI_TOKENS.StartAutomationUseCase, startAutomationUseCase);
// Authentication-related use cases (only if adapter supports it)
if (browserAutomation instanceof PlaywrightAutomationAdapter && !fixtureMode) {
const authService = browserAutomation as AuthenticationServicePort;
container.registerInstance(
DI_TOKENS.CheckAuthenticationUseCase,
new CheckAuthenticationUseCase(authService)
);
container.registerInstance(
DI_TOKENS.InitiateLoginUseCase,
new InitiateLoginUseCase(authService)
);
container.registerInstance(
DI_TOKENS.ClearSessionUseCase,
new ClearSessionUseCase(authService)
);
container.registerInstance<AuthenticationServicePort>(
DI_TOKENS.AuthenticationService,
authService
);
}
// Overlay Sync Service - create singleton instance directly
const lifecycleEmitter = browserAutomation as any;
const publisher = {
publish: async (_event: any) => {
try {
logger.debug?.('OverlaySyncPublisher.publish', _event);
} catch {
// swallow
}
},
} as any;
const overlaySyncService = new OverlaySyncService({
lifecycleEmitter,
publisher,
logger,
});
container.registerInstance(DI_TOKENS.OverlaySyncPort, overlaySyncService);
logger.info('DI container configured', {
automationMode: config.mode,
sessionRepositoryType: 'InMemorySessionRepository',
browserAutomationType: browserAutomation.constructor.name,
});
}
/**
* Reset the container (for testing)
*/
export function resetDIContainer(): void {
container.clearInstances();
}
/**
* Get the TSyringe container instance
*/
export function getDIContainer() {
return container;
}

View File

@@ -1,37 +1,23 @@
import { app } from 'electron';
import * as path from 'path';
import { InMemorySessionRepository } from '@/packages/automation/infrastructure/repositories/InMemorySessionRepository';
import {
MockBrowserAutomationAdapter,
PlaywrightAutomationAdapter,
AutomationAdapterMode,
FixtureServer,
} from '@/packages/automation/infrastructure/adapters/automation';
import { MockAutomationEngineAdapter } from '@/packages/automation/infrastructure/adapters/automation/engine/MockAutomationEngineAdapter';
import { AutomationEngineAdapter } from '@/packages/automation/infrastructure/adapters/automation/engine/AutomationEngineAdapter';
import { StartAutomationSessionUseCase } from '@/packages/automation/application/use-cases/StartAutomationSessionUseCase';
import { CheckAuthenticationUseCase } from '@/packages/automation/application/use-cases/CheckAuthenticationUseCase';
import { InitiateLoginUseCase } from '@/packages/automation/application/use-cases/InitiateLoginUseCase';
import { ClearSessionUseCase } from '@/packages/automation/application/use-cases/ClearSessionUseCase';
import { ConfirmCheckoutUseCase } from '@/packages/automation/application/use-cases/ConfirmCheckoutUseCase';
import {
loadAutomationConfig,
getAutomationMode,
AutomationMode,
BrowserModeConfigLoader,
} from '@/packages/automation/infrastructure/config';
import { PinoLogAdapter } from '@/packages/automation/infrastructure/adapters/logging/PinoLogAdapter';
import { NoOpLogAdapter } from '@/packages/automation/infrastructure/adapters/logging/NoOpLogAdapter';
import { loadLoggingConfig } from '@/packages/automation/infrastructure/config/LoggingConfig';
import 'reflect-metadata';
import { configureDIContainer, resetDIContainer, getDIContainer, resolveSessionDataPath, resolveTemplatePath } from './di-config';
import { DI_TOKENS } from './di-tokens';
import { PlaywrightAutomationAdapter, FixtureServer } from '@gridpilot/automation/infrastructure/adapters/automation';
import { StartAutomationSessionUseCase } from '@gridpilot/automation/application/use-cases/StartAutomationSessionUseCase';
import { CheckAuthenticationUseCase } from '@gridpilot/automation/application/use-cases/CheckAuthenticationUseCase';
import { InitiateLoginUseCase } from '@gridpilot/automation/application/use-cases/InitiateLoginUseCase';
import { ClearSessionUseCase } from '@gridpilot/automation/application/use-cases/ClearSessionUseCase';
import { ConfirmCheckoutUseCase } from '@gridpilot/automation/application/use-cases/ConfirmCheckoutUseCase';
import { getAutomationMode, AutomationMode, BrowserModeConfigLoader } from '@gridpilot/automation/infrastructure/config';
import type { SessionRepositoryPort } from '@gridpilot/automation/application/ports/SessionRepositoryPort';
import type { ScreenAutomationPort } from '@gridpilot/automation/application/ports/ScreenAutomationPort';
import type { IBrowserAutomation } from '@gridpilot/automation/application/ports/ScreenAutomationPort';
import type { AutomationEnginePort } from '@gridpilot/automation/application/ports/AutomationEnginePort';
import type { AuthenticationServicePort } from '@gridpilot/automation/application/ports/AuthenticationServicePort';
import type { CheckoutConfirmationPort } from '@gridpilot/automation/application/ports/CheckoutConfirmationPort';
import type { LoggerPort } from '@gridpilot/automation/application/ports/LoggerPort';
import type { OverlaySyncPort } from '@gridpilot/automation/application/ports/OverlaySyncPort';
import type { IAutomationLifecycleEmitter } from '@/packages/automation/infrastructure/adapters/IAutomationLifecycleEmitter';
import { OverlaySyncService } from '@/packages/automation/application/services/OverlaySyncService';
// Re-export for backward compatibility
export { resolveSessionDataPath, resolveTemplatePath };
export interface BrowserConnectionResult {
success: boolean;
@@ -39,275 +25,50 @@ export interface BrowserConnectionResult {
}
/**
* Test-tolerant resolution of the path to store persistent browser session data.
* When Electron's `app` is unavailable (e.g., in vitest), fall back to safe defaults.
*
* @returns Absolute path to the iracing session directory
* Check if running in fixture hosted mode
*/
import * as os from 'os';
// Use a runtime-safe wrapper around Electron's `app` so importing this module
// in a plain Node/Vitest environment does not throw. We intentionally avoid
// top-level `app.*` calls without checks. (test-tolerance)
let electronApp: {
getAppPath?: () => string;
getPath?: (name: string) => string;
isPackaged?: boolean;
} | undefined;
try {
// Require inside try/catch to avoid module resolution errors in test env.
// eslint-disable-next-line @typescript-eslint/no-var-requires
const _electron = require('electron');
electronApp = _electron?.app;
} catch {
electronApp = undefined;
}
export function resolveSessionDataPath(): string {
// Prefer Electron userData if available, otherwise use os.tmpdir() as a safe fallback.
const userDataPath =
electronApp?.getPath?.('userData') ?? path.join(process.cwd(), 'userData') ?? os.tmpdir();
return path.join(userDataPath, 'iracing-session');
}
/**
* Resolve the absolute path to the template directory.
* Handles both development and production (packaged) Electron environments.
*
* @returns Absolute path to the iracing templates directory
*/
export function resolveTemplatePath(): string {
// Test-tolerant resolution of template path. Use Electron app when available,
// otherwise fall back to process.cwd(). Preserve original runtime behavior when
// Electron's app is present (test-tolerance).
const appPath = electronApp?.getAppPath?.() ?? process.cwd();
const isPackaged = electronApp?.isPackaged ?? false;
if (isPackaged) {
return path.join(appPath, 'resources/templates/iracing');
}
// Development or unknown environment: prefer project-relative resources.
return path.join(appPath, '../../resources/templates/iracing');
}
/**
* Create logger based on environment configuration.
* In test environment, returns NoOpLogAdapter for silent logging.
*/
function createLogger(): LoggerPort {
const config = loadLoggingConfig();
if (process.env.NODE_ENV === 'test') {
return new NoOpLogAdapter();
}
return new PinoLogAdapter(config);
}
/**
* Determine the adapter mode based on environment.
* - 'production' → 'real' (uses iRacing website selectors)
* - 'development' → 'real' (uses iRacing website selectors)
* - 'test' → 'mock' (uses data-* attribute selectors)
*/
function getAdapterMode(envMode: AutomationMode): AutomationAdapterMode {
return envMode === 'test' ? 'mock' : 'real';
}
function isFixtureHostedMode(): boolean {
return process.env.NODE_ENV === 'test' && process.env.COMPANION_FIXTURE_HOSTED === '1';
}
/**
* Create screen automation adapter based on configuration mode.
*
* Mode mapping:
* - 'production' → PlaywrightAutomationAdapter with mode='real' for iRacing website
* - 'development' → PlaywrightAutomationAdapter with mode='real' for iRacing website
* - 'test' → MockBrowserAutomationAdapter
*
* @param mode - The automation mode from configuration
* @param logger - Logger instance for the adapter
* @returns PlaywrightAutomationAdapter instance (implements both IScreenAutomation and IAuthenticationService)
* DIContainer - Facade over TSyringe container for backward compatibility
*/
function createBrowserAutomationAdapter(
mode: AutomationMode,
logger: ILogger,
browserModeConfigLoader: BrowserModeConfigLoader,
options?: { fixtureBaseUrl?: string; forcePlaywrightReal?: boolean }
): PlaywrightAutomationAdapter | MockBrowserAutomationAdapter {
const config = loadAutomationConfig();
// Resolve absolute template path for Electron or fallback environments
const absoluteTemplatePath = resolveTemplatePath();
const sessionDataPath = resolveSessionDataPath();
// Use safe accessors for app metadata to avoid throwing in test env (test-tolerance).
const safeAppPath = electronApp?.getAppPath?.() ?? process.cwd();
const safeIsPackaged = electronApp?.isPackaged ?? false;
logger.debug('Resolved paths', {
absoluteTemplatePath,
sessionDataPath,
appPath: safeAppPath,
isPackaged: safeIsPackaged,
cwd: process.cwd()
});
const adapterMode = getAdapterMode(mode);
// Get browser mode configuration from provided loader
const browserModeConfig = browserModeConfigLoader.load();
logger.info('Creating browser automation adapter', {
envMode: mode,
adapterMode,
browserMode: browserModeConfig.mode,
browserModeSource: browserModeConfig.source,
});
switch (mode) {
case 'production':
case 'development':
return new PlaywrightAutomationAdapter(
{
headless: browserModeConfig.mode === 'headless',
mode: adapterMode,
userDataDir: sessionDataPath,
baseUrl: options?.fixtureBaseUrl ?? '',
},
logger.child({ adapter: 'Playwright', mode: adapterMode }),
browserModeConfigLoader
);
case 'test':
default:
if (options?.forcePlaywrightReal) {
return new PlaywrightAutomationAdapter(
{
headless: browserModeConfig.mode === 'headless',
timeout: config.defaultTimeout ?? 10_000,
baseUrl: options.fixtureBaseUrl ?? '',
mode: 'real',
userDataDir: sessionDataPath,
},
logger.child({ adapter: 'Playwright', mode: 'real' }),
browserModeConfigLoader
);
}
return new MockBrowserAutomationAdapter();
}
}
export class DIContainer {
private static instance: DIContainer;
private logger: LoggerPort;
private sessionRepository!: SessionRepositoryPort;
private browserAutomation!: PlaywrightAutomationAdapter | MockBrowserAutomationAdapter;
private automationEngine!: AutomationEnginePort;
private fixtureServer: FixtureServer | null = null;
private startAutomationUseCase!: StartAutomationSessionUseCase;
private checkAuthenticationUseCase: CheckAuthenticationUseCase | null = null;
private initiateLoginUseCase: InitiateLoginUseCase | null = null;
private clearSessionUseCase: ClearSessionUseCase | null = null;
private confirmCheckoutUseCase: ConfirmCheckoutUseCase | null = null;
private automationMode: AutomationMode;
private browserModeConfigLoader: BrowserModeConfigLoader;
private overlaySyncService?: OverlaySyncService;
private initialized = false;
private automationMode: AutomationMode;
private fixtureServer: FixtureServer | null = null;
private confirmCheckoutUseCase: ConfirmCheckoutUseCase | null = null;
private constructor() {
// Initialize logger first - it's needed by other components
this.logger = createLogger();
this.automationMode = getAutomationMode();
this.logger.info('DIContainer initializing', {
automationMode: this.automationMode,
nodeEnv: process.env.NODE_ENV
});
// Defer heavy initialization that may touch Electron/app paths until first use.
// Keep BrowserModeConfigLoader available immediately so callers can inspect it.
this.browserModeConfigLoader = new BrowserModeConfigLoader();
// Ensure the DIContainer exposes a development-visible default in interactive dev environment.
// Some integration/smoke tests expect the DI-provided loader to default to 'headed' in development.
if (process.env.NODE_ENV === 'development') {
this.browserModeConfigLoader.setDevelopmentMode('headed');
}
}
/**
* Lazily perform initialization that may access Electron APIs or filesystem.
* Called on first demand by methods that require the heavy components.
* Lazily initialize the TSyringe container
*/
private ensureInitialized(): void {
if (this.initialized) return;
const config = loadAutomationConfig();
this.sessionRepository = new InMemorySessionRepository();
const fixtureMode = isFixtureHostedMode();
const fixtureBaseUrl = fixtureMode ? 'http://localhost:3456' : undefined;
this.browserAutomation = createBrowserAutomationAdapter(
config.mode,
this.logger,
this.browserModeConfigLoader,
{ fixtureBaseUrl, forcePlaywrightReal: fixtureMode }
);
if (fixtureMode) {
this.fixtureServer = new FixtureServer();
this.automationEngine = new AutomationEngineAdapter(
this.browserAutomation as IScreenAutomation,
this.sessionRepository
);
} else {
this.automationEngine = new MockAutomationEngineAdapter(
this.browserAutomation,
this.sessionRepository
);
}
this.startAutomationUseCase = new StartAutomationSessionUseCase(
this.automationEngine,
this.browserAutomation,
this.sessionRepository
);
if (this.browserAutomation instanceof PlaywrightAutomationAdapter && !fixtureMode) {
const authService = this.browserAutomation as IAuthenticationService;
this.checkAuthenticationUseCase = new CheckAuthenticationUseCase(authService);
this.initiateLoginUseCase = new InitiateLoginUseCase(authService);
this.clearSessionUseCase = new ClearSessionUseCase(authService);
} else {
this.checkAuthenticationUseCase = null;
this.initiateLoginUseCase = null;
this.clearSessionUseCase = null;
}
this.logger.info('DIContainer initialized', {
automationMode: config.mode,
sessionRepositoryType: 'InMemorySessionRepository',
browserAutomationType: this.getBrowserAutomationType(config.mode)
configureDIContainer();
const logger = getDIContainer().resolve<LoggerPort>(DI_TOKENS.Logger);
logger.info('DIContainer initialized', {
automationMode: this.automationMode,
nodeEnv: process.env.NODE_ENV,
});
this.initialized = true;
}
private getBrowserAutomationType(mode: AutomationMode): string {
switch (mode) {
case 'production':
case 'development':
return 'PlaywrightAutomationAdapter';
case 'test':
default:
return 'MockBrowserAutomationAdapter';
const fixtureMode = isFixtureHostedMode();
if (fixtureMode) {
try {
this.fixtureServer = getDIContainer().resolve<FixtureServer>(DI_TOKENS.FixtureServer);
} catch {
// FixtureServer not registered in non-fixture mode
}
}
this.initialized = true;
}
public static getInstance(): DIContainer {
@@ -319,91 +80,110 @@ export class DIContainer {
public getStartAutomationUseCase(): StartAutomationSessionUseCase {
this.ensureInitialized();
return this.startAutomationUseCase;
return getDIContainer().resolve<StartAutomationSessionUseCase>(DI_TOKENS.StartAutomationUseCase);
}
public getSessionRepository(): SessionRepositoryPort {
this.ensureInitialized();
return this.sessionRepository;
return getDIContainer().resolve<SessionRepositoryPort>(DI_TOKENS.SessionRepository);
}
public getAutomationEngine(): AutomationEnginePort {
this.ensureInitialized();
return this.automationEngine;
return getDIContainer().resolve<AutomationEnginePort>(DI_TOKENS.AutomationEngine);
}
public getAutomationMode(): AutomationMode {
return this.automationMode;
}
public getBrowserAutomation(): ScreenAutomationPort {
public getBrowserAutomation(): IBrowserAutomation {
this.ensureInitialized();
return this.browserAutomation;
return getDIContainer().resolve<IBrowserAutomation>(DI_TOKENS.BrowserAutomation);
}
public getLogger(): LoggerPort {
return this.logger;
this.ensureInitialized();
return getDIContainer().resolve<LoggerPort>(DI_TOKENS.Logger);
}
public getCheckAuthenticationUseCase(): CheckAuthenticationUseCase | null {
this.ensureInitialized();
return this.checkAuthenticationUseCase;
try {
return getDIContainer().resolve<CheckAuthenticationUseCase>(DI_TOKENS.CheckAuthenticationUseCase);
} catch {
return null;
}
}
public getInitiateLoginUseCase(): InitiateLoginUseCase | null {
this.ensureInitialized();
return this.initiateLoginUseCase;
try {
return getDIContainer().resolve<InitiateLoginUseCase>(DI_TOKENS.InitiateLoginUseCase);
} catch {
return null;
}
}
public getClearSessionUseCase(): ClearSessionUseCase | null {
this.ensureInitialized();
return this.clearSessionUseCase;
try {
return getDIContainer().resolve<ClearSessionUseCase>(DI_TOKENS.ClearSessionUseCase);
} catch {
return null;
}
}
public getAuthenticationService(): AuthenticationServicePort | null {
this.ensureInitialized();
if (this.browserAutomation instanceof PlaywrightAutomationAdapter) {
return this.browserAutomation as AuthenticationServicePort;
try {
return getDIContainer().resolve<AuthenticationServicePort>(DI_TOKENS.AuthenticationService);
} catch {
return null;
}
return null;
}
public setConfirmCheckoutUseCase(
checkoutConfirmationPort: CheckoutConfirmationPort
): void {
public setConfirmCheckoutUseCase(checkoutConfirmationPort: CheckoutConfirmationPort): void {
this.ensureInitialized();
// Create ConfirmCheckoutUseCase with checkout service from browser automation
// and the provided confirmation port
const browserAutomation = getDIContainer().resolve<IBrowserAutomation>(DI_TOKENS.BrowserAutomation);
this.confirmCheckoutUseCase = new ConfirmCheckoutUseCase(
this.browserAutomation as any, // implements ICheckoutService
browserAutomation as any,
checkoutConfirmationPort
);
}
public getConfirmCheckoutUseCase(): ConfirmCheckoutUseCase | null {
this.ensureInitialized();
return this.confirmCheckoutUseCase;
}
/**
* Initialize automation connection based on mode.
* In production/development mode, connects via Playwright browser automation.
* In test mode, returns success immediately (no connection needed).
*/
public getBrowserModeConfigLoader(): BrowserModeConfigLoader {
this.ensureInitialized();
return getDIContainer().resolve<BrowserModeConfigLoader>(DI_TOKENS.BrowserModeConfigLoader);
}
public getOverlaySyncPort(): OverlaySyncPort {
this.ensureInitialized();
return getDIContainer().resolve<OverlaySyncPort>(DI_TOKENS.OverlaySyncPort);
}
public async initializeBrowserConnection(): Promise<BrowserConnectionResult> {
this.ensureInitialized();
const fixtureMode = isFixtureHostedMode();
this.logger.info('Initializing automation connection', { mode: this.automationMode, fixtureMode });
const logger = this.getLogger();
logger.info('Initializing automation connection', { mode: this.automationMode, fixtureMode });
if (this.automationMode === 'production' || this.automationMode === 'development' || fixtureMode) {
try {
if (fixtureMode && this.fixtureServer && !this.fixtureServer.isRunning()) {
await this.fixtureServer.start();
}
const playwrightAdapter = this.browserAutomation as PlaywrightAutomationAdapter;
const browserAutomation = this.getBrowserAutomation();
const playwrightAdapter = browserAutomation as PlaywrightAutomationAdapter;
const result = await playwrightAdapter.connect();
if (!result.success) {
this.logger.error(
logger.error(
'Automation connection failed',
new Error(result.error || 'Unknown error'),
{ mode: this.automationMode }
@@ -416,7 +196,7 @@ export class DIContainer {
if (!isConnected || !page) {
const errorMsg = 'Browser not connected';
this.logger.error(
logger.error(
'Automation connection reported success but has no usable page',
new Error(errorMsg),
{ mode: this.automationMode, isConnected, hasPage: !!page }
@@ -424,143 +204,77 @@ export class DIContainer {
return { success: false, error: errorMsg };
}
this.logger.info('Automation connection established', {
logger.info('Automation connection established', {
mode: this.automationMode,
adapter: 'Playwright'
adapter: 'Playwright',
});
return { success: true };
} catch (error) {
const errorMsg =
error instanceof Error ? error.message : 'Failed to initialize Playwright';
this.logger.error(
const errorMsg = error instanceof Error ? error.message : 'Failed to initialize Playwright';
logger.error(
'Automation connection failed',
error instanceof Error ? error : new Error(errorMsg),
{ mode: this.automationMode }
);
return {
success: false,
error: errorMsg
error: errorMsg,
};
}
}
this.logger.debug('Test mode - no automation connection needed');
logger.debug('Test mode - no automation connection needed');
return { success: true };
}
/**
* Shutdown the container and cleanup resources.
* Should be called when the application is closing.
*/
public async shutdown(): Promise<void> {
this.ensureInitialized();
this.logger.info('DIContainer shutting down');
if (this.browserAutomation && 'disconnect' in this.browserAutomation) {
const logger = this.getLogger();
logger.info('DIContainer shutting down');
const browserAutomation = this.getBrowserAutomation();
if (browserAutomation && 'disconnect' in browserAutomation) {
try {
await (this.browserAutomation as PlaywrightAutomationAdapter).disconnect();
this.logger.info('Automation adapter disconnected');
await (browserAutomation as PlaywrightAutomationAdapter).disconnect();
logger.info('Automation adapter disconnected');
} catch (error) {
this.logger.error('Error disconnecting automation adapter', error instanceof Error ? error : new Error('Unknown error'));
logger.error(
'Error disconnecting automation adapter',
error instanceof Error ? error : new Error('Unknown error')
);
}
}
if (this.fixtureServer && this.fixtureServer.isRunning()) {
try {
await this.fixtureServer.stop();
this.logger.info('FixtureServer stopped');
logger.info('FixtureServer stopped');
} catch (error) {
this.logger.error('Error stopping FixtureServer', error instanceof Error ? error : new Error('Unknown error'));
logger.error('Error stopping FixtureServer', error instanceof Error ? error : new Error('Unknown error'));
} finally {
this.fixtureServer = null;
}
}
this.logger.info('DIContainer shutdown complete');
logger.info('DIContainer shutdown complete');
}
/**
* Get the browser mode configuration loader.
* Provides access to runtime browser mode control (headed/headless).
*/
public getBrowserModeConfigLoader(): BrowserModeConfigLoader {
return this.browserModeConfigLoader;
}
public getOverlaySyncPort(): OverlaySyncPort {
this.ensureInitialized();
if (!this.overlaySyncService) {
// Use the browser automation adapter as the lifecycle emitter when available.
const lifecycleEmitter = this.browserAutomation as unknown as IAutomationLifecycleEmitter;
// Lightweight in-process publisher (best-effort no-op). The ipc handlers will forward lifecycle events to renderer.
const publisher = {
publish: async (_event: any) => {
try {
this.logger.debug?.('OverlaySyncPublisher.publish', _event);
} catch {
// swallow
}
}
} as any;
this.overlaySyncService = new OverlaySyncService({
lifecycleEmitter,
publisher,
logger: this.logger
});
}
return this.overlaySyncService;
}
/**
* Recreate browser automation and related use-cases from the current
* BrowserModeConfigLoader state. This allows runtime changes to the
* development-mode headed/headless setting to take effect without
* restarting the whole process.
*/
public refreshBrowserAutomation(): void {
this.ensureInitialized();
const config = loadAutomationConfig();
// Recreate browser automation adapter using current loader state
this.browserAutomation = createBrowserAutomationAdapter(
config.mode,
this.logger,
this.browserModeConfigLoader
);
// Recreate automation engine and start use case to pick up new adapter
this.automationEngine = new MockAutomationEngineAdapter(
this.browserAutomation,
this.sessionRepository
);
this.startAutomationUseCase = new StartAutomationSessionUseCase(
this.automationEngine,
this.browserAutomation,
this.sessionRepository
);
// Recreate authentication use-cases if adapter supports them, otherwise clear
if (this.browserAutomation instanceof PlaywrightAutomationAdapter) {
const authService = this.browserAutomation as AuthenticationServicePort;
this.checkAuthenticationUseCase = new CheckAuthenticationUseCase(authService);
this.initiateLoginUseCase = new InitiateLoginUseCase(authService);
this.clearSessionUseCase = new ClearSessionUseCase(authService);
} else {
this.checkAuthenticationUseCase = null;
this.initiateLoginUseCase = null;
this.clearSessionUseCase = null;
}
this.logger.info('Browser automation refreshed from updated BrowserModeConfigLoader', {
browserMode: this.browserModeConfigLoader.load().mode
// Reconfigure the entire container to pick up new browser mode settings
resetDIContainer();
this.initialized = false;
this.ensureInitialized();
const logger = this.getLogger();
const browserModeConfigLoader = this.getBrowserModeConfigLoader();
logger.info('Browser automation refreshed from updated BrowserModeConfigLoader', {
browserMode: browserModeConfigLoader.load().mode,
});
}
/**
* Reset the singleton instance (useful for testing with different configurations).
*/
public static resetInstance(): void {
resetDIContainer();
DIContainer.instance = undefined as unknown as DIContainer;
}
}

View File

@@ -0,0 +1,35 @@
/**
* Dependency Injection tokens for TSyringe container
*/
export const DI_TOKENS = {
// Core Services
Logger: Symbol.for('LoggerPort'),
// Repositories
SessionRepository: Symbol.for('SessionRepositoryPort'),
// Adapters
BrowserAutomation: Symbol.for('ScreenAutomationPort'),
AutomationEngine: Symbol.for('AutomationEnginePort'),
AuthenticationService: Symbol.for('AuthenticationServicePort'),
// Configuration
AutomationMode: Symbol.for('AutomationMode'),
BrowserModeConfigLoader: Symbol.for('BrowserModeConfigLoader'),
// Use Cases
StartAutomationUseCase: Symbol.for('StartAutomationSessionUseCase'),
CheckAuthenticationUseCase: Symbol.for('CheckAuthenticationUseCase'),
InitiateLoginUseCase: Symbol.for('InitiateLoginUseCase'),
ClearSessionUseCase: Symbol.for('ClearSessionUseCase'),
ConfirmCheckoutUseCase: Symbol.for('ConfirmCheckoutUseCase'),
// Services
OverlaySyncPort: Symbol.for('OverlaySyncPort'),
// Infrastructure
FixtureServer: Symbol.for('FixtureServer'),
} as const;
export type DITokens = typeof DI_TOKENS;