Fix script deletion during execution on desktop
This commit fixes an issue seen on certain Windows environments (Windows 10 22H2 and 11 23H2 Pro Azure VMs) where scripts were being deleted during execution due to temporary directory usage. To resolve this, scripts are now stored in a persistent directory, enhancing reliability for long-running scripts and improving auditability along with troubleshooting. Key changes: - Move script execution logic to the `main` process from `preloader` to utilize Electron's `app.getPath`. - Improve runtime environment detection for non-browser environments to allow its usage in Electron main process. - Introduce a secure module to expose IPC channels from the main process to the renderer via the preloader process. Supporting refactorings include: - Simplify `CodeRunner` interface by removing the `tempScriptFolderName` parameter. - Rename `NodeSystemOperations` to `NodeElectronSystemOperations` as it now wraps electron APIs too, and convert it to class for simplicity. - Rename `TemporaryFileCodeRunner` to `ScriptFileCodeRunner` to reflect its new functinoality. - Rename `SystemOperations` folder to `System` for simplicity. - Rename `HostRuntimeEnvironment` to `BrowserRuntimeEnvironment` for clarity. - Refactor main Electron process configuration to align with latest Electron documentation/recommendations. - Refactor unit tests `BrowserRuntimeEnvironment` to simplify singleton workaround. - Use alias imports like `electron/main` and `electron/common` for better clarity.
This commit is contained in:
@@ -32,8 +32,11 @@ privacy.sexy adopts a defense in depth strategy to protect users on multiple lay
|
||||
privacy.sexy actively follows security guidelines from the Open Web Application Security Project (OWASP) at strictest level.
|
||||
This approach protects against attacks like Cross Site Scripting (XSS) and data injection.
|
||||
- **Host System Access Control:**
|
||||
The desktop application segregates code sections based on their access levels.
|
||||
The desktop application segregates and isolates code sections based on their access levels through sandboxing.
|
||||
This provides a critical defense mechanism, prevents attackers from introducing harmful code into the app, known as injection attacks.
|
||||
- **Auditing and Transparency:**
|
||||
The desktop application improves security and transparency by logging application activities and retaining files of executed scripts
|
||||
This facilitates detailed auditability and effective troubleshooting, contributing to the integrity and reliability of the application.
|
||||
|
||||
### Update Security and Integrity
|
||||
|
||||
|
||||
@@ -50,5 +50,12 @@ Log file locations vary by operating system:
|
||||
|
||||
### Script execution
|
||||
|
||||
Direct execution of scripts is possible in the desktop version, offering a more integrated experience.
|
||||
This functionality is not present in the web version due to browser limitations.
|
||||
The desktop version of privacy.sexy enables direct script execution, providing a seamless and integrated experience.
|
||||
This direct execution capability isn't available in the web version due to inherent browser restrictions.
|
||||
|
||||
For enhanced auditability and easier troubleshooting, the desktop version keeps a record of executed scripts in designated directories.
|
||||
These locations vary based on the operating system:
|
||||
|
||||
- macOS: `$HOME/Library/Application Support/privacy.sexy/runs`
|
||||
- Linux: `$HOME/.config/privacy.sexy/runs`
|
||||
- Windows: `%APPDATA%\privacy.sexy\runs`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { resolve } from 'node:path';
|
||||
import { mergeConfig, UserConfig } from 'vite';
|
||||
import { defineConfig, externalizeDepsPlugin } from 'electron-vite';
|
||||
import { getAliasesFromTsConfig, getClientEnvironmentVariables } from './vite-config-helper';
|
||||
import { getAliases, getClientEnvironmentVariables } from './vite-config-helper';
|
||||
import { createVueConfig } from './vite.config';
|
||||
import distDirs from './dist-dirs.json' assert { type: 'json' };
|
||||
|
||||
@@ -54,7 +54,9 @@ function getSharedElectronConfig(options: {
|
||||
},
|
||||
rollupOptions: {
|
||||
output: {
|
||||
entryFileNames: '[name].cjs', // This is needed so `type="module"` works
|
||||
// Mark: electron-esm-support
|
||||
// This is needed so `type="module"` works
|
||||
entryFileNames: '[name].cjs',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -64,7 +66,7 @@ function getSharedElectronConfig(options: {
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
...getAliasesFromTsConfig(),
|
||||
...getAliases(),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
export interface CodeRunner {
|
||||
runCode(
|
||||
code: string,
|
||||
tempScriptFolderName: string,
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { IApplicationContext } from '@/application/Context/IApplicationContext';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { IApplication } from '@/domain/IApplication';
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
import { IApplicationFactory } from '../IApplicationFactory';
|
||||
import { ApplicationFactory } from '../ApplicationFactory';
|
||||
import { ApplicationContext } from './ApplicationContext';
|
||||
|
||||
export async function buildContext(
|
||||
factory: IApplicationFactory = ApplicationFactory.Current,
|
||||
environment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||
environment = CurrentEnvironment,
|
||||
): Promise<IApplicationContext> {
|
||||
const app = await factory.getApp();
|
||||
const os = getInitialOs(app, environment.os);
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { SystemOperations } from '../../System/SystemOperations';
|
||||
import { NodeElectronSystemOperations } from '../../System/NodeElectronSystemOperations';
|
||||
import { ScriptDirectoryProvider } from './ScriptDirectoryProvider';
|
||||
|
||||
export const ExecutionSubdirectory = 'runs';
|
||||
|
||||
export class PersistentDirectoryProvider implements ScriptDirectoryProvider {
|
||||
constructor(
|
||||
private readonly system: SystemOperations = new NodeElectronSystemOperations(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
) { }
|
||||
|
||||
async provideScriptDirectory(): Promise<string> {
|
||||
const scriptsDirectory = this.system.location.combinePaths(
|
||||
/*
|
||||
Switched from temporary to persistent directory for script storage for improved reliability.
|
||||
|
||||
Temporary directories in some environments, such certain Windows Pro Azure VMs, showed
|
||||
issues where scripts were interrupted due to directory cleanup during script execution.
|
||||
This was observed with system temp directories (e.g., `%LOCALAPPDATA%\Temp`).
|
||||
|
||||
Persistent directories offer better stability during long executions and aid in auditability
|
||||
and troubleshooting.
|
||||
*/
|
||||
this.system.operatingSystem.getUserDataDirectory(),
|
||||
ExecutionSubdirectory,
|
||||
);
|
||||
this.logger.info(`Attempting to create script directory at path: ${scriptsDirectory}`);
|
||||
try {
|
||||
await this.system.fileSystem.createDirectory(scriptsDirectory, true);
|
||||
this.logger.info(`Script directory successfully created at: ${scriptsDirectory}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error creating script directory at ${scriptsDirectory}: ${error.message}`, error);
|
||||
throw error;
|
||||
}
|
||||
return scriptsDirectory;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export interface ScriptDirectoryProvider {
|
||||
provideScriptDirectory(): Promise<string>;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
import { FilenameGenerator } from './FilenameGenerator';
|
||||
|
||||
/**
|
||||
@@ -14,7 +14,7 @@ export class OsTimestampedFilenameGenerator implements FilenameGenerator {
|
||||
private readonly currentOs?: OperatingSystem;
|
||||
|
||||
constructor(
|
||||
environment: RuntimeEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||
environment: RuntimeEnvironment = CurrentEnvironment,
|
||||
) {
|
||||
this.currentOs = environment.os;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { SystemOperations } from '../System/SystemOperations';
|
||||
import { NodeElectronSystemOperations } from '../System/NodeElectronSystemOperations';
|
||||
import { FilenameGenerator } from './Filename/FilenameGenerator';
|
||||
import { ScriptFileCreator } from './ScriptFileCreator';
|
||||
import { OsTimestampedFilenameGenerator } from './Filename/OsTimestampedFilenameGenerator';
|
||||
import { ScriptDirectoryProvider } from './Directory/ScriptDirectoryProvider';
|
||||
import { PersistentDirectoryProvider } from './Directory/PersistentDirectoryProvider';
|
||||
|
||||
export class ScriptFileCreationOrchestrator implements ScriptFileCreator {
|
||||
constructor(
|
||||
private readonly system: SystemOperations = new NodeElectronSystemOperations(),
|
||||
private readonly filenameGenerator: FilenameGenerator = new OsTimestampedFilenameGenerator(),
|
||||
private readonly directoryProvider: ScriptDirectoryProvider = new PersistentDirectoryProvider(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
) { }
|
||||
|
||||
public async createScriptFile(contents: string): Promise<string> {
|
||||
const filePath = await this.provideFilePath();
|
||||
await this.createFile(filePath, contents);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private async provideFilePath(): Promise<string> {
|
||||
const filename = this.filenameGenerator.generateFilename();
|
||||
const directoryPath = await this.directoryProvider.provideScriptDirectory();
|
||||
const filePath = this.system.location.combinePaths(directoryPath, filename);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private async createFile(filePath: string, contents: string): Promise<void> {
|
||||
this.logger.info(`Creating file at ${filePath}, size: ${contents.length} characters`);
|
||||
await this.system.fileSystem.writeToFile(filePath, contents);
|
||||
this.logger.info(`File created successfully at ${filePath}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export interface ScriptFileCreator {
|
||||
createScriptFile(contents: string): Promise<string>;
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { CommandOps, SystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
import { CommandOps, SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { createNodeSystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/NodeSystemOperations';
|
||||
import { NodeElectronSystemOperations } from '@/infrastructure/CodeRunner/System/NodeElectronSystemOperations';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
import { ScriptFileExecutor } from './ScriptFileExecutor';
|
||||
|
||||
export class VisibleTerminalScriptExecutor implements ScriptFileExecutor {
|
||||
constructor(
|
||||
private readonly system: SystemOperations = createNodeSystemOperations(),
|
||||
private readonly system: SystemOperations = new NodeElectronSystemOperations(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
private readonly environment: RuntimeEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||
private readonly environment: RuntimeEnvironment = CurrentEnvironment,
|
||||
) { }
|
||||
|
||||
public async executeScriptFile(filePath: string): Promise<void> {
|
||||
|
||||
29
src/infrastructure/CodeRunner/ScriptFileCodeRunner.ts
Normal file
29
src/infrastructure/CodeRunner/ScriptFileCodeRunner.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { CodeRunner } from '@/application/CodeRunner';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ElectronLogger } from '../Log/ElectronLogger';
|
||||
import { ScriptFileExecutor } from './Execution/ScriptFileExecutor';
|
||||
import { VisibleTerminalScriptExecutor } from './Execution/VisibleTerminalScriptFileExecutor';
|
||||
import { ScriptFileCreator } from './Creation/ScriptFileCreator';
|
||||
import { ScriptFileCreationOrchestrator } from './Creation/ScriptFileCreationOrchestrator';
|
||||
|
||||
export class ScriptFileCodeRunner implements CodeRunner {
|
||||
constructor(
|
||||
private readonly scriptFileExecutor: ScriptFileExecutor = new VisibleTerminalScriptExecutor(),
|
||||
private readonly scriptFileCreator: ScriptFileCreator = new ScriptFileCreationOrchestrator(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
) { }
|
||||
|
||||
public async runCode(
|
||||
code: string,
|
||||
): Promise<void> {
|
||||
this.logger.info('Initiating script running process.');
|
||||
try {
|
||||
const scriptFilePath = await this.scriptFileCreator.createScriptFile(code);
|
||||
await this.scriptFileExecutor.executeScriptFile(scriptFilePath);
|
||||
this.logger.info(`Successfully ran script at ${scriptFilePath}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error running script: ${error.message}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { join } from 'node:path';
|
||||
import { chmod, mkdir, writeFile } from 'node:fs/promises';
|
||||
import { exec } from 'node:child_process';
|
||||
import { app } from 'electron/main';
|
||||
import {
|
||||
CommandOps, FileSystemOps, LocationOps, OperatingSystemOps, SystemOperations,
|
||||
} from './SystemOperations';
|
||||
|
||||
export class NodeElectronSystemOperations implements SystemOperations {
|
||||
public readonly operatingSystem: OperatingSystemOps = {
|
||||
/*
|
||||
This method returns the directory for storing app's configuration files.
|
||||
It appends your app's name to the default appData directory.
|
||||
Conventionally, you should store user data files in this directory.
|
||||
However, avoid writing large files here as some environments might back up this directory
|
||||
to cloud storage, potentially causing issues with file size.
|
||||
|
||||
Based on tests it returns:
|
||||
|
||||
- Windows: `%APPDATA%\privacy.sexy`
|
||||
- Linux: `$HOME/.config/privacy.sexy/runs`
|
||||
- macOS: `$HOME/Library/Application Support/privacy.sexy/runs`
|
||||
|
||||
For more details, refer to the Electron documentation: https://web.archive.org/web/20240104154857/https://www.electronjs.org/docs/latest/api/app#appgetpathname
|
||||
*/
|
||||
getUserDataDirectory: () => {
|
||||
return app.getPath('userData');
|
||||
},
|
||||
};
|
||||
|
||||
public readonly location: LocationOps = {
|
||||
combinePaths: (...pathSegments) => join(...pathSegments),
|
||||
};
|
||||
|
||||
public readonly fileSystem: FileSystemOps = {
|
||||
setFilePermissions: (
|
||||
filePath: string,
|
||||
mode: string | number,
|
||||
) => chmod(filePath, mode),
|
||||
createDirectory: async (
|
||||
directoryPath: string,
|
||||
isRecursive?: boolean,
|
||||
) => {
|
||||
await mkdir(directoryPath, { recursive: isRecursive });
|
||||
// Ignoring the return value from `mkdir`, which is the first directory created
|
||||
// when `recursive` is true, or empty return value.
|
||||
// See https://github.com/nodejs/node/pull/31530
|
||||
},
|
||||
writeToFile: (
|
||||
filePath: string,
|
||||
data: string,
|
||||
) => writeFile(filePath, data),
|
||||
};
|
||||
|
||||
public readonly command: CommandOps = {
|
||||
exec: (command) => new Promise((resolve, reject) => {
|
||||
exec(command, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -6,7 +6,7 @@ export interface SystemOperations {
|
||||
}
|
||||
|
||||
export interface OperatingSystemOps {
|
||||
getTempDirectory(): string;
|
||||
getUserDataDirectory(): string;
|
||||
}
|
||||
|
||||
export interface LocationOps {
|
||||
@@ -1,46 +0,0 @@
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { chmod, mkdir, writeFile } from 'node:fs/promises';
|
||||
import { exec } from 'node:child_process';
|
||||
import { SystemOperations } from './SystemOperations';
|
||||
|
||||
export function createNodeSystemOperations(): SystemOperations {
|
||||
return {
|
||||
operatingSystem: {
|
||||
getTempDirectory: () => tmpdir(),
|
||||
},
|
||||
location: {
|
||||
combinePaths: (...pathSegments) => join(...pathSegments),
|
||||
},
|
||||
fileSystem: {
|
||||
setFilePermissions: (
|
||||
filePath: string,
|
||||
mode: string | number,
|
||||
) => chmod(filePath, mode),
|
||||
createDirectory: async (
|
||||
directoryPath: string,
|
||||
isRecursive?: boolean,
|
||||
) => {
|
||||
await mkdir(directoryPath, { recursive: isRecursive });
|
||||
// Ignoring the return value from `mkdir`, which is the first directory created
|
||||
// when `recursive` is true. The function contract is to not return any value,
|
||||
// and we avoid handling this inconsistent behavior.
|
||||
// See https://github.com/nodejs/node/pull/31530
|
||||
},
|
||||
writeToFile: (
|
||||
filePath: string,
|
||||
data: string,
|
||||
) => writeFile(filePath, data),
|
||||
},
|
||||
command: {
|
||||
exec: (command) => new Promise((resolve, reject) => {
|
||||
exec(command, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import { CodeRunner } from '@/application/CodeRunner';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ElectronLogger } from '../Log/ElectronLogger';
|
||||
import { SystemOperations } from './SystemOperations/SystemOperations';
|
||||
import { createNodeSystemOperations } from './SystemOperations/NodeSystemOperations';
|
||||
import { FilenameGenerator } from './Filename/FilenameGenerator';
|
||||
import { ScriptFileExecutor } from './Execution/ScriptFileExecutor';
|
||||
import { VisibleTerminalScriptExecutor } from './Execution/VisibleTerminalScriptFileExecutor';
|
||||
import { OsTimestampedFilenameGenerator } from './Filename/OsTimestampedFilenameGenerator';
|
||||
|
||||
export class TemporaryFileCodeRunner implements CodeRunner {
|
||||
constructor(
|
||||
private readonly system: SystemOperations = createNodeSystemOperations(),
|
||||
private readonly filenameGenerator: FilenameGenerator = new OsTimestampedFilenameGenerator(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
private readonly scriptFileExecutor: ScriptFileExecutor = new VisibleTerminalScriptExecutor(),
|
||||
) { }
|
||||
|
||||
public async runCode(
|
||||
code: string,
|
||||
tempScriptFolderName: string,
|
||||
): Promise<void> {
|
||||
this.logger.info('Starting running code.');
|
||||
try {
|
||||
const filename = this.filenameGenerator.generateFilename();
|
||||
const filePath = await this.createTemporaryFile(filename, tempScriptFolderName, code);
|
||||
await this.scriptFileExecutor.executeScriptFile(filePath);
|
||||
this.logger.info(`Successfully executed script at ${filePath}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error executing script: ${error.message}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async createTemporaryFile(
|
||||
filename: string,
|
||||
tempScriptFolderName: string,
|
||||
contents: string,
|
||||
): Promise<string> {
|
||||
const directoryPath = this.system.location.combinePaths(
|
||||
this.system.operatingSystem.getTempDirectory(),
|
||||
tempScriptFolderName,
|
||||
);
|
||||
await this.createDirectoryIfNotExists(directoryPath);
|
||||
const filePath = this.system.location.combinePaths(directoryPath, filename);
|
||||
await this.createFile(filePath, contents);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private async createFile(filePath: string, contents: string): Promise<void> {
|
||||
this.logger.info(`Creating file at ${filePath}, size: ${contents.length} characters`);
|
||||
await this.system.fileSystem.writeToFile(filePath, contents);
|
||||
this.logger.info(`File created successfully at ${filePath}`);
|
||||
}
|
||||
|
||||
private async createDirectoryIfNotExists(directoryPath: string): Promise<void> {
|
||||
this.logger.info(`Checking and ensuring directory exists: ${directoryPath}`);
|
||||
await this.system.fileSystem.createDirectory(directoryPath, true);
|
||||
this.logger.info(`Directory confirmed at: ${directoryPath}`);
|
||||
}
|
||||
}
|
||||
@@ -2,22 +2,19 @@ import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { WindowVariables } from '@/infrastructure/WindowVariables/WindowVariables';
|
||||
import { IEnvironmentVariables } from '@/infrastructure/EnvironmentVariables/IEnvironmentVariables';
|
||||
import { EnvironmentVariablesFactory } from '@/infrastructure/EnvironmentVariables/EnvironmentVariablesFactory';
|
||||
import { RuntimeEnvironment } from '../RuntimeEnvironment';
|
||||
import { ConditionBasedOsDetector } from './BrowserOs/ConditionBasedOsDetector';
|
||||
import { BrowserEnvironment, BrowserOsDetector } from './BrowserOs/BrowserOsDetector';
|
||||
import { RuntimeEnvironment } from './RuntimeEnvironment';
|
||||
import { isTouchEnabledDevice } from './TouchSupportDetection';
|
||||
|
||||
export class HostRuntimeEnvironment implements RuntimeEnvironment {
|
||||
public static readonly CurrentEnvironment
|
||||
: RuntimeEnvironment = new HostRuntimeEnvironment(window);
|
||||
|
||||
export class BrowserRuntimeEnvironment implements RuntimeEnvironment {
|
||||
public readonly isDesktop: boolean;
|
||||
|
||||
public readonly os: OperatingSystem | undefined;
|
||||
|
||||
public readonly isNonProduction: boolean;
|
||||
|
||||
protected constructor(
|
||||
public constructor(
|
||||
window: Partial<Window>,
|
||||
environmentVariables: IEnvironmentVariables = EnvironmentVariablesFactory.Current.instance,
|
||||
browserOsDetector: BrowserOsDetector = new ConditionBasedOsDetector(),
|
||||
@@ -1,6 +1,8 @@
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
|
||||
export function convertPlatformToOs(platform: NodeJS.Platform): OperatingSystem | undefined {
|
||||
export function convertPlatformToOs(
|
||||
platform: NodeJS.Platform,
|
||||
): OperatingSystem | undefined {
|
||||
switch (platform) {
|
||||
case 'darwin':
|
||||
return OperatingSystem.macOS;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { RuntimeEnvironment } from '../RuntimeEnvironment';
|
||||
import { convertPlatformToOs } from './NodeOsMapper';
|
||||
|
||||
export class NodeRuntimeEnvironment implements RuntimeEnvironment {
|
||||
public readonly isDesktop: boolean;
|
||||
|
||||
public readonly os: OperatingSystem | undefined;
|
||||
|
||||
public readonly isNonProduction: boolean;
|
||||
|
||||
constructor(
|
||||
nodeProcess: NodeJSProcessAccessor = globalThis.process,
|
||||
convertToOs: PlatformToOperatingSystemConverter = convertPlatformToOs,
|
||||
) {
|
||||
if (!nodeProcess) { throw new Error('missing process'); } // do not trust strictNullChecks for global objects
|
||||
this.isDesktop = true;
|
||||
this.os = convertToOs(nodeProcess.platform);
|
||||
this.isNonProduction = nodeProcess.env.NODE_ENV !== 'production'; // populated by Vite
|
||||
}
|
||||
}
|
||||
|
||||
export interface NodeJSProcessAccessor {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
export type PlatformToOperatingSystemConverter = typeof convertPlatformToOs;
|
||||
@@ -0,0 +1,27 @@
|
||||
import { BrowserRuntimeEnvironment } from './Browser/BrowserRuntimeEnvironment';
|
||||
import { NodeRuntimeEnvironment } from './Node/NodeRuntimeEnvironment';
|
||||
import { RuntimeEnvironment } from './RuntimeEnvironment';
|
||||
|
||||
export const CurrentEnvironment = determineAndCreateRuntimeEnvironment(
|
||||
() => globalThis.window,
|
||||
);
|
||||
|
||||
export function determineAndCreateRuntimeEnvironment(
|
||||
windowAccessor: WindowAccessor,
|
||||
browserEnvironmentFactory: BrowserRuntimeEnvironmentFactory = (
|
||||
window,
|
||||
) => new BrowserRuntimeEnvironment(window),
|
||||
nodeEnvironmentFactory: NodeRuntimeEnvironmentFactory = () => new NodeRuntimeEnvironment(),
|
||||
): RuntimeEnvironment {
|
||||
const window = windowAccessor();
|
||||
if (window) {
|
||||
return browserEnvironmentFactory(window);
|
||||
}
|
||||
return nodeEnvironmentFactory();
|
||||
}
|
||||
|
||||
export type BrowserRuntimeEnvironmentFactory = (window: Window) => RuntimeEnvironment;
|
||||
|
||||
export type NodeRuntimeEnvironmentFactory = () => NodeRuntimeEnvironment;
|
||||
|
||||
export type WindowAccessor = () => Window | undefined;
|
||||
@@ -1,10 +1,10 @@
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { ConsoleLogger } from '@/infrastructure/Log/ConsoleLogger';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { LoggerFactory } from '@/application/Common/Log/LoggerFactory';
|
||||
import { NoopLogger } from '@/infrastructure/Log/NoopLogger';
|
||||
import { WindowInjectedLogger } from '@/infrastructure/Log/WindowInjectedLogger';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
|
||||
export class ClientLoggerFactory implements LoggerFactory {
|
||||
public static readonly Current: LoggerFactory = new ClientLoggerFactory();
|
||||
@@ -12,7 +12,7 @@ export class ClientLoggerFactory implements LoggerFactory {
|
||||
public readonly logger: Logger;
|
||||
|
||||
protected constructor(
|
||||
environment: RuntimeEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||
environment: RuntimeEnvironment = CurrentEnvironment,
|
||||
) {
|
||||
if (environment.isDesktop) {
|
||||
this.logger = new WindowInjectedLogger();
|
||||
|
||||
@@ -13,7 +13,7 @@ import { PropertyKeys } from '@/TypeHelpers';
|
||||
import { useUserSelectionState } from '@/presentation/components/Shared/Hooks/UseUserSelectionState';
|
||||
import { useLogger } from '@/presentation/components/Shared/Hooks/UseLogger';
|
||||
import { useCodeRunner } from '@/presentation/components/Shared/Hooks/UseCodeRunner';
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
|
||||
export function provideDependencies(
|
||||
context: IApplicationContext,
|
||||
@@ -33,7 +33,7 @@ export function provideDependencies(
|
||||
),
|
||||
useRuntimeEnvironment: (di) => di.provide(
|
||||
InjectionKeys.useRuntimeEnvironment,
|
||||
HostRuntimeEnvironment.CurrentEnvironment,
|
||||
CurrentEnvironment,
|
||||
),
|
||||
useAutoUnsubscribedEvents: (di) => di.provide(
|
||||
InjectionKeys.useAutoUnsubscribedEvents,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
import { Bootstrapper } from '../Bootstrapper';
|
||||
|
||||
export class MobileSafariActivePseudoClassEnabler implements Bootstrapper {
|
||||
constructor(
|
||||
private readonly currentEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||
private readonly currentEnvironment = CurrentEnvironment,
|
||||
private readonly browser: BrowserAccessor = GlobalBrowserAccessor,
|
||||
) {
|
||||
|
||||
|
||||
@@ -26,10 +26,7 @@ export default defineComponent({
|
||||
|
||||
async function executeCode() {
|
||||
if (!codeRunner) { throw new Error('missing code runner'); }
|
||||
await codeRunner.runCode(
|
||||
currentContext.state.code.current,
|
||||
currentContext.app.info.name,
|
||||
);
|
||||
await codeRunner.runCode(currentContext.state.code.current);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
24
src/presentation/electron/main/IpcRegistration.ts
Normal file
24
src/presentation/electron/main/IpcRegistration.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { ScriptFileCodeRunner } from '@/infrastructure/CodeRunner/ScriptFileCodeRunner';
|
||||
import { CodeRunner } from '@/application/CodeRunner';
|
||||
import { registerIpcChannel } from '../shared/IpcBridging/IpcProxy';
|
||||
import { IpcChannelDefinitions } from '../shared/IpcBridging/IpcChannelDefinitions';
|
||||
|
||||
export function registerAllIpcChannels(
|
||||
createCodeRunner: CodeRunnerFactory = () => new ScriptFileCodeRunner(),
|
||||
registrar: IpcRegistrar = registerIpcChannel,
|
||||
) {
|
||||
const registrars: Record<keyof typeof IpcChannelDefinitions, () => void> = {
|
||||
CodeRunner: () => registrar(IpcChannelDefinitions.CodeRunner, createCodeRunner()),
|
||||
};
|
||||
Object.entries(registrars).forEach(([name, register]) => {
|
||||
try {
|
||||
register();
|
||||
} catch (err) {
|
||||
throw new AggregateError(`main: Failed to register IPC channel "${name}"`, err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export type CodeRunnerFactory = () => CodeRunner;
|
||||
|
||||
export type IpcRegistrar = typeof registerIpcChannel;
|
||||
@@ -1,4 +1,4 @@
|
||||
import { app, dialog } from 'electron';
|
||||
import { app, dialog } from 'electron/main';
|
||||
import { autoUpdater, UpdateInfo } from 'electron-updater';
|
||||
import { ProgressInfo } from 'electron-builder';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { dialog } from 'electron';
|
||||
import { dialog } from 'electron/main';
|
||||
|
||||
export enum ManualUpdateChoice {
|
||||
NoAction = 0,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { existsSync, createWriteStream, type WriteStream } from 'node:fs';
|
||||
import { unlink, mkdir } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { app } from 'electron/main';
|
||||
import { UpdateInfo } from 'electron-updater';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { UpdateProgressBar } from '../UpdateProgressBar';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { app, shell } from 'electron';
|
||||
import { app } from 'electron/main';
|
||||
import { shell } from 'electron/common';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { retryFileSystemAccess } from './RetryFileSystemAccess';
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import ProgressBar from 'electron-progressbar';
|
||||
import { ProgressInfo } from 'electron-builder';
|
||||
import { app, BrowserWindow } from 'electron';
|
||||
import { app, BrowserWindow } from 'electron/main';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
|
||||
export class UpdateProgressBar {
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
// Initializes Electron's main process, always runs in the background, and manages the main window.
|
||||
|
||||
import {
|
||||
app, protocol, BrowserWindow, shell, screen,
|
||||
} from 'electron';
|
||||
app, protocol, BrowserWindow, screen,
|
||||
} from 'electron/main';
|
||||
import { shell } from 'electron/common';
|
||||
import log from 'electron-log/main';
|
||||
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer';
|
||||
import { validateRuntimeSanity } from '@/infrastructure/RuntimeSanity/SanityChecks';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { name } from '@/../package.json' assert { type: 'json' };
|
||||
import { setupAutoUpdater } from './Update/UpdateInitializer';
|
||||
import {
|
||||
APP_ICON_PATH, PRELOADER_SCRIPT_PATH, RENDERER_HTML_PATH, RENDERER_URL,
|
||||
} from './ElectronConfig';
|
||||
import { registerAllIpcChannels } from './IpcRegistration';
|
||||
|
||||
const isDevelopment = !app.isPackaged;
|
||||
|
||||
@@ -57,36 +60,11 @@ function createWindow() {
|
||||
});
|
||||
}
|
||||
|
||||
let macOsQuit = false;
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform === 'darwin'
|
||||
&& !macOsQuit) {
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
return;
|
||||
}
|
||||
app.quit();
|
||||
});
|
||||
configureAppQuitBehavior();
|
||||
registerAllIpcChannels();
|
||||
setAppName();
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
// On macOS we application quit is stopped if user does not Cmd + Q
|
||||
// But we still want to be able to use app.quit() and quit the application
|
||||
// on menu bar, after updates etc.
|
||||
app.on('before-quit', () => {
|
||||
macOsQuit = true;
|
||||
});
|
||||
}
|
||||
|
||||
app.on('activate', () => {
|
||||
// On macOS it's common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (win === null) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('ready', async () => {
|
||||
app.whenReady().then(async () => {
|
||||
if (isDevelopment) {
|
||||
try {
|
||||
await installExtension(VUEJS_DEVTOOLS);
|
||||
@@ -95,6 +73,13 @@ app.on('ready', async () => {
|
||||
}
|
||||
}
|
||||
createWindow();
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
// On macOS it's common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Exit cleanly on request from parent process in development mode.
|
||||
@@ -156,3 +141,39 @@ function setupLogger(): void {
|
||||
log.transports.file.level = 'silly';
|
||||
log.eventLogger.startLogging();
|
||||
}
|
||||
|
||||
function configureAppQuitBehavior() {
|
||||
let macOsQuit = false;
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform === 'darwin'
|
||||
&& !macOsQuit) {
|
||||
/*
|
||||
On macOS it is common for applications and their menu bar
|
||||
to stay active until the user quits explicitly with Cmd + Q
|
||||
*/
|
||||
return;
|
||||
}
|
||||
app.quit();
|
||||
});
|
||||
if (process.platform === 'darwin') {
|
||||
/*
|
||||
On macOS we application quit is stopped if user does not Cmd + Q
|
||||
But we still want to be able to use app.quit() and quit the application
|
||||
on menu bar, after updates etc.
|
||||
*/
|
||||
app.on('before-quit', () => {
|
||||
macOsQuit = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function setAppName() {
|
||||
/*
|
||||
Set the app name in development mode to ensure correct userData path.
|
||||
Without this, `app.getPath('userData')` defaults to 'Electron'.
|
||||
*/
|
||||
if (isDevelopment) {
|
||||
app.setName(name); // Works only for Windows, unsolved for macOS.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { contextBridge } from 'electron';
|
||||
import { contextBridge } from 'electron/renderer';
|
||||
import { bindObjectMethods } from './MethodContextBinder';
|
||||
import { provideWindowVariables } from './RendererApiProvider';
|
||||
|
||||
|
||||
14
src/presentation/electron/preload/ContextBridging/README.md
Normal file
14
src/presentation/electron/preload/ContextBridging/README.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Context Bridging Module
|
||||
|
||||
This module establishes secure, maintainable, and efficient inter-process communication between the preloader
|
||||
and renderer processes.
|
||||
|
||||
## Benefits
|
||||
|
||||
- **Security**: Exposes intended parts of an object to the renderer process, safeguarding the application's
|
||||
integrity and security.
|
||||
- **Type Safety and Maintainability**: Offers type-checked contracts for robust and easy-to-maintain code.
|
||||
- **Simplicity**: Streamlines the process of exposing APIs to the renderer process, minimizing the complexity
|
||||
of context bindings.
|
||||
- **Scalability**: Enhances the scalability of API exposure and simplifies managing more complex API structures,
|
||||
overcoming the limitations of ad-hoc approaches.
|
||||
@@ -1,27 +1,27 @@
|
||||
import { createElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { WindowVariables } from '@/infrastructure/WindowVariables/WindowVariables';
|
||||
import { TemporaryFileCodeRunner } from '@/infrastructure/CodeRunner/TemporaryFileCodeRunner';
|
||||
import { CodeRunner } from '@/application/CodeRunner';
|
||||
import { convertPlatformToOs } from './NodeOsMapper';
|
||||
import { convertPlatformToOs } from '@/infrastructure/RuntimeEnvironment/Node/NodeOsMapper';
|
||||
import { createIpcConsumerProxy } from '../../shared/IpcBridging/IpcProxy';
|
||||
import { IpcChannelDefinitions } from '../../shared/IpcBridging/IpcChannelDefinitions';
|
||||
import { createSecureFacade } from './SecureFacadeCreator';
|
||||
|
||||
export function provideWindowVariables(
|
||||
createCodeRunner: CodeRunnerFactory = () => new TemporaryFileCodeRunner(),
|
||||
createLogger: LoggerFactory = () => createElectronLogger(),
|
||||
convertToOs = convertPlatformToOs,
|
||||
createApiFacade: ApiFacadeFactory = createSecureFacade,
|
||||
ipcConsumerCreator: IpcConsumerProxyCreator = createIpcConsumerProxy,
|
||||
): WindowVariables {
|
||||
return {
|
||||
isDesktop: true,
|
||||
log: createApiFacade(createLogger(), ['info', 'debug', 'warn', 'error']),
|
||||
os: convertToOs(process.platform),
|
||||
codeRunner: createApiFacade(createCodeRunner(), ['runCode']),
|
||||
codeRunner: ipcConsumerCreator(IpcChannelDefinitions.CodeRunner),
|
||||
};
|
||||
}
|
||||
|
||||
export type LoggerFactory = () => Logger;
|
||||
|
||||
export type CodeRunnerFactory = () => CodeRunner;
|
||||
|
||||
export type ApiFacadeFactory = typeof createSecureFacade;
|
||||
|
||||
export type IpcConsumerProxyCreator = typeof createIpcConsumerProxy;
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { FunctionKeys } from '@/TypeHelpers';
|
||||
|
||||
export interface IpcChannel<T> {
|
||||
readonly namespace: string;
|
||||
readonly accessibleMembers: readonly FunctionKeys<T>[]; // Property keys are not yet supported
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { FunctionKeys } from '@/TypeHelpers';
|
||||
import { CodeRunner } from '@/application/CodeRunner';
|
||||
import { IpcChannel } from './IpcChannel';
|
||||
|
||||
export const IpcChannelDefinitions = {
|
||||
CodeRunner: defineElectronIpcChannel<CodeRunner>('code-run', ['runCode']),
|
||||
} as const;
|
||||
|
||||
function defineElectronIpcChannel<T>(
|
||||
name: string,
|
||||
functionNames: readonly FunctionKeys<T>[],
|
||||
): IpcChannel<T> {
|
||||
return {
|
||||
namespace: name,
|
||||
accessibleMembers: functionNames,
|
||||
};
|
||||
}
|
||||
48
src/presentation/electron/shared/IpcBridging/IpcProxy.ts
Normal file
48
src/presentation/electron/shared/IpcBridging/IpcProxy.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { ipcMain } from 'electron/main';
|
||||
import { ipcRenderer } from 'electron/renderer';
|
||||
import { isFunction } from '@/TypeHelpers';
|
||||
import { IpcChannel } from './IpcChannel';
|
||||
|
||||
export function createIpcConsumerProxy<T>(
|
||||
channel: IpcChannel<T>,
|
||||
electronIpcRenderer: Electron.IpcRenderer = ipcRenderer,
|
||||
): AsyncMethods<T> {
|
||||
const facade: Partial<T> = {};
|
||||
channel.accessibleMembers.forEach((member) => {
|
||||
const functionKey = member as string;
|
||||
const ipcChannel = getIpcChannelIdentifier(channel.namespace, functionKey);
|
||||
facade[functionKey] = ((...args: unknown[]) => {
|
||||
return electronIpcRenderer.invoke(ipcChannel, ...args);
|
||||
}) as AsyncMethods<T>[keyof T];
|
||||
});
|
||||
return facade as AsyncMethods<T>;
|
||||
}
|
||||
|
||||
export function registerIpcChannel<T>(
|
||||
channel: IpcChannel<T>,
|
||||
originalObject: T,
|
||||
electronIpcMain: Electron.IpcMain = ipcMain,
|
||||
) {
|
||||
channel.accessibleMembers.forEach((functionKey) => {
|
||||
const originalFunction = originalObject[functionKey];
|
||||
if (!isFunction(originalFunction)) {
|
||||
throw new Error('Non-function members are not yet supported');
|
||||
}
|
||||
const ipcChannel = getIpcChannelIdentifier(channel.namespace, functionKey as string);
|
||||
electronIpcMain.handle(ipcChannel, (_event, ...args: unknown[]) => {
|
||||
return originalFunction.apply(originalObject, args);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function getIpcChannelIdentifier(namespace: string, key: string) {
|
||||
return `proxy:${namespace}:${key}`;
|
||||
}
|
||||
|
||||
type AsyncMethods<T> = {
|
||||
[P in keyof T]: T[P] extends (...args: infer Args) => infer R
|
||||
? R extends Promise<unknown>
|
||||
? (...args: Args) => R
|
||||
: (...args: Args) => Promise<R>
|
||||
: never;
|
||||
};
|
||||
17
src/presentation/electron/shared/IpcBridging/README.md
Normal file
17
src/presentation/electron/shared/IpcBridging/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# IPC bridging
|
||||
|
||||
This module introduces structured and type-safe inter-process communication (IPC) to Electron applications,
|
||||
enhancing the development and maintenance of complex features.
|
||||
|
||||
## Benefits
|
||||
|
||||
- **Type safety**: Ensures reliable data exchange between processes and prevents runtime errors through enforced
|
||||
type checks in IPC communication.
|
||||
- **Maintainability**: Facilitates easy tracking and management of inter-process contracts using defined and clear
|
||||
interfaces.
|
||||
- **Security**: Implements the least-privilege principle by defining which members are accessible in proxy objects,
|
||||
enhancing the security of IPC interactions.
|
||||
- **Simplicity**: Simplifies IPC calls by abstracting the underlying complexity, providing a more straightforward
|
||||
interface for developers.
|
||||
- **Scalability**: Structured IPC management supports effective scaling and reduces the challenges of ad-hoc
|
||||
IPC implementations.
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { ConditionBasedOsDetector } from '@/infrastructure/RuntimeEnvironment/BrowserOs/ConditionBasedOsDetector';
|
||||
import { BrowserEnvironment } from '@/infrastructure/RuntimeEnvironment/BrowserOs/BrowserOsDetector';
|
||||
import { ConditionBasedOsDetector } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserOs/ConditionBasedOsDetector';
|
||||
import { BrowserEnvironment } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserOs/BrowserOsDetector';
|
||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||
import { BrowserOsTestCases } from './BrowserOsTestCases';
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@ import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { MobileSafariActivePseudoClassEnabler } from '@/presentation/bootstrapping/Modules/MobileSafariActivePseudoClassEnabler';
|
||||
import { EventName, createWindowEventSpies } from '@tests/shared/Spies/WindowEventSpies';
|
||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||
import { isTouchEnabledDevice } from '@/infrastructure/RuntimeEnvironment/TouchSupportDetection';
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { isTouchEnabledDevice } from '@/infrastructure/RuntimeEnvironment/Browser/TouchSupportDetection';
|
||||
import { BrowserRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserRuntimeEnvironment';
|
||||
import { MobileSafariDetectionTestCases } from './MobileSafariDetectionTestCases';
|
||||
|
||||
describe('MobileSafariActivePseudoClassEnabler', () => {
|
||||
@@ -17,7 +17,7 @@ describe('MobileSafariActivePseudoClassEnabler', () => {
|
||||
const expectedEvent: EventName = 'touchstart';
|
||||
patchUserAgent(userAgent, afterEach);
|
||||
const { isAddEventCalled, currentListeners } = createWindowEventSpies(afterEach);
|
||||
const patchedEnvironment = new ConstructibleRuntimeEnvironment(supportsTouch);
|
||||
const patchedEnvironment = new TouchSupportControlledBrowserEnvironment(supportsTouch);
|
||||
const sut = new MobileSafariActivePseudoClassEnabler(patchedEnvironment);
|
||||
// act
|
||||
sut.bootstrap();
|
||||
@@ -59,7 +59,7 @@ function getTouchDetectorMock(
|
||||
return () => isTouchEnabled;
|
||||
}
|
||||
|
||||
class ConstructibleRuntimeEnvironment extends HostRuntimeEnvironment {
|
||||
class TouchSupportControlledBrowserEnvironment extends BrowserRuntimeEnvironment {
|
||||
public constructor(isTouchEnabled: boolean) {
|
||||
super(window, undefined, undefined, getTouchDetectorMock(isTouchEnabled));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ExecutionSubdirectory, PersistentDirectoryProvider } from '@/infrastructure/CodeRunner/Creation/Directory/PersistentDirectoryProvider';
|
||||
import { SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { LocationOpsStub } from '@tests/unit/shared/Stubs/LocationOpsStub';
|
||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||
import { OperatingSystemOpsStub } from '@tests/unit/shared/Stubs/OperatingSystemOpsStub';
|
||||
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
|
||||
import { FileSystemOpsStub } from '@tests/unit/shared/Stubs/FileSystemOpsStub';
|
||||
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
|
||||
import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
|
||||
|
||||
describe('PersistentDirectoryProvider', () => {
|
||||
describe('createDirectory', () => {
|
||||
describe('path generation', () => {
|
||||
it('uses user directory as base', async () => {
|
||||
// arrange
|
||||
const expectedBaseDirectory = 'base-directory';
|
||||
const pathSegmentSeparator = '/STUB-SEGMENT-SEPARATOR/';
|
||||
const locationOps = new LocationOpsStub()
|
||||
.withDefaultSeparator(pathSegmentSeparator);
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withSystem(new SystemOperationsStub()
|
||||
.withOperatingSystem(new OperatingSystemOpsStub()
|
||||
.withUserDirectoryResult(expectedBaseDirectory))
|
||||
.withLocation(locationOps));
|
||||
|
||||
// act
|
||||
const actualDirectoryResult = await context.createDirectory();
|
||||
|
||||
// assert
|
||||
const actualBaseDirectory = actualDirectoryResult.split(pathSegmentSeparator)[0];
|
||||
expect(actualBaseDirectory).to.equal(expectedBaseDirectory);
|
||||
const calls = locationOps.callHistory.filter((call) => call.methodName === 'combinePaths');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [combinedBaseDirectory] = calls[0].args;
|
||||
expect(combinedBaseDirectory).to.equal(expectedBaseDirectory);
|
||||
});
|
||||
it('appends execution subdirectory', async () => {
|
||||
// arrange
|
||||
const expectedSubdirectory = ExecutionSubdirectory;
|
||||
const pathSegmentSeparator = '/STUB-SEGMENT-SEPARATOR/';
|
||||
const locationOps = new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator);
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withSystem(new SystemOperationsStub()
|
||||
.withLocation(locationOps));
|
||||
|
||||
// act
|
||||
const actualDirectoryResult = await context.createDirectory();
|
||||
|
||||
// assert
|
||||
const actualSubdirectory = actualDirectoryResult
|
||||
.split(pathSegmentSeparator)
|
||||
.pop();
|
||||
expect(actualSubdirectory).to.equal(expectedSubdirectory);
|
||||
const calls = locationOps.callHistory.filter((call) => call.methodName === 'combinePaths');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [,combinedSubdirectory] = calls[0].args;
|
||||
expect(combinedSubdirectory).to.equal(expectedSubdirectory);
|
||||
});
|
||||
it('correctly forms the full path', async () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/';
|
||||
const baseDirectory = 'base-directory';
|
||||
const expectedDirectory = [baseDirectory, ExecutionSubdirectory].join(pathSegmentSeparator);
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withSystem(new SystemOperationsStub()
|
||||
.withLocation(new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator))
|
||||
.withOperatingSystem(
|
||||
new OperatingSystemOpsStub().withUserDirectoryResult(baseDirectory),
|
||||
));
|
||||
|
||||
// act
|
||||
const actualDirectory = await context.createDirectory();
|
||||
|
||||
// assert
|
||||
expect(actualDirectory).to.equal(expectedDirectory);
|
||||
});
|
||||
});
|
||||
describe('directory creation', () => {
|
||||
it('creates directory recursively', async () => {
|
||||
// arrange
|
||||
const expectedIsRecursive = true;
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withSystem(new SystemOperationsStub().withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
const expectedDir = await context.createDirectory();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'createDirectory');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualPath, actualIsRecursive] = calls[0].args;
|
||||
expect(actualPath).to.equal(expectedDir);
|
||||
expect(actualIsRecursive).to.equal(expectedIsRecursive);
|
||||
});
|
||||
it('logs error when creation fails', async () => {
|
||||
// arrange
|
||||
const logger = new LoggerStub();
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
filesystem.createDirectory = () => { throw new Error(); };
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withLogger(logger)
|
||||
.withSystem(new SystemOperationsStub().withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
try {
|
||||
await context.createDirectory();
|
||||
} catch {
|
||||
// swallow
|
||||
}
|
||||
|
||||
// assert
|
||||
const errorCall = logger.callHistory.find((c) => c.methodName === 'error');
|
||||
expectExists(errorCall);
|
||||
});
|
||||
it('throws error on creation failure', async () => {
|
||||
// arrange
|
||||
const expectedError = 'expected file system error';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
filesystem.createDirectory = () => { throw new Error(expectedError); };
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withSystem(new SystemOperationsStub().withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
const act = () => context.createDirectory();
|
||||
|
||||
// assert
|
||||
await expectThrowsAsync(act, expectedError);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class PersistentDirectoryProviderTestSetup {
|
||||
private system: SystemOperations = new SystemOperationsStub();
|
||||
|
||||
private logger: Logger = new LoggerStub();
|
||||
|
||||
public withSystem(system: SystemOperations): this {
|
||||
this.system = system;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withLogger(logger: Logger): this {
|
||||
this.logger = logger;
|
||||
return this;
|
||||
}
|
||||
|
||||
public createDirectory(): ReturnType<PersistentDirectoryProvider['provideScriptDirectory']> {
|
||||
const provider = new PersistentDirectoryProvider(this.system, this.logger);
|
||||
return provider.provideScriptDirectory();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { AllSupportedOperatingSystems, SupportedOperatingSystem } from '@tests/shared/TestCases/SupportedOperatingSystems';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { OsTimestampedFilenameGenerator } from '@/infrastructure/CodeRunner/Filename/OsTimestampedFilenameGenerator';
|
||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||
import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub';
|
||||
import { OsTimestampedFilenameGenerator } from '@/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator';
|
||||
|
||||
describe('OsTimestampedFilenameGenerator', () => {
|
||||
describe('generateFilename', () => {
|
||||
@@ -0,0 +1,165 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ScriptFileCreationOrchestrator } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator';
|
||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||
import { FileSystemOpsStub } from '@tests/unit/shared/Stubs/FileSystemOpsStub';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||
import { ScriptDirectoryProvider } from '@/infrastructure/CodeRunner/Creation/Directory/ScriptDirectoryProvider';
|
||||
import { ScriptDirectoryProviderStub } from '@tests/unit/shared/Stubs/ScriptDirectoryProviderStub';
|
||||
import { FilenameGenerator } from '@/infrastructure/CodeRunner/Creation/Filename/FilenameGenerator';
|
||||
import { FilenameGeneratorStub } from '@tests/unit/shared/Stubs/FilenameGeneratorStub';
|
||||
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
|
||||
import { SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { LocationOpsStub } from '@tests/unit/shared/Stubs/LocationOpsStub';
|
||||
|
||||
describe('ScriptFileCreationOrchestrator', () => {
|
||||
describe('createScriptFile', () => {
|
||||
describe('path generation', () => {
|
||||
it('generates correct directory path', async () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||
const expectedScriptDirectory = '/expected-script-directory';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new ScriptFileCreationOrchestratorTestSetup()
|
||||
.withSystemOperations(new SystemOperationsStub()
|
||||
.withLocation(
|
||||
new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator),
|
||||
)
|
||||
.withFileSystem(filesystem))
|
||||
.withDirectoryProvider(
|
||||
new ScriptDirectoryProviderStub().withDirectoryPath(expectedScriptDirectory),
|
||||
);
|
||||
|
||||
// act
|
||||
const actualFilePath = await context.createScriptFile();
|
||||
|
||||
// assert
|
||||
const actualDirectory = actualFilePath
|
||||
.split(pathSegmentSeparator)
|
||||
.slice(0, -1)
|
||||
.join(pathSegmentSeparator);
|
||||
expect(actualDirectory).to.equal(expectedScriptDirectory, formatAssertionMessage([
|
||||
`Actual file path: ${actualFilePath}`,
|
||||
]));
|
||||
});
|
||||
it('generates correct file name', async () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const expectedFilename = 'expected-script-file-name';
|
||||
const context = new ScriptFileCreationOrchestratorTestSetup()
|
||||
.withFilenameGenerator(new FilenameGeneratorStub().withFilename(expectedFilename))
|
||||
.withSystemOperations(new SystemOperationsStub()
|
||||
.withFileSystem(filesystem)
|
||||
.withLocation(new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator)));
|
||||
|
||||
// act
|
||||
const actualFilePath = await context.createScriptFile();
|
||||
|
||||
// assert
|
||||
const actualFileName = actualFilePath
|
||||
.split(pathSegmentSeparator)
|
||||
.pop();
|
||||
expect(actualFileName).to.equal(expectedFilename);
|
||||
});
|
||||
it('generates complete file path', async () => {
|
||||
// arrange
|
||||
const expectedPath = 'expected-script-path';
|
||||
const fileName = 'file-name';
|
||||
const directoryPath = 'directory-path';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new ScriptFileCreationOrchestratorTestSetup()
|
||||
.withFilenameGenerator(new FilenameGeneratorStub().withFilename(fileName))
|
||||
.withDirectoryProvider(new ScriptDirectoryProviderStub().withDirectoryPath(directoryPath))
|
||||
.withSystemOperations(new SystemOperationsStub()
|
||||
.withFileSystem(filesystem)
|
||||
.withLocation(
|
||||
new LocationOpsStub().withJoinResult(expectedPath, directoryPath, fileName),
|
||||
));
|
||||
|
||||
// act
|
||||
const actualFilePath = await context.createScriptFile();
|
||||
|
||||
// assert
|
||||
expect(actualFilePath).to.equal(expectedPath);
|
||||
});
|
||||
});
|
||||
describe('writing file to system', () => {
|
||||
it('writes file to the generated path', async () => {
|
||||
// arrange
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new ScriptFileCreationOrchestratorTestSetup()
|
||||
.withSystemOperations(new SystemOperationsStub()
|
||||
.withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
const expectedPath = await context.createScriptFile();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualFilePath] = calls[0].args;
|
||||
expect(actualFilePath).to.equal(expectedPath);
|
||||
});
|
||||
it('writes provided script content to file', async () => {
|
||||
// arrange
|
||||
const expectedCode = 'expected-code';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new ScriptFileCreationOrchestratorTestSetup()
|
||||
.withSystemOperations(new SystemOperationsStub().withFileSystem(filesystem))
|
||||
.withFileContents(expectedCode);
|
||||
|
||||
// act
|
||||
await context.createScriptFile();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [, actualData] = calls[0].args;
|
||||
expect(actualData).to.equal(expectedCode);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class ScriptFileCreationOrchestratorTestSetup {
|
||||
private system: SystemOperations = new SystemOperationsStub();
|
||||
|
||||
private filenameGenerator: FilenameGenerator = new FilenameGeneratorStub();
|
||||
|
||||
private directoryProvider: ScriptDirectoryProvider = new ScriptDirectoryProviderStub();
|
||||
|
||||
private logger: Logger = new LoggerStub();
|
||||
|
||||
private fileContents = `[${ScriptFileCreationOrchestratorTestSetup.name}] script file contents`;
|
||||
|
||||
public withFileContents(fileContents: string): this {
|
||||
this.fileContents = fileContents;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withDirectoryProvider(directoryProvider: ScriptDirectoryProvider): this {
|
||||
this.directoryProvider = directoryProvider;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withFilenameGenerator(generator: FilenameGenerator): this {
|
||||
this.filenameGenerator = generator;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withSystemOperations(system: SystemOperations): this {
|
||||
this.system = system;
|
||||
return this;
|
||||
}
|
||||
|
||||
public createScriptFile(): ReturnType<ScriptFileCreationOrchestrator['createScriptFile']> {
|
||||
const creator = new ScriptFileCreationOrchestrator(
|
||||
this.system,
|
||||
this.filenameGenerator,
|
||||
this.directoryProvider,
|
||||
this.logger,
|
||||
);
|
||||
return creator.createScriptFile(this.fileContents);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironm
|
||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
|
||||
import { CommandOpsStub } from '@tests/unit/shared/Stubs/CommandOpsStub';
|
||||
import { SystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
import { SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { FileSystemOpsStub } from '@tests/unit/shared/Stubs/FileSystemOpsStub';
|
||||
|
||||
describe('VisibleTerminalScriptFileExecutor', () => {
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ScriptFileCodeRunner } from '@/infrastructure/CodeRunner/ScriptFileCodeRunner';
|
||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ScriptFileExecutor } from '@/infrastructure/CodeRunner/Execution/ScriptFileExecutor';
|
||||
import { ScriptFileExecutorStub } from '@tests/unit/shared/Stubs/ScriptFileExecutorStub';
|
||||
import { ScriptFileCreator } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreator';
|
||||
import { ScriptFileCreatorStub } from '@tests/unit/shared/Stubs/ScriptFileCreatorStub';
|
||||
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
|
||||
import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
|
||||
|
||||
describe('ScriptFileCodeRunner', () => {
|
||||
describe('runCode', () => {
|
||||
it('executes the script file as expected', async () => {
|
||||
// arrange
|
||||
const expectedFilePath = 'expected script path';
|
||||
const fileExecutor = new ScriptFileExecutorStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withFileCreator(new ScriptFileCreatorStub().withCreatedFilePath(expectedFilePath))
|
||||
.withFileExecutor(fileExecutor);
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
const executeCalls = fileExecutor.callHistory.filter((call) => call.methodName === 'executeScriptFile');
|
||||
expect(executeCalls.length).to.equal(1);
|
||||
const [actualPath] = executeCalls[0].args;
|
||||
expect(actualPath).to.equal(expectedFilePath);
|
||||
});
|
||||
it('creates script file with provided code', async () => {
|
||||
// arrange
|
||||
const expectedCode = 'expected code';
|
||||
const fileCreator = new ScriptFileCreatorStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withFileCreator(fileCreator)
|
||||
.withCode(expectedCode);
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
const createCalls = fileCreator.callHistory.filter((call) => call.methodName === 'createScriptFile');
|
||||
expect(createCalls.length).to.equal(1);
|
||||
const [actualCode] = createCalls[0].args;
|
||||
expect(actualCode).to.equal(expectedCode);
|
||||
});
|
||||
describe('error handling', () => {
|
||||
const testScenarios: ReadonlyArray<{
|
||||
readonly description: string;
|
||||
readonly injectedException: Error;
|
||||
readonly faultyContext: CodeRunnerTestSetup;
|
||||
}> = [
|
||||
(() => {
|
||||
const error = new Error('script file execution failed');
|
||||
const executor = new ScriptFileExecutorStub();
|
||||
executor.executeScriptFile = () => {
|
||||
throw error;
|
||||
};
|
||||
return {
|
||||
description: 'fails to execute script file',
|
||||
injectedException: error,
|
||||
faultyContext: new CodeRunnerTestSetup().withFileExecutor(executor),
|
||||
};
|
||||
})(),
|
||||
(() => {
|
||||
const error = new Error('script file creation failed');
|
||||
const creator = new ScriptFileCreatorStub();
|
||||
creator.createScriptFile = () => {
|
||||
throw error;
|
||||
};
|
||||
return {
|
||||
description: 'fails to create script file',
|
||||
injectedException: error,
|
||||
faultyContext: new CodeRunnerTestSetup().withFileCreator(creator),
|
||||
};
|
||||
})(),
|
||||
];
|
||||
describe('logs errors correctly', () => {
|
||||
testScenarios.forEach(({ description, faultyContext }) => {
|
||||
it(`logs error when ${description}`, async () => {
|
||||
// arrange
|
||||
const logger = new LoggerStub();
|
||||
faultyContext.withLogger(logger);
|
||||
// act
|
||||
try {
|
||||
await faultyContext.runCode();
|
||||
} catch {
|
||||
// Swallow
|
||||
}
|
||||
// assert
|
||||
const errorCall = logger.callHistory.find((c) => c.methodName === 'error');
|
||||
expectExists(errorCall);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('correctly rethrows errors', () => {
|
||||
testScenarios.forEach(({ description, injectedException, faultyContext }) => {
|
||||
it(`rethrows error when ${description}`, async () => {
|
||||
// act
|
||||
const act = () => faultyContext.runCode();
|
||||
// assert
|
||||
await expectThrowsAsync(act, injectedException.message);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class CodeRunnerTestSetup {
|
||||
private code = `[${CodeRunnerTestSetup.name}]code`;
|
||||
|
||||
private fileCreator: ScriptFileCreator = new ScriptFileCreatorStub();
|
||||
|
||||
private fileExecutor: ScriptFileExecutor = new ScriptFileExecutorStub();
|
||||
|
||||
private logger: Logger = new LoggerStub();
|
||||
|
||||
public async runCode(): Promise<void> {
|
||||
const runner = new ScriptFileCodeRunner(
|
||||
this.fileExecutor,
|
||||
this.fileCreator,
|
||||
this.logger,
|
||||
);
|
||||
await runner.runCode(this.code);
|
||||
}
|
||||
|
||||
public withFileExecutor(fileExecutor: ScriptFileExecutor): this {
|
||||
this.fileExecutor = fileExecutor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withCode(code: string): this {
|
||||
this.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withLogger(logger: Logger): this {
|
||||
this.logger = logger;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withFileCreator(fileCreator: ScriptFileCreator): this {
|
||||
this.fileCreator = fileCreator;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,257 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { FileSystemOps, SystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
import { TemporaryFileCodeRunner } from '@/infrastructure/CodeRunner/TemporaryFileCodeRunner';
|
||||
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
|
||||
import { OperatingSystemOpsStub } from '@tests/unit/shared/Stubs/OperatingSystemOpsStub';
|
||||
import { LocationOpsStub } from '@tests/unit/shared/Stubs/LocationOpsStub';
|
||||
import { FunctionKeys } from '@/TypeHelpers';
|
||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { FilenameGenerator } from '@/infrastructure/CodeRunner/Filename/FilenameGenerator';
|
||||
import { FilenameGeneratorStub } from '@tests/unit/shared/Stubs/FilenameGeneratorStub';
|
||||
import { ScriptFileExecutor } from '@/infrastructure/CodeRunner/Execution/ScriptFileExecutor';
|
||||
import { ScriptFileExecutorStub } from '@tests/unit/shared/Stubs/ScriptFileExecutorStub';
|
||||
import { FileSystemOpsStub } from '@tests/unit/shared/Stubs/FileSystemOpsStub';
|
||||
|
||||
describe('TemporaryFileCodeRunner', () => {
|
||||
describe('runCode', () => {
|
||||
describe('directory creation', () => {
|
||||
it('creates temporary directory recursively', async () => {
|
||||
// arrange
|
||||
const expectedDir = 'expected-dir';
|
||||
const expectedIsRecursive = true;
|
||||
|
||||
const folderName = 'privacy.sexy';
|
||||
const temporaryDirName = 'tmp';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withOperatingSystem(
|
||||
new OperatingSystemOpsStub()
|
||||
.withTemporaryDirectoryResult(temporaryDirName),
|
||||
)
|
||||
.withLocation(
|
||||
new LocationOpsStub()
|
||||
.withJoinResult(expectedDir, temporaryDirName, folderName),
|
||||
)
|
||||
.withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
await context
|
||||
.withFolderName(folderName)
|
||||
.runCode();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'createDirectory');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualPath, actualIsRecursive] = calls[0].args;
|
||||
expect(actualPath).to.equal(expectedDir);
|
||||
expect(actualIsRecursive).to.equal(expectedIsRecursive);
|
||||
});
|
||||
});
|
||||
describe('file creation', () => {
|
||||
it('creates a file with expected code', async () => {
|
||||
// arrange
|
||||
const expectedCode = 'expected-code';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withFileSystem(filesystem));
|
||||
// act
|
||||
await context
|
||||
.withCode(expectedCode)
|
||||
.runCode();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [, actualData] = calls[0].args;
|
||||
expect(actualData).to.equal(expectedCode);
|
||||
});
|
||||
it('creates file in expected directory', async () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||
const temporaryDirName = '/tmp';
|
||||
const folderName = 'privacy.sexy';
|
||||
const expectedDirectory = [temporaryDirName, folderName].join(pathSegmentSeparator);
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withOperatingSystem(
|
||||
new OperatingSystemOpsStub()
|
||||
.withTemporaryDirectoryResult(temporaryDirName),
|
||||
)
|
||||
.withLocation(
|
||||
new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator),
|
||||
)
|
||||
.withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
await context
|
||||
.withFolderName(folderName)
|
||||
.runCode();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualFilePath] = calls[0].args;
|
||||
const actualDirectory = actualFilePath
|
||||
.split(pathSegmentSeparator)
|
||||
.slice(0, -1)
|
||||
.join(pathSegmentSeparator);
|
||||
expect(actualDirectory).to.equal(expectedDirectory, formatAssertionMessage([
|
||||
`Actual file path: ${actualFilePath}`,
|
||||
]));
|
||||
});
|
||||
it('creates file with expected file name', async () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const expectedFilename = 'expected-script-file-name';
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withFileNameGenerator(new FilenameGeneratorStub().withFilename(expectedFilename))
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withFileSystem(filesystem)
|
||||
.withLocation(new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator)));
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualFilePath] = calls[0].args;
|
||||
const actualFileName = actualFilePath
|
||||
.split(pathSegmentSeparator)
|
||||
.pop();
|
||||
expect(actualFileName).to.equal(actualFileName, formatAssertionMessage([
|
||||
`Actual file path: ${actualFilePath}`,
|
||||
]));
|
||||
});
|
||||
it('creates file after creating the directory', async () => {
|
||||
const expectedOrder: readonly FunctionKeys<FileSystemOps>[] = [
|
||||
'createDirectory',
|
||||
'writeToFile',
|
||||
];
|
||||
const fileSystem = new FileSystemOpsStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withFileSystem(fileSystem));
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
const actualOrder = fileSystem.callHistory
|
||||
.map((c) => c.methodName)
|
||||
.filter((command) => expectedOrder.includes(command));
|
||||
expect(expectedOrder).to.deep.equal(actualOrder);
|
||||
});
|
||||
});
|
||||
describe('file execution', () => {
|
||||
it('executes correct file', async () => {
|
||||
// arrange
|
||||
const fileSystem = new FileSystemOpsStub();
|
||||
const fileExecutor = new ScriptFileExecutorStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops.withFileSystem(fileSystem))
|
||||
.withFileExecutor(fileExecutor);
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
const writeFileCalls = fileSystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(writeFileCalls.length).to.equal(1);
|
||||
const [expectedFilePath] = writeFileCalls[0].args;
|
||||
const execFileCalls = fileExecutor.callHistory.filter((call) => call.methodName === 'executeScriptFile');
|
||||
expect(execFileCalls.length).to.equal(1);
|
||||
const [actualPath] = execFileCalls[0].args;
|
||||
expect(actualPath).to.equal(expectedFilePath);
|
||||
});
|
||||
it('executes after creating the file', async () => {
|
||||
// arrange
|
||||
let isFileCreated = false;
|
||||
let isExecutedAfterCreation = false;
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
filesystem.writeToFile = () => {
|
||||
isFileCreated = true;
|
||||
return Promise.resolve();
|
||||
};
|
||||
const fileExecutor = new ScriptFileExecutorStub();
|
||||
fileExecutor.executeScriptFile = () => {
|
||||
isExecutedAfterCreation = isFileCreated;
|
||||
return Promise.resolve();
|
||||
};
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops.withFileSystem(filesystem))
|
||||
.withFileExecutor(fileExecutor);
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
expect(isExecutedAfterCreation).to.equal(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class CodeRunnerTestSetup {
|
||||
private code = `[${CodeRunnerTestSetup.name}]code`;
|
||||
|
||||
private folderName = `[${CodeRunnerTestSetup.name}]folderName`;
|
||||
|
||||
private filenameGenerator: FilenameGenerator = new FilenameGeneratorStub();
|
||||
|
||||
private systemOperations: SystemOperations = new SystemOperationsStub();
|
||||
|
||||
private fileExecutor: ScriptFileExecutor = new ScriptFileExecutorStub();
|
||||
|
||||
private logger: Logger = new LoggerStub();
|
||||
|
||||
public async runCode(): Promise<void> {
|
||||
const runner = new TemporaryFileCodeRunner(
|
||||
this.systemOperations,
|
||||
this.filenameGenerator,
|
||||
this.logger,
|
||||
this.fileExecutor,
|
||||
);
|
||||
await runner.runCode(this.code, this.folderName);
|
||||
}
|
||||
|
||||
public withSystemOperations(
|
||||
systemOperations: SystemOperations,
|
||||
): this {
|
||||
this.systemOperations = systemOperations;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withSystemOperationsStub(
|
||||
setup: (stub: SystemOperationsStub) => SystemOperationsStub,
|
||||
): this {
|
||||
const stub = setup(new SystemOperationsStub());
|
||||
return this.withSystemOperations(stub);
|
||||
}
|
||||
|
||||
public withFolderName(folderName: string): this {
|
||||
this.folderName = folderName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withFileExecutor(fileExecutor: ScriptFileExecutor): this {
|
||||
this.fileExecutor = fileExecutor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withCode(code: string): this {
|
||||
this.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withFileNameGenerator(fileNameGenerator: FilenameGenerator): this {
|
||||
this.filenameGenerator = fileNameGenerator;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { BrowserCondition, TouchSupportExpectation } from '@/infrastructure/RuntimeEnvironment/BrowserOs/BrowserCondition';
|
||||
import { ConditionBasedOsDetector } from '@/infrastructure/RuntimeEnvironment/BrowserOs/ConditionBasedOsDetector';
|
||||
import { BrowserCondition, TouchSupportExpectation } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserOs/BrowserCondition';
|
||||
import { ConditionBasedOsDetector } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserOs/ConditionBasedOsDetector';
|
||||
import { getAbsentStringTestCases, itEachAbsentCollectionValue } from '@tests/unit/shared/TestCases/AbsentTests';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { BrowserEnvironmentStub } from '@tests/unit/shared/Stubs/BrowserEnvironmentStub';
|
||||
@@ -1,15 +1,15 @@
|
||||
// eslint-disable-next-line max-classes-per-file
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { BrowserOsDetector } from '@/infrastructure/RuntimeEnvironment/BrowserOs/BrowserOsDetector';
|
||||
import { BrowserOsDetector } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserOs/BrowserOsDetector';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { BrowserRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserRuntimeEnvironment';
|
||||
import { itEachAbsentObjectValue } from '@tests/unit/shared/TestCases/AbsentTests';
|
||||
import { BrowserOsDetectorStub } from '@tests/unit/shared/Stubs/BrowserOsDetectorStub';
|
||||
import { IEnvironmentVariables } from '@/infrastructure/EnvironmentVariables/IEnvironmentVariables';
|
||||
import { EnvironmentVariablesStub } from '@tests/unit/shared/Stubs/EnvironmentVariablesStub';
|
||||
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
|
||||
|
||||
describe('HostRuntimeEnvironment', () => {
|
||||
describe('BrowserRuntimeEnvironment', () => {
|
||||
describe('ctor', () => {
|
||||
describe('throws if window is absent', () => {
|
||||
itEachAbsentObjectValue((absentValue) => {
|
||||
@@ -17,9 +17,9 @@ describe('HostRuntimeEnvironment', () => {
|
||||
const expectedError = 'missing window';
|
||||
const absentWindow = absentValue;
|
||||
// act
|
||||
const act = () => createEnvironment({
|
||||
window: absentWindow as never,
|
||||
});
|
||||
const act = () => new BrowserRuntimeEnvironmentBuilder()
|
||||
.withWindow(absentWindow as never)
|
||||
.build();
|
||||
// assert
|
||||
expect(act).to.throw(expectedError);
|
||||
});
|
||||
@@ -28,12 +28,13 @@ describe('HostRuntimeEnvironment', () => {
|
||||
// arrange
|
||||
const expectedTouchSupport = true;
|
||||
const osDetector = new BrowserOsDetectorStub();
|
||||
const window = { os: undefined, navigator: { userAgent: 'Forcing touch detection' } } as Partial<Window>;
|
||||
// act
|
||||
createEnvironment({
|
||||
window: { os: undefined, navigator: { userAgent: 'Forcing touch detection' } } as Partial<Window>,
|
||||
isTouchSupported: expectedTouchSupport,
|
||||
browserOsDetector: osDetector,
|
||||
});
|
||||
new BrowserRuntimeEnvironmentBuilder()
|
||||
.withWindow(window)
|
||||
.withBrowserOsDetector(osDetector)
|
||||
.withTouchSupported(expectedTouchSupport)
|
||||
.build();
|
||||
// assert
|
||||
const actualCall = osDetector.callHistory.find((c) => c.methodName === 'detect');
|
||||
expectExists(actualCall);
|
||||
@@ -48,9 +49,9 @@ describe('HostRuntimeEnvironment', () => {
|
||||
isDesktop: true,
|
||||
};
|
||||
// act
|
||||
const sut = createEnvironment({
|
||||
window: desktopWindow,
|
||||
});
|
||||
const sut = new BrowserRuntimeEnvironmentBuilder()
|
||||
.withWindow(desktopWindow)
|
||||
.build();
|
||||
// assert
|
||||
expect(sut.isDesktop).to.equal(true);
|
||||
});
|
||||
@@ -61,9 +62,9 @@ describe('HostRuntimeEnvironment', () => {
|
||||
isDesktop: false,
|
||||
};
|
||||
// act
|
||||
const sut = createEnvironment({
|
||||
window: browserWindow,
|
||||
});
|
||||
const sut = new BrowserRuntimeEnvironmentBuilder()
|
||||
.withWindow(browserWindow)
|
||||
.build();
|
||||
// assert
|
||||
expect(sut.isDesktop).to.equal(expectedValue);
|
||||
});
|
||||
@@ -77,9 +78,9 @@ describe('HostRuntimeEnvironment', () => {
|
||||
throw new Error('should not reach here');
|
||||
},
|
||||
};
|
||||
const sut = createEnvironment({
|
||||
browserOsDetector: browserDetectorMock,
|
||||
});
|
||||
const sut = new BrowserRuntimeEnvironmentBuilder()
|
||||
.withBrowserOsDetector(browserDetectorMock)
|
||||
.build();
|
||||
// act
|
||||
const actual = sut.os;
|
||||
// assert
|
||||
@@ -103,10 +104,10 @@ describe('HostRuntimeEnvironment', () => {
|
||||
},
|
||||
};
|
||||
// act
|
||||
const sut = createEnvironment({
|
||||
window: windowWithUserAgent as Partial<Window>,
|
||||
browserOsDetector: browserDetectorMock,
|
||||
});
|
||||
const sut = new BrowserRuntimeEnvironmentBuilder()
|
||||
.withWindow(windowWithUserAgent as Partial<Window>)
|
||||
.withBrowserOsDetector(browserDetectorMock)
|
||||
.build();
|
||||
const actual = sut.os;
|
||||
// assert
|
||||
expect(actual).to.equal(expected);
|
||||
@@ -127,9 +128,9 @@ describe('HostRuntimeEnvironment', () => {
|
||||
os: expectedOs,
|
||||
};
|
||||
// act
|
||||
const sut = createEnvironment({
|
||||
window: desktopWindowWithOs,
|
||||
});
|
||||
const sut = new BrowserRuntimeEnvironmentBuilder()
|
||||
.withWindow(desktopWindowWithOs)
|
||||
.build();
|
||||
// assert
|
||||
const actualOs = sut.os;
|
||||
expect(actualOs).to.equal(expectedOs);
|
||||
@@ -144,9 +145,9 @@ describe('HostRuntimeEnvironment', () => {
|
||||
os: absentValue as never,
|
||||
};
|
||||
// act
|
||||
const sut = createEnvironment({
|
||||
window: windowWithAbsentOs,
|
||||
});
|
||||
const sut = new BrowserRuntimeEnvironmentBuilder()
|
||||
.withWindow(windowWithAbsentOs)
|
||||
.build();
|
||||
// assert
|
||||
expect(sut.os).to.equal(expectedValue);
|
||||
});
|
||||
@@ -161,9 +162,9 @@ describe('HostRuntimeEnvironment', () => {
|
||||
const environment = new EnvironmentVariablesStub()
|
||||
.withIsNonProduction(expectedValue);
|
||||
// act
|
||||
const sut = createEnvironment({
|
||||
environmentVariables: environment,
|
||||
});
|
||||
const sut = new BrowserRuntimeEnvironmentBuilder()
|
||||
.withEnvironmentVariables(environment)
|
||||
.build();
|
||||
// assert
|
||||
const actualValue = sut.isNonProduction;
|
||||
expect(actualValue).to.equal(expectedValue);
|
||||
@@ -172,32 +173,41 @@ describe('HostRuntimeEnvironment', () => {
|
||||
});
|
||||
});
|
||||
|
||||
interface EnvironmentOptions {
|
||||
readonly window?: Partial<Window>;
|
||||
readonly browserOsDetector?: BrowserOsDetector;
|
||||
readonly environmentVariables?: IEnvironmentVariables;
|
||||
readonly isTouchSupported?: boolean;
|
||||
}
|
||||
class BrowserRuntimeEnvironmentBuilder {
|
||||
private window: Partial<Window> = {};
|
||||
|
||||
function createEnvironment(options: Partial<EnvironmentOptions> = {}): TestableRuntimeEnvironment {
|
||||
const defaultOptions: Required<EnvironmentOptions> = {
|
||||
window: {},
|
||||
browserOsDetector: new BrowserOsDetectorStub(),
|
||||
environmentVariables: new EnvironmentVariablesStub(),
|
||||
isTouchSupported: false,
|
||||
};
|
||||
private browserOsDetector: BrowserOsDetector = new BrowserOsDetectorStub();
|
||||
|
||||
return new TestableRuntimeEnvironment({ ...defaultOptions, ...options });
|
||||
}
|
||||
private environmentVariables: IEnvironmentVariables = new EnvironmentVariablesStub();
|
||||
|
||||
class TestableRuntimeEnvironment extends HostRuntimeEnvironment {
|
||||
/* Using a separate object instead of `ConstructorParameter<..>` */
|
||||
public constructor(options: Required<EnvironmentOptions>) {
|
||||
super(
|
||||
options.window,
|
||||
options.environmentVariables,
|
||||
options.browserOsDetector,
|
||||
() => options.isTouchSupported,
|
||||
private isTouchSupported = false;
|
||||
|
||||
public withEnvironmentVariables(environmentVariables: IEnvironmentVariables): this {
|
||||
this.environmentVariables = environmentVariables;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withWindow(window: Partial<Window>): this {
|
||||
this.window = window;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withBrowserOsDetector(browserOsDetector: BrowserOsDetector): this {
|
||||
this.browserOsDetector = browserOsDetector;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withTouchSupported(isTouchSupported: boolean): this {
|
||||
this.isTouchSupported = isTouchSupported;
|
||||
return this;
|
||||
}
|
||||
|
||||
public build() {
|
||||
return new BrowserRuntimeEnvironment(
|
||||
this.window,
|
||||
this.environmentVariables,
|
||||
this.browserOsDetector,
|
||||
() => this.isTouchSupported,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { BrowserTouchSupportAccessor, isTouchEnabledDevice } from '@/infrastructure/RuntimeEnvironment/TouchSupportDetection';
|
||||
import { BrowserTouchSupportAccessor, isTouchEnabledDevice } from '@/infrastructure/RuntimeEnvironment/Browser/TouchSupportDetection';
|
||||
|
||||
describe('TouchSupportDetection', () => {
|
||||
describe('isTouchEnabledDevice', () => {
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe } from 'vitest';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { convertPlatformToOs } from '@/presentation/electron/preload/ContextBridging/NodeOsMapper';
|
||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||
import { convertPlatformToOs } from '@/infrastructure/RuntimeEnvironment/Node/NodeOsMapper';
|
||||
|
||||
describe('NodeOsMapper', () => {
|
||||
describe('convertPlatformToOs', () => {
|
||||
@@ -0,0 +1,146 @@
|
||||
// eslint-disable-next-line max-classes-per-file
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { NodeJSProcessAccessor, NodeRuntimeEnvironment, PlatformToOperatingSystemConverter } from '@/infrastructure/RuntimeEnvironment/Node/NodeRuntimeEnvironment';
|
||||
import { itEachAbsentObjectValue } from '@tests/unit/shared/TestCases/AbsentTests';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
|
||||
describe('NodeRuntimeEnvironment', () => {
|
||||
describe('constructor', () => {
|
||||
describe('throws with missing process', () => {
|
||||
itEachAbsentObjectValue((absentValue) => {
|
||||
// arrange
|
||||
const expectedError = 'missing process';
|
||||
const absentProcess = absentValue;
|
||||
// act
|
||||
const act = () => new NodeRuntimeEnvironmentBuilder()
|
||||
.withProcess(absentProcess as never)
|
||||
.build();
|
||||
// assert
|
||||
expect(act).to.throw(expectedError);
|
||||
}, { excludeUndefined: true });
|
||||
});
|
||||
});
|
||||
describe('os', () => {
|
||||
it('matches specified OS', () => {
|
||||
// arrange
|
||||
const expectedOs = OperatingSystem.Android;
|
||||
const osConverterMock: PlatformToOperatingSystemConverter = () => expectedOs;
|
||||
// act
|
||||
const environment = new NodeRuntimeEnvironmentBuilder()
|
||||
.withOsConverter(osConverterMock)
|
||||
.build();
|
||||
// assert
|
||||
expect(environment.os).to.equal(expectedOs);
|
||||
});
|
||||
it('uses process platform to determine OS', () => {
|
||||
// arrange
|
||||
const expectedPlatform: NodeJS.Platform = 'win32';
|
||||
let actualPlatform: NodeJS.Platform | undefined;
|
||||
const osConverterMock: PlatformToOperatingSystemConverter = (platform) => {
|
||||
actualPlatform = platform;
|
||||
return undefined;
|
||||
};
|
||||
const nodeProcessMock = new NodeJSProcessAccessorStub()
|
||||
.withPlatform(expectedPlatform);
|
||||
// act
|
||||
new NodeRuntimeEnvironmentBuilder()
|
||||
.withOsConverter(osConverterMock)
|
||||
.withProcess(nodeProcessMock)
|
||||
.build();
|
||||
// assert
|
||||
expect(expectedPlatform).to.equal(actualPlatform);
|
||||
});
|
||||
it('is undefined for unknown platforms', () => {
|
||||
// arrange
|
||||
const expectedOs = undefined;
|
||||
const osConverterMock: PlatformToOperatingSystemConverter = () => undefined;
|
||||
// act
|
||||
const environment = new NodeRuntimeEnvironmentBuilder()
|
||||
.withOsConverter(osConverterMock)
|
||||
.build();
|
||||
// assert
|
||||
expect(environment.os).to.equal(expectedOs);
|
||||
});
|
||||
});
|
||||
describe('isDesktop', () => {
|
||||
it('is always true', () => {
|
||||
// arrange
|
||||
const expectedDesktopCondition = true;
|
||||
// act
|
||||
const environment = new NodeRuntimeEnvironment();
|
||||
/// assert
|
||||
expect(environment.isDesktop).to.equal(expectedDesktopCondition);
|
||||
});
|
||||
});
|
||||
describe('isNonProduction', () => {
|
||||
it('identifies development mode', () => {
|
||||
// arrange
|
||||
const expectedNonProductionCondition = true;
|
||||
const nodeProcess = new NodeJSProcessAccessorStub()
|
||||
.withNodeEnv('development');
|
||||
// act
|
||||
const environment = new NodeRuntimeEnvironmentBuilder()
|
||||
.withProcess(nodeProcess)
|
||||
.build();
|
||||
/// assert
|
||||
expect(environment.isNonProduction).to.equal(expectedNonProductionCondition);
|
||||
});
|
||||
it('identifies production mode', () => {
|
||||
// arrange
|
||||
const expectedNonProductionCondition = false;
|
||||
const nodeProcess = new NodeJSProcessAccessorStub()
|
||||
.withNodeEnv('production');
|
||||
// act
|
||||
const environment = new NodeRuntimeEnvironmentBuilder()
|
||||
.withProcess(nodeProcess)
|
||||
.build();
|
||||
/// assert
|
||||
expect(environment.isNonProduction).to.equal(expectedNonProductionCondition);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class NodeJSProcessAccessorStub implements NodeJSProcessAccessor {
|
||||
private nodeEnv?: string = 'development';
|
||||
|
||||
public platform: NodeJS.Platform = 'linux';
|
||||
|
||||
public get env() {
|
||||
return {
|
||||
NODE_ENV: this.nodeEnv,
|
||||
};
|
||||
}
|
||||
|
||||
public withNodeEnv(nodeEnv?: string): this {
|
||||
this.nodeEnv = nodeEnv;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withPlatform(platform: NodeJS.Platform): this {
|
||||
this.platform = platform;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
class NodeRuntimeEnvironmentBuilder {
|
||||
private process?: NodeJSProcessAccessor = new NodeJSProcessAccessorStub();
|
||||
|
||||
private osConverter?: PlatformToOperatingSystemConverter = () => OperatingSystem.Windows;
|
||||
|
||||
public withProcess(process?: NodeJSProcessAccessor): this {
|
||||
this.process = process;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withOsConverter(osConverter?: PlatformToOperatingSystemConverter): this {
|
||||
this.osConverter = osConverter;
|
||||
return this;
|
||||
}
|
||||
|
||||
public build(): NodeRuntimeEnvironment {
|
||||
return new NodeRuntimeEnvironment(
|
||||
this.process,
|
||||
this.osConverter,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
BrowserRuntimeEnvironmentFactory, NodeRuntimeEnvironmentFactory,
|
||||
WindowAccessor, determineAndCreateRuntimeEnvironment,
|
||||
} from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub';
|
||||
|
||||
describe('RuntimeEnvironmentFactory', () => {
|
||||
describe('determineAndCreateRuntimeEnvironment', () => {
|
||||
it('uses browser environment when window exists', () => {
|
||||
// arrange
|
||||
const expectedEnvironment = new RuntimeEnvironmentStub();
|
||||
const context = new RuntimeEnvironmentFactoryTestSetup()
|
||||
.withWindowAccessor(() => { return {} as Window; })
|
||||
.withBrowserEnvironmentFactory(() => expectedEnvironment);
|
||||
// act
|
||||
const actualEnvironment = context.buildEnvironment();
|
||||
// assert
|
||||
expect(actualEnvironment).to.equal(expectedEnvironment);
|
||||
});
|
||||
|
||||
it('passes correct window to browser environment', () => {
|
||||
// arrange
|
||||
const expectedWindow = {} as Window;
|
||||
let actualWindow: Window | undefined;
|
||||
const browserEnvironmentFactoryMock: BrowserRuntimeEnvironmentFactory = (providedWindow) => {
|
||||
actualWindow = providedWindow;
|
||||
return new RuntimeEnvironmentStub();
|
||||
};
|
||||
const context = new RuntimeEnvironmentFactoryTestSetup()
|
||||
.withWindowAccessor(() => expectedWindow)
|
||||
.withBrowserEnvironmentFactory(browserEnvironmentFactoryMock);
|
||||
// act
|
||||
context.buildEnvironment();
|
||||
// assert
|
||||
expect(actualWindow).to.equal(expectedWindow);
|
||||
});
|
||||
|
||||
it('uses node environment when window is absent', () => {
|
||||
// arrange
|
||||
const expectedEnvironment = new RuntimeEnvironmentStub();
|
||||
const context = new RuntimeEnvironmentFactoryTestSetup()
|
||||
.withWindowAccessor(() => undefined)
|
||||
.withNodeEnvironmentFactory(() => expectedEnvironment);
|
||||
// act
|
||||
const actualEnvironment = context.buildEnvironment();
|
||||
// assert
|
||||
expect(actualEnvironment).to.equal(expectedEnvironment);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
export class RuntimeEnvironmentFactoryTestSetup {
|
||||
private windowAccessor: WindowAccessor = () => undefined;
|
||||
|
||||
private browserEnvironmentFactory
|
||||
: BrowserRuntimeEnvironmentFactory = () => new RuntimeEnvironmentStub();
|
||||
|
||||
private nodeEnvironmentFactory
|
||||
: NodeRuntimeEnvironmentFactory = () => new RuntimeEnvironmentStub();
|
||||
|
||||
public withWindowAccessor(windowAccessor: WindowAccessor): this {
|
||||
this.windowAccessor = windowAccessor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withNodeEnvironmentFactory(
|
||||
nodeEnvironmentFactory: NodeRuntimeEnvironmentFactory,
|
||||
): this {
|
||||
this.nodeEnvironmentFactory = nodeEnvironmentFactory;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withBrowserEnvironmentFactory(
|
||||
browserEnvironmentFactory: BrowserRuntimeEnvironmentFactory,
|
||||
): this {
|
||||
this.browserEnvironmentFactory = browserEnvironmentFactory;
|
||||
return this;
|
||||
}
|
||||
|
||||
public buildEnvironment(): ReturnType<typeof determineAndCreateRuntimeEnvironment> {
|
||||
return determineAndCreateRuntimeEnvironment(
|
||||
this.windowAccessor,
|
||||
this.browserEnvironmentFactory,
|
||||
this.nodeEnvironmentFactory,
|
||||
);
|
||||
}
|
||||
}
|
||||
111
tests/unit/presentation/electron/main/IpcRegistration.spec.ts
Normal file
111
tests/unit/presentation/electron/main/IpcRegistration.spec.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { CodeRunnerStub } from '@tests/unit/shared/Stubs/CodeRunnerStub';
|
||||
import { IpcChannelDefinitions } from '@/presentation/electron/shared/IpcBridging/IpcChannelDefinitions';
|
||||
import { CodeRunnerFactory, IpcRegistrar, registerAllIpcChannels } from '@/presentation/electron/main/IpcRegistration';
|
||||
import { IpcChannel } from '@/presentation/electron/shared/IpcBridging/IpcChannel';
|
||||
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
|
||||
import { collectExceptionMessage } from '@tests/unit/shared/ExceptionCollector';
|
||||
|
||||
describe('IpcRegistration', () => {
|
||||
describe('registerAllIpcChannels', () => {
|
||||
it('registers all defined IPC channels', () => {
|
||||
Object.entries(IpcChannelDefinitions).forEach(([key, expectedChannel]) => {
|
||||
it(key, () => {
|
||||
// arrange
|
||||
const { registrarMock, isChannelRegistered } = createIpcRegistrarMock();
|
||||
const context = new IpcRegistrationTestSetup()
|
||||
.withRegistrar(registrarMock);
|
||||
// act
|
||||
context.run();
|
||||
// assert
|
||||
expect(isChannelRegistered(expectedChannel)).to.equal(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('registers expected instances', () => {
|
||||
const testScenarios: Record<keyof typeof IpcChannelDefinitions, {
|
||||
buildContext: (context: IpcRegistrationTestSetup) => IpcRegistrationTestSetup,
|
||||
expectedInstance: object,
|
||||
}> = {
|
||||
CodeRunner: (() => {
|
||||
const expectedInstance = new CodeRunnerStub();
|
||||
return {
|
||||
buildContext: (c) => c.withCodeRunnerFactory(() => expectedInstance),
|
||||
expectedInstance,
|
||||
};
|
||||
})(),
|
||||
};
|
||||
Object.entries(testScenarios).forEach(([
|
||||
key, { buildContext, expectedInstance },
|
||||
]) => {
|
||||
it(key, () => {
|
||||
// arrange
|
||||
const { registrarMock, getRegisteredInstance } = createIpcRegistrarMock();
|
||||
const context = buildContext(new IpcRegistrationTestSetup()
|
||||
.withRegistrar(registrarMock));
|
||||
// act
|
||||
context.run();
|
||||
// assert
|
||||
const actualInstance = getRegisteredInstance(IpcChannelDefinitions.CodeRunner);
|
||||
expect(actualInstance).to.equal(expectedInstance);
|
||||
});
|
||||
});
|
||||
});
|
||||
it('throws an error if registration fails', () => {
|
||||
// arrange
|
||||
const expectedError = 'registrar error';
|
||||
const registrarMock: IpcRegistrar = () => {
|
||||
throw new Error(expectedError);
|
||||
};
|
||||
const context = new IpcRegistrationTestSetup()
|
||||
.withRegistrar(registrarMock);
|
||||
// act
|
||||
const exceptionMessage = collectExceptionMessage(() => context.run());
|
||||
// assert
|
||||
expect(exceptionMessage).to.include(expectedError);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class IpcRegistrationTestSetup {
|
||||
private codeRunnerFactory: CodeRunnerFactory = () => new CodeRunnerStub();
|
||||
|
||||
private registrar: IpcRegistrar = () => { /* NOOP */ };
|
||||
|
||||
public withRegistrar(registrar: IpcRegistrar): this {
|
||||
this.registrar = registrar;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withCodeRunnerFactory(codeRunnerFactory: CodeRunnerFactory): this {
|
||||
this.codeRunnerFactory = codeRunnerFactory;
|
||||
return this;
|
||||
}
|
||||
|
||||
public run() {
|
||||
registerAllIpcChannels(
|
||||
this.codeRunnerFactory,
|
||||
this.registrar,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function createIpcRegistrarMock() {
|
||||
const registeredChannels = new Array<Parameters<IpcRegistrar>>();
|
||||
const registrarMock: IpcRegistrar = <T>(channel: IpcChannel<T>, obj: T) => {
|
||||
registeredChannels.push([channel as IpcChannel<unknown>, obj]);
|
||||
};
|
||||
const isChannelRegistered = <T>(channel: IpcChannel<T>): boolean => {
|
||||
return registeredChannels.some((i) => i[0] === channel);
|
||||
};
|
||||
const getRegisteredInstance = <T>(channel: IpcChannel<T>): unknown => {
|
||||
const registration = registeredChannels.find((i) => i[0] === channel);
|
||||
expectExists(registration);
|
||||
return registration[1];
|
||||
};
|
||||
return {
|
||||
registrarMock,
|
||||
isChannelRegistered,
|
||||
getRegisteredInstance,
|
||||
};
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ApiFacadeFactory, provideWindowVariables } from '@/presentation/electron/preload/ContextBridging/RendererApiProvider';
|
||||
import { ApiFacadeFactory, IpcConsumerProxyCreator, provideWindowVariables } from '@/presentation/electron/preload/ContextBridging/RendererApiProvider';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||
import { CodeRunner } from '@/application/CodeRunner';
|
||||
import { CodeRunnerStub } from '@tests/unit/shared/Stubs/CodeRunnerStub';
|
||||
import { PropertyKeys } from '@/TypeHelpers';
|
||||
import { WindowVariables } from '@/infrastructure/WindowVariables/WindowVariables';
|
||||
import { IpcChannelDefinitions } from '@/presentation/electron/shared/IpcBridging/IpcChannelDefinitions';
|
||||
import { IpcChannel } from '@/presentation/electron/shared/IpcBridging/IpcChannel';
|
||||
|
||||
describe('RendererApiProvider', () => {
|
||||
describe('provideWindowVariables', () => {
|
||||
@@ -21,17 +21,7 @@ describe('RendererApiProvider', () => {
|
||||
setupContext: (context) => context,
|
||||
expectedValue: true,
|
||||
},
|
||||
codeRunner: (() => {
|
||||
const codeRunner = new CodeRunnerStub();
|
||||
const createFacadeMock: ApiFacadeFactory = (obj) => obj;
|
||||
return {
|
||||
description: 'encapsulates correctly',
|
||||
setupContext: (context) => context
|
||||
.withCodeRunner(codeRunner)
|
||||
.withApiFacadeCreator(createFacadeMock),
|
||||
expectedValue: codeRunner,
|
||||
};
|
||||
})(),
|
||||
codeRunner: expectIpcConsumer(IpcChannelDefinitions.CodeRunner),
|
||||
os: (() => {
|
||||
const operatingSystem = OperatingSystem.WindowsPhone;
|
||||
return {
|
||||
@@ -40,17 +30,10 @@ describe('RendererApiProvider', () => {
|
||||
expectedValue: operatingSystem,
|
||||
};
|
||||
})(),
|
||||
log: (() => {
|
||||
const logger = new LoggerStub();
|
||||
const createFacadeMock: ApiFacadeFactory = (obj) => obj;
|
||||
return {
|
||||
description: 'encapsulates correctly',
|
||||
setupContext: (context) => context
|
||||
.withLogger(logger)
|
||||
.withApiFacadeCreator(createFacadeMock),
|
||||
expectedValue: logger,
|
||||
};
|
||||
})(),
|
||||
log: expectFacade({
|
||||
instance: new LoggerStub(),
|
||||
setupContext: (c, logger) => c.withLogger(logger),
|
||||
}),
|
||||
};
|
||||
Object.entries(testScenarios).forEach((
|
||||
[property, { description, setupContext, expectedValue }],
|
||||
@@ -65,22 +48,43 @@ describe('RendererApiProvider', () => {
|
||||
expect(actualValue).to.equal(expectedValue);
|
||||
});
|
||||
});
|
||||
function expectIpcConsumer<T>(expectedDefinition: IpcChannel<T>): WindowVariableTestCase {
|
||||
const ipcConsumerCreator: IpcConsumerProxyCreator = (definition) => definition as never;
|
||||
return {
|
||||
description: 'creates correct IPC consumer',
|
||||
setupContext: (context) => context
|
||||
.withIpcConsumerCreator(ipcConsumerCreator),
|
||||
expectedValue: expectedDefinition,
|
||||
};
|
||||
}
|
||||
function expectFacade<T>(options: {
|
||||
readonly instance: T;
|
||||
setupContext: (
|
||||
context: RendererApiProviderTestContext,
|
||||
instance: T,
|
||||
) => RendererApiProviderTestContext;
|
||||
}): WindowVariableTestCase {
|
||||
const createFacadeMock: ApiFacadeFactory = (obj) => obj;
|
||||
return {
|
||||
description: 'creates correct facade',
|
||||
setupContext: (context) => options.setupContext(
|
||||
context.withApiFacadeCreator(createFacadeMock),
|
||||
options.instance,
|
||||
),
|
||||
expectedValue: options.instance,
|
||||
};
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
class RendererApiProviderTestContext {
|
||||
private codeRunner: CodeRunner = new CodeRunnerStub();
|
||||
|
||||
private os: OperatingSystem = OperatingSystem.Android;
|
||||
|
||||
private log: Logger = new LoggerStub();
|
||||
|
||||
private apiFacadeCreator: ApiFacadeFactory = (obj) => obj;
|
||||
|
||||
public withCodeRunner(codeRunner: CodeRunner): this {
|
||||
this.codeRunner = codeRunner;
|
||||
return this;
|
||||
}
|
||||
private ipcConsumerCreator: IpcConsumerProxyCreator = () => { return {} as never; };
|
||||
|
||||
public withOs(os: OperatingSystem): this {
|
||||
this.os = os;
|
||||
@@ -97,12 +101,17 @@ class RendererApiProviderTestContext {
|
||||
return this;
|
||||
}
|
||||
|
||||
public withIpcConsumerCreator(ipcConsumerCreator: IpcConsumerProxyCreator): this {
|
||||
this.ipcConsumerCreator = ipcConsumerCreator;
|
||||
return this;
|
||||
}
|
||||
|
||||
public provideWindowVariables() {
|
||||
return provideWindowVariables(
|
||||
() => this.codeRunner,
|
||||
() => this.log,
|
||||
() => this.os,
|
||||
this.apiFacadeCreator,
|
||||
this.ipcConsumerCreator,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { IpcChannel } from '@/presentation/electron/shared/IpcBridging/IpcChannel';
|
||||
import { IpcChannelDefinitions } from '@/presentation/electron/shared/IpcBridging/IpcChannelDefinitions';
|
||||
|
||||
describe('IpcChannelDefinitions', () => {
|
||||
it('defines IPC channels correctly', () => {
|
||||
const testScenarios: Record<keyof typeof IpcChannelDefinitions, {
|
||||
readonly expectedNamespace: string;
|
||||
readonly expectedAccessibleMembers: readonly string[];
|
||||
}> = {
|
||||
CodeRunner: {
|
||||
expectedNamespace: 'code-run',
|
||||
expectedAccessibleMembers: ['runCode'],
|
||||
},
|
||||
};
|
||||
Object.entries(testScenarios).forEach((
|
||||
[definitionKey, { expectedNamespace, expectedAccessibleMembers }],
|
||||
) => {
|
||||
describe(`channel: "${definitionKey}"`, () => {
|
||||
const ipcChannelUnderTest = IpcChannelDefinitions[definitionKey] as IpcChannel<unknown>;
|
||||
it('has expected namespace', () => {
|
||||
// act
|
||||
const actualNamespace = ipcChannelUnderTest.namespace;
|
||||
// assert
|
||||
expect(actualNamespace).to.equal(expectedNamespace);
|
||||
});
|
||||
it('has expected accessible members', () => {
|
||||
// act
|
||||
const actualAccessibleMembers = ipcChannelUnderTest.accessibleMembers;
|
||||
// assert
|
||||
expect(actualAccessibleMembers).to.have.lengthOf(expectedAccessibleMembers.length);
|
||||
expect(actualAccessibleMembers).to.have.members(expectedAccessibleMembers);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('IPC channel uniqueness', () => {
|
||||
it('has unique namespaces', () => {
|
||||
// arrange
|
||||
const extractedNamespacesFromDefinitions = Object
|
||||
.values(IpcChannelDefinitions)
|
||||
.map((channel) => channel.namespace);
|
||||
// act
|
||||
const duplicateNamespaceEntries = extractedNamespacesFromDefinitions
|
||||
.filter((item, index) => extractedNamespacesFromDefinitions.indexOf(item) !== index);
|
||||
// assert
|
||||
expect(duplicateNamespaceEntries).to.have.lengthOf(0);
|
||||
});
|
||||
it('has unique accessible members within each channel', () => {
|
||||
Object.values(IpcChannelDefinitions).forEach((channel) => {
|
||||
// arrange
|
||||
const { accessibleMembers: accessibleMembersOfChannel } = channel;
|
||||
// act
|
||||
const repeatedAccessibleMembersInChannel = accessibleMembersOfChannel
|
||||
.filter((item, index) => accessibleMembersOfChannel.indexOf(item) !== index);
|
||||
// assert
|
||||
expect(repeatedAccessibleMembersInChannel).to.have.lengthOf(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
260
tests/unit/presentation/electron/shared/IpcProxy.spec.ts
Normal file
260
tests/unit/presentation/electron/shared/IpcProxy.spec.ts
Normal file
@@ -0,0 +1,260 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createIpcConsumerProxy, registerIpcChannel } from '@/presentation/electron/shared/IpcBridging/IpcProxy';
|
||||
import { IpcChannel } from '@/presentation/electron/shared/IpcBridging/IpcChannel';
|
||||
|
||||
describe('IpcProxy', () => {
|
||||
describe('createIpcConsumerProxy', () => {
|
||||
describe('argument handling', () => {
|
||||
it('sync method in proxy correctly receives and forwards arguments', async () => {
|
||||
// arrange
|
||||
const expectedArg1 = 'expected-arg-1';
|
||||
const expectedArg2 = 2;
|
||||
interface TestSyncMethods {
|
||||
syncMethod(stringArg: string, numberArg: number): void;
|
||||
}
|
||||
const ipcChannelMock: IpcChannel<TestSyncMethods> = {
|
||||
namespace: 'testNamespace',
|
||||
accessibleMembers: ['syncMethod'],
|
||||
};
|
||||
const { registeredCallArgs, ipcRendererMock } = mockIpcRenderer();
|
||||
// act
|
||||
const proxy = createIpcConsumerProxy(ipcChannelMock, ipcRendererMock);
|
||||
await proxy.syncMethod(expectedArg1, expectedArg2);
|
||||
// assert
|
||||
expect(registeredCallArgs).to.have.lengthOf(1);
|
||||
const actualFunctionArgs = registeredCallArgs[0];
|
||||
expect(actualFunctionArgs).to.have.lengthOf(3);
|
||||
expect(actualFunctionArgs[1]).to.equal(expectedArg1);
|
||||
expect(actualFunctionArgs[2]).to.equal(expectedArg2);
|
||||
});
|
||||
it('sync method in proxy correctly returns expected value', async () => {
|
||||
// arrange
|
||||
const expectedArg1 = 'expected-arg-1';
|
||||
const expectedArg2 = 2;
|
||||
interface TestAsyncMethods {
|
||||
asyncMethod(stringArg: string, numberArg: number): Promise<void>;
|
||||
}
|
||||
const mockedIpcChannel: IpcChannel<TestAsyncMethods> = {
|
||||
namespace: 'testNamespace',
|
||||
accessibleMembers: ['asyncMethod'],
|
||||
};
|
||||
const { registeredCallArgs, ipcRendererMock } = mockIpcRenderer();
|
||||
// act
|
||||
const proxy = createIpcConsumerProxy(mockedIpcChannel, ipcRendererMock);
|
||||
await proxy.asyncMethod(expectedArg1, expectedArg2);
|
||||
// assert
|
||||
expect(registeredCallArgs).to.have.lengthOf(1);
|
||||
const actualFunctionArgs = registeredCallArgs[0];
|
||||
expect(actualFunctionArgs).to.have.lengthOf(3);
|
||||
expect(actualFunctionArgs[1]).to.equal(expectedArg1);
|
||||
expect(actualFunctionArgs[2]).to.equal(expectedArg2);
|
||||
});
|
||||
});
|
||||
describe('return value handling', () => {
|
||||
it('sync function returns correct value', async () => {
|
||||
// arrange
|
||||
const expectedReturnValue = 'expected-return-value';
|
||||
interface TestSyncMethods {
|
||||
syncMethod(): typeof expectedReturnValue;
|
||||
}
|
||||
const ipcChannelMock: IpcChannel<TestSyncMethods> = {
|
||||
namespace: 'testNamespace',
|
||||
accessibleMembers: ['syncMethod'],
|
||||
};
|
||||
const { ipcRendererMock } = mockIpcRenderer(Promise.resolve(expectedReturnValue));
|
||||
// act
|
||||
const proxy = createIpcConsumerProxy(ipcChannelMock, ipcRendererMock);
|
||||
const actualReturnValue = await proxy.syncMethod();
|
||||
// assert
|
||||
expect(actualReturnValue).to.equal(expectedReturnValue);
|
||||
});
|
||||
it('async function returns correct value', async () => {
|
||||
// arrange
|
||||
const expectedReturnValue = 'expected-return-value';
|
||||
interface TestAsyncMethods {
|
||||
asyncMethod(): Promise<typeof expectedReturnValue>;
|
||||
}
|
||||
const ipcChannelMock: IpcChannel<TestAsyncMethods> = {
|
||||
namespace: 'testNamespace',
|
||||
accessibleMembers: ['asyncMethod'],
|
||||
};
|
||||
const { ipcRendererMock } = mockIpcRenderer(Promise.resolve(expectedReturnValue));
|
||||
// act
|
||||
const proxy = createIpcConsumerProxy(ipcChannelMock, ipcRendererMock);
|
||||
const actualReturnValue = await proxy.asyncMethod();
|
||||
// assert
|
||||
expect(actualReturnValue).to.equal(expectedReturnValue);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('registerIpcChannel', () => {
|
||||
describe('original function invocation', () => {
|
||||
it('sync function is called with correct arguments', () => {
|
||||
// arrange
|
||||
const expectedArgumentValues = ['first-argument-value', 42];
|
||||
const syncMethodName = 'syncMethod';
|
||||
const testObject = {
|
||||
[syncMethodName]: (stringArg: string, numberArg: number) => {
|
||||
recordedMethodArguments.push([stringArg, numberArg]);
|
||||
},
|
||||
};
|
||||
const recordedMethodArguments = new Array<Parameters<typeof testObject['syncMethod']>>();
|
||||
const testIpcChannel: IpcChannel<typeof testObject> = {
|
||||
namespace: 'testNamespace',
|
||||
accessibleMembers: [syncMethodName],
|
||||
};
|
||||
const { ipcMainMock, registeredHandlersByChannel } = mockIpcMain();
|
||||
|
||||
// act
|
||||
registerIpcChannel(testIpcChannel, testObject, ipcMainMock);
|
||||
const proxyFunction = registeredHandlersByChannel[
|
||||
Object.keys(registeredHandlersByChannel)[0]];
|
||||
proxyFunction(null, ...expectedArgumentValues);
|
||||
|
||||
// assert
|
||||
expect(recordedMethodArguments).to.have.lengthOf(1);
|
||||
const actualArgumentValues = recordedMethodArguments[0];
|
||||
expect(actualArgumentValues).to.deep.equal(expectedArgumentValues);
|
||||
});
|
||||
it('async function is called with correct arguments', async () => {
|
||||
// arrange
|
||||
const expectedArgumentValues = ['first-argument-value', 42];
|
||||
const asyncMethodName = 'asyncMethod';
|
||||
const testObject = {
|
||||
[asyncMethodName]: (stringArg: string, numberArg: number) => {
|
||||
recordedMethodArguments.push([stringArg, numberArg]);
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
const recordedMethodArguments = new Array<Parameters<typeof testObject['asyncMethod']>>();
|
||||
const testIpcChannel: IpcChannel<typeof testObject> = {
|
||||
namespace: 'testNamespace',
|
||||
accessibleMembers: [asyncMethodName],
|
||||
};
|
||||
const { ipcMainMock, registeredHandlersByChannel } = mockIpcMain();
|
||||
|
||||
// act
|
||||
registerIpcChannel(testIpcChannel, testObject, ipcMainMock);
|
||||
const proxyFunction = registeredHandlersByChannel[
|
||||
Object.keys(registeredHandlersByChannel)[0]];
|
||||
await proxyFunction(null, ...expectedArgumentValues);
|
||||
|
||||
// assert
|
||||
expect(recordedMethodArguments).to.have.lengthOf(1);
|
||||
expect(recordedMethodArguments[0]).to.deep.equal(expectedArgumentValues);
|
||||
});
|
||||
});
|
||||
describe('return value handling', () => {
|
||||
it('sync function returns correct value', () => {
|
||||
// arrange
|
||||
const expectedReturnValue = 'expected-return-value';
|
||||
const syncMethodName = 'syncMethod';
|
||||
const testObject = {
|
||||
[syncMethodName]: () => expectedReturnValue,
|
||||
};
|
||||
const testIpcChannel: IpcChannel<typeof testObject> = {
|
||||
namespace: 'testNamespace',
|
||||
accessibleMembers: [syncMethodName],
|
||||
};
|
||||
const { ipcMainMock, registeredHandlersByChannel } = mockIpcMain();
|
||||
|
||||
// act
|
||||
registerIpcChannel(testIpcChannel, testObject, ipcMainMock);
|
||||
const proxyFunction = registeredHandlersByChannel[
|
||||
Object.keys(registeredHandlersByChannel)[0]];
|
||||
const actualReturnValue = proxyFunction(null);
|
||||
|
||||
// assert
|
||||
expect(actualReturnValue).to.equal(expectedReturnValue);
|
||||
});
|
||||
it('async function returns correct value', async () => {
|
||||
// arrange
|
||||
const expectedReturnValue = 'expected-return-value';
|
||||
const asyncMethodName = 'asyncMethod';
|
||||
const testObject = {
|
||||
[asyncMethodName]: () => Promise.resolve(expectedReturnValue),
|
||||
};
|
||||
const testIpcChannel: IpcChannel<typeof testObject> = {
|
||||
namespace: 'testNamespace',
|
||||
accessibleMembers: [asyncMethodName],
|
||||
};
|
||||
const { ipcMainMock, registeredHandlersByChannel } = mockIpcMain();
|
||||
|
||||
// act
|
||||
registerIpcChannel(testIpcChannel, testObject, ipcMainMock);
|
||||
const proxyFunction = registeredHandlersByChannel[
|
||||
Object.keys(registeredHandlersByChannel)[0]];
|
||||
const actualReturnValue = await proxyFunction(null);
|
||||
|
||||
// assert
|
||||
expect(actualReturnValue).to.equal(expectedReturnValue);
|
||||
});
|
||||
});
|
||||
it('registers channel names for each member', () => {
|
||||
// arrange
|
||||
const namespace = 'testNamespace';
|
||||
const method1Name = 'method1';
|
||||
const method2Name = 'method2';
|
||||
const expectedChannelNames = [
|
||||
`proxy:${namespace}:${method1Name}`,
|
||||
`proxy:${namespace}:${method2Name}`,
|
||||
];
|
||||
const testObject = {
|
||||
[`${method1Name}`]: () => {},
|
||||
[`${method2Name}`]: () => Promise.resolve(),
|
||||
};
|
||||
const testIpcChannel: IpcChannel<typeof testObject> = {
|
||||
namespace: 'testNamespace',
|
||||
accessibleMembers: [method1Name, method2Name],
|
||||
};
|
||||
const { ipcMainMock, registeredHandlersByChannel } = mockIpcMain();
|
||||
// act
|
||||
registerIpcChannel(testIpcChannel, testObject, ipcMainMock);
|
||||
// assert
|
||||
const actualChannelNames = Object.keys(registeredHandlersByChannel);
|
||||
expect(actualChannelNames).to.have.lengthOf(expectedChannelNames.length);
|
||||
expect(actualChannelNames).to.have.members(expectedChannelNames);
|
||||
});
|
||||
it('throws error for non-function members', () => {
|
||||
// arrange
|
||||
const expectedError = 'Non-function members are not yet supported';
|
||||
const propertyName = 'propertyKey';
|
||||
const testObject = { [`${propertyName}`]: 123 };
|
||||
const testIpcChannel: IpcChannel<typeof testObject> = {
|
||||
namespace: 'testNamespace',
|
||||
accessibleMembers: [propertyName] as never,
|
||||
};
|
||||
// act
|
||||
const act = () => registerIpcChannel(testIpcChannel, testObject, mockIpcMain().ipcMainMock);
|
||||
// assert
|
||||
expect(act).to.throw(expectedError);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function mockIpcMain() {
|
||||
const registeredHandlersByChannel: Record<string, (...args: unknown[]) => unknown> = {};
|
||||
const ipcMainMock: Partial<Electron.IpcMain> = {
|
||||
handle: (channel, handler) => {
|
||||
registeredHandlersByChannel[channel] = handler;
|
||||
},
|
||||
};
|
||||
return {
|
||||
ipcMainMock: ipcMainMock as Electron.IpcMain,
|
||||
registeredHandlersByChannel,
|
||||
};
|
||||
}
|
||||
|
||||
function mockIpcRenderer(returnValuePromise: Promise<unknown> = Promise.resolve()) {
|
||||
const registeredCallArgs = new Array<Parameters<Electron.IpcRenderer['invoke']>>();
|
||||
const ipcRendererMock: Partial<Electron.IpcRenderer> = {
|
||||
invoke: (...args) => {
|
||||
registeredCallArgs.push([...args]);
|
||||
return returnValuePromise;
|
||||
},
|
||||
};
|
||||
return {
|
||||
ipcRendererMock: ipcRendererMock as Electron.IpcRenderer,
|
||||
registeredCallArgs,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { BrowserCondition, TouchSupportExpectation } from '@/infrastructure/RuntimeEnvironment/BrowserOs/BrowserCondition';
|
||||
import { BrowserCondition, TouchSupportExpectation } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserOs/BrowserCondition';
|
||||
|
||||
export class BrowserConditionStub implements BrowserCondition {
|
||||
public operatingSystem: OperatingSystem = OperatingSystem.Android;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BrowserEnvironment } from '@/infrastructure/RuntimeEnvironment/BrowserOs/BrowserOsDetector';
|
||||
import { BrowserEnvironment } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserOs/BrowserOsDetector';
|
||||
|
||||
export class BrowserEnvironmentStub implements BrowserEnvironment {
|
||||
public isTouchSupported = false;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { BrowserEnvironment, BrowserOsDetector } from '@/infrastructure/RuntimeEnvironment/BrowserOs/BrowserOsDetector';
|
||||
import { BrowserEnvironment, BrowserOsDetector } from '@/infrastructure/RuntimeEnvironment/Browser/BrowserOs/BrowserOsDetector';
|
||||
import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls';
|
||||
|
||||
export class BrowserOsDetectorStub
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CommandOps } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
import { CommandOps } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls';
|
||||
|
||||
export class CommandOpsStub
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FileSystemOps } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
import { FileSystemOps } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls';
|
||||
|
||||
export class FileSystemOpsStub
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FilenameGenerator } from '@/infrastructure/CodeRunner/Filename/FilenameGenerator';
|
||||
import { FilenameGenerator } from '@/infrastructure/CodeRunner/Creation/Filename/FilenameGenerator';
|
||||
|
||||
export class FilenameGeneratorStub implements FilenameGenerator {
|
||||
private filename = `[${FilenameGeneratorStub.name}]file-name-stub`;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { LocationOps } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
import { LocationOps } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls';
|
||||
|
||||
export class LocationOpsStub
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { OperatingSystemOps } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
import { OperatingSystemOps } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls';
|
||||
|
||||
export class OperatingSystemOpsStub
|
||||
extends StubWithObservableMethodCalls<OperatingSystemOps>
|
||||
implements OperatingSystemOps {
|
||||
private temporaryDirectory = '/stub-temp-dir/';
|
||||
private userDataDirectory = `/${OperatingSystemOpsStub.name}-user-data-dir/`;
|
||||
|
||||
public withTemporaryDirectoryResult(directory: string): this {
|
||||
this.temporaryDirectory = directory;
|
||||
public withUserDirectoryResult(directory: string): this {
|
||||
this.userDataDirectory = directory;
|
||||
return this;
|
||||
}
|
||||
|
||||
public getTempDirectory(): string {
|
||||
public getUserDataDirectory(): string {
|
||||
this.registerMethodCall({
|
||||
methodName: 'getTempDirectory',
|
||||
methodName: 'getUserDataDirectory',
|
||||
args: [],
|
||||
});
|
||||
return this.temporaryDirectory;
|
||||
return this.userDataDirectory;
|
||||
}
|
||||
}
|
||||
|
||||
14
tests/unit/shared/Stubs/ScriptDirectoryProviderStub.ts
Normal file
14
tests/unit/shared/Stubs/ScriptDirectoryProviderStub.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { ScriptDirectoryProvider } from '@/infrastructure/CodeRunner/Creation/Directory/ScriptDirectoryProvider';
|
||||
|
||||
export class ScriptDirectoryProviderStub implements ScriptDirectoryProvider {
|
||||
private directoryPath = `[${ScriptDirectoryProviderStub.name}]scriptDirectory`;
|
||||
|
||||
public withDirectoryPath(directoryPath: string): this {
|
||||
this.directoryPath = directoryPath;
|
||||
return this;
|
||||
}
|
||||
|
||||
public provideScriptDirectory(): Promise<string> {
|
||||
return Promise.resolve(this.directoryPath);
|
||||
}
|
||||
}
|
||||
21
tests/unit/shared/Stubs/ScriptFileCreatorStub.ts
Normal file
21
tests/unit/shared/Stubs/ScriptFileCreatorStub.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { ScriptFileCreator } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreator';
|
||||
import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls';
|
||||
|
||||
export class ScriptFileCreatorStub
|
||||
extends StubWithObservableMethodCalls<ScriptFileCreator>
|
||||
implements ScriptFileCreator {
|
||||
private createdFilePath = `[${ScriptFileCreatorStub.name}]scriptFilePath`;
|
||||
|
||||
public withCreatedFilePath(path: string): this {
|
||||
this.createdFilePath = path;
|
||||
return this;
|
||||
}
|
||||
|
||||
public createScriptFile(contents: string): Promise<string> {
|
||||
this.registerMethodCall({
|
||||
methodName: 'createScriptFile',
|
||||
args: [contents],
|
||||
});
|
||||
return Promise.resolve(this.createdFilePath);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
OperatingSystemOps,
|
||||
LocationOps,
|
||||
SystemOperations,
|
||||
} from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
} from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { CommandOpsStub } from './CommandOpsStub';
|
||||
import { FileSystemOpsStub } from './FileSystemOpsStub';
|
||||
import { LocationOpsStub } from './LocationOpsStub';
|
||||
|
||||
@@ -4,16 +4,13 @@ import { VITE_USER_DEFINED_ENVIRONMENT_KEYS } from './src/infrastructure/Environ
|
||||
import tsconfigJson from './tsconfig.json' assert { type: 'json' };
|
||||
import packageJson from './package.json' assert { type: 'json' };
|
||||
|
||||
export function getAliasesFromTsConfig(): Record<string, string> {
|
||||
const { paths } = tsconfigJson.compilerOptions;
|
||||
return Object.keys(paths).reduce((aliases, pathName) => {
|
||||
const pathFolder = paths[pathName][0];
|
||||
const aliasFolder = pathFolder.substring(0, pathFolder.length - 1); // trim * from end
|
||||
const aliasName = pathName.substring(0, pathName.length - 2); // trim /* from end
|
||||
const aliasPath = resolve(getSelfDirectoryAbsolutePath(), aliasFolder);
|
||||
aliases[aliasName] = aliasPath;
|
||||
return aliases;
|
||||
}, {});
|
||||
type ViteAliasDefinitions = Record<string, string>;
|
||||
|
||||
export function getAliases(): ViteAliasDefinitions {
|
||||
return {
|
||||
...getPathAliasesFromTsConfig(),
|
||||
...getElectronProcessSpecificModuleAliases(),
|
||||
};
|
||||
}
|
||||
|
||||
export function getSelfDirectoryAbsolutePath() {
|
||||
@@ -28,7 +25,9 @@ type ViteEnvironmentKeyValues = {
|
||||
]: string
|
||||
};
|
||||
|
||||
export function getClientEnvironmentVariables(): Record<string, string> {
|
||||
type ViteGlobalVariableReplacementDefinitions = Record<string, string>;
|
||||
|
||||
export function getClientEnvironmentVariables(): ViteGlobalVariableReplacementDefinitions {
|
||||
const environmentVariables: ViteEnvironmentKeyValues = {
|
||||
[VITE_USER_DEFINED_ENVIRONMENT_KEYS.NAME]: packageJson.name,
|
||||
[VITE_USER_DEFINED_ENVIRONMENT_KEYS.VERSION]: packageJson.version,
|
||||
@@ -37,8 +36,33 @@ export function getClientEnvironmentVariables(): Record<string, string> {
|
||||
[VITE_USER_DEFINED_ENVIRONMENT_KEYS.SLOGAN]: packageJson.slogan,
|
||||
};
|
||||
return Object.entries(environmentVariables).reduce((acc, [key, value]) => {
|
||||
const newKey = `import.meta.env.${key}`;
|
||||
const newValue = JSON.stringify(value);
|
||||
return { ...acc, [newKey]: newValue };
|
||||
const formattedEnvVariableKey = `import.meta.env.${key}`;
|
||||
const jsonEncodedEnvVariableValue = JSON.stringify(value);
|
||||
return { ...acc, [formattedEnvVariableKey]: jsonEncodedEnvVariableValue };
|
||||
}, {});
|
||||
}
|
||||
|
||||
function getPathAliasesFromTsConfig(): ViteAliasDefinitions {
|
||||
const { paths } = tsconfigJson.compilerOptions;
|
||||
return Object.keys(paths).reduce((aliases, pathName) => {
|
||||
const pathFolder = paths[pathName][0];
|
||||
const aliasFolder = pathFolder.substring(0, pathFolder.length - 1); // trim * from end
|
||||
const aliasName = pathName.substring(0, pathName.length - 2); // trim /* from end
|
||||
const aliasPath = resolve(getSelfDirectoryAbsolutePath(), aliasFolder);
|
||||
aliases[aliasName] = aliasPath;
|
||||
return aliases;
|
||||
}, {});
|
||||
}
|
||||
|
||||
function getElectronProcessSpecificModuleAliases(): ViteAliasDefinitions {
|
||||
// Workaround for scoped Electron module imports due to https://github.com/alex8088/electron-vite/issues/372
|
||||
const electronProcessScopedModuleAliases = [
|
||||
'electron/main',
|
||||
'electron/renderer',
|
||||
'electron/common',
|
||||
] as const;
|
||||
return electronProcessScopedModuleAliases.reduce((aliases, alias) => {
|
||||
aliases[alias] = 'electron';
|
||||
return aliases;
|
||||
}, {});
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import vue from '@vitejs/plugin-vue';
|
||||
import legacy from '@vitejs/plugin-legacy';
|
||||
import ViteYaml from '@modyfi/vite-plugin-yaml';
|
||||
import distDirs from './dist-dirs.json' assert { type: 'json' };
|
||||
import { getAliasesFromTsConfig, getClientEnvironmentVariables, getSelfDirectoryAbsolutePath } from './vite-config-helper';
|
||||
import { getAliases, getClientEnvironmentVariables, getSelfDirectoryAbsolutePath } from './vite-config-helper';
|
||||
|
||||
const WEB_DIRECTORY = resolve(getSelfDirectoryAbsolutePath(), 'src/presentation');
|
||||
const TEST_INITIALIZATION_FILE = resolve(getSelfDirectoryAbsolutePath(), 'tests/shared/bootstrap/setup.ts');
|
||||
@@ -33,7 +33,7 @@ export function createVueConfig(options?: {
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
...getAliasesFromTsConfig(),
|
||||
...getAliases(),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
@@ -43,7 +43,7 @@ export function createVueConfig(options?: {
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
alias: {
|
||||
...getAliasesFromTsConfig(),
|
||||
...getAliases(),
|
||||
},
|
||||
setupFiles: [
|
||||
TEST_INITIALIZATION_FILE,
|
||||
|
||||
Reference in New Issue
Block a user