@zenflux/core 0.1.11 → 0.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/zenflux-core.cjs +5 -5
- package/dist/zenflux-core.mjs +5 -5
- package/package.json +3 -4
- package/src/bases/controller-base.ts +0 -96
- package/src/bases/index.ts +0 -6
- package/src/bases/initialize-base.ts +0 -32
- package/src/bases/object-base.ts +0 -55
- package/src/clients/http.ts +0 -152
- package/src/command-bases/command-base.ts +0 -82
- package/src/command-bases/command-internal.ts +0 -11
- package/src/command-bases/command-public.ts +0 -12
- package/src/command-bases/command-restful.ts +0 -55
- package/src/command-bases/index.ts +0 -8
- package/src/errors/command-already-registered.ts +0 -13
- package/src/errors/command-not-found.ts +0 -12
- package/src/errors/controller-already-registered.ts +0 -13
- package/src/errors/controller-already-set.ts +0 -13
- package/src/errors/error-with-metadata.ts +0 -14
- package/src/errors/force-method-implementation.ts +0 -15
- package/src/errors/index-public.ts +0 -1
- package/src/errors/index.ts +0 -10
- package/src/exports-index.ts +0 -13
- package/src/exports.ts +0 -58
- package/src/index.ts +0 -18
- package/src/interfaces/commands.ts +0 -17
- package/src/interfaces/config.ts +0 -23
- package/src/interfaces/index.ts +0 -8
- package/src/interfaces/logger.ts +0 -19
- package/src/interfaces/restful.ts +0 -23
- package/src/managers/commands.ts +0 -268
- package/src/managers/controllers.ts +0 -40
- package/src/managers/export.ts +0 -30
- package/src/managers/index.ts +0 -8
- package/src/managers/internal.ts +0 -11
- package/src/managers/restful.ts +0 -117
- package/src/modules/debugger.ts +0 -89
- package/src/modules/event-bus/event-bus.ts +0 -204
- package/src/modules/logger/config.ts +0 -44
- package/src/modules/logger/implementation.ts +0 -287
- package/src/modules/logger/index.ts +0 -2
- package/src/modules/logger/logger-browser-infra.ts +0 -344
- package/src/modules/logger/types/picocolors.d.ts +0 -15
- package/src/modules/logger/utils/index.ts +0 -3
- package/src/modules/logger/utils/object.ts +0 -19
- package/src/modules/logger/utils/rgb.ts +0 -34
- package/src/modules/mcp-server/mcp-server.ts +0 -139
- package/src/modules/mcp-server/mcp-service.ts +0 -80
- package/src/modules/service/service-base.ts +0 -55
- package/src/modules/service/service-locator.ts +0 -205
- package/src/modules/service/service-with-dependencies-base.ts +0 -51
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Function hexColorDelta() : Return color difference in ratio decimal point.
|
|
3
|
-
*
|
|
4
|
-
* @copyright http://jsfiddle.net/96sME/
|
|
5
|
-
*/
|
|
6
|
-
export const getHexColorDelta = function ( hex1: string, hex2: string ): number {
|
|
7
|
-
hex1 = hex1.replace( "#", "" );
|
|
8
|
-
hex2 = hex2.replace( "#", "" );
|
|
9
|
-
|
|
10
|
-
// Get red/green/blue int values of hex1
|
|
11
|
-
const r1 = parseInt( hex1.substring( 0, 2 ), 16 );
|
|
12
|
-
const g1 = parseInt( hex1.substring( 2, 4 ), 16 );
|
|
13
|
-
const b1 = parseInt( hex1.substring( 4, 6 ), 16 );
|
|
14
|
-
|
|
15
|
-
// Get red/green/blue int values of hex2
|
|
16
|
-
const r2 = parseInt( hex2.substring( 0, 2 ), 16 );
|
|
17
|
-
const g2 = parseInt( hex2.substring( 2, 4 ), 16 );
|
|
18
|
-
const b2 = parseInt( hex2.substring( 4, 6 ), 16 );
|
|
19
|
-
|
|
20
|
-
// Calculate differences between reds, greens and blues
|
|
21
|
-
let r = 255 - Math.abs( r1 - r2 );
|
|
22
|
-
let g = 255 - Math.abs( g1 - g2 );
|
|
23
|
-
let b = 255 - Math.abs( b1 - b2 );
|
|
24
|
-
|
|
25
|
-
// Limit differences between 0 and 1
|
|
26
|
-
|
|
27
|
-
r /= 255;
|
|
28
|
-
g /= 255;
|
|
29
|
-
b /= 255;
|
|
30
|
-
|
|
31
|
-
// 0 means opposite colors, 1 means same colors
|
|
32
|
-
return ( r + g + b ) / 3;
|
|
33
|
-
};
|
|
34
|
-
|
|
@@ -1,139 +0,0 @@
|
|
|
1
|
-
import { FastMCP } from "fastmcp";
|
|
2
|
-
import { z } from "zod";
|
|
3
|
-
|
|
4
|
-
import { ObjectBase } from "../../bases";
|
|
5
|
-
|
|
6
|
-
// Keep logs in memory (simple approach)
|
|
7
|
-
const MAX_LOGS = 5000; // Define a maximum number of logs to store
|
|
8
|
-
const logs: any[] = [];
|
|
9
|
-
|
|
10
|
-
export class McpServer extends ObjectBase {
|
|
11
|
-
private server: FastMCP;
|
|
12
|
-
|
|
13
|
-
public static getName(): string {
|
|
14
|
-
return "ZenFlux/Core/Modules/McpServer";
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
public constructor() {
|
|
18
|
-
super();
|
|
19
|
-
|
|
20
|
-
this.server = new FastMCP( {
|
|
21
|
-
name: "ZenfluxBackendLogger",
|
|
22
|
-
version: "0.1.0",
|
|
23
|
-
} );
|
|
24
|
-
|
|
25
|
-
this.defineMcpTools();
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
private defineMcpTools(): void {
|
|
29
|
-
// Define the getRecentLogs tool using the fastmcp API
|
|
30
|
-
this.server.addTool( {
|
|
31
|
-
name: "getRecentLogs",
|
|
32
|
-
description: "Retrieves the most recent logs received by the MCP server, optionally filtered by time range.",
|
|
33
|
-
parameters: z.object( {
|
|
34
|
-
limit: z.number().optional().default( 50 ).describe( "Maximum number of logs to return" ),
|
|
35
|
-
startTime: z.number().optional().describe( "Optional start timestamp (ms) to filter logs after" ),
|
|
36
|
-
endTime: z.number().optional().describe( "Optional end timestamp (ms) to filter logs before" ),
|
|
37
|
-
} ),
|
|
38
|
-
execute: async( args ) => {
|
|
39
|
-
const { limit, startTime, endTime } = args;
|
|
40
|
-
|
|
41
|
-
// Get initial slice based on limit (most recent)
|
|
42
|
-
let recentLogs = logs.slice( -limit );
|
|
43
|
-
|
|
44
|
-
// Apply time filters if provided
|
|
45
|
-
if ( startTime ) {
|
|
46
|
-
recentLogs = recentLogs.filter( log => log.timestamp >= startTime );
|
|
47
|
-
}
|
|
48
|
-
if ( endTime ) {
|
|
49
|
-
recentLogs = recentLogs.filter( log => log.timestamp <= endTime );
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
return JSON.stringify( recentLogs, null, 2 );
|
|
53
|
-
},
|
|
54
|
-
} );
|
|
55
|
-
|
|
56
|
-
// Define the getLogsInfo tool
|
|
57
|
-
this.server.addTool( {
|
|
58
|
-
name: "getLogsInfo",
|
|
59
|
-
description: "Provides information about stored logs, including count, and first/last timestamps.",
|
|
60
|
-
parameters: z.object( {} ), // No parameters
|
|
61
|
-
execute: async() => {
|
|
62
|
-
const logCount = logs.length;
|
|
63
|
-
const firstTimestamp = logCount > 0 ? logs[ 0 ]?.timestamp : null;
|
|
64
|
-
const lastTimestamp = logCount > 0 ? logs[ logCount - 1 ]?.timestamp : null;
|
|
65
|
-
|
|
66
|
-
const info = {
|
|
67
|
-
logCount,
|
|
68
|
-
firstTimestamp,
|
|
69
|
-
lastTimestamp
|
|
70
|
-
};
|
|
71
|
-
return JSON.stringify( info, null, 2 );
|
|
72
|
-
},
|
|
73
|
-
} );
|
|
74
|
-
|
|
75
|
-
// Define the getLogsRange tool
|
|
76
|
-
this.server.addTool( {
|
|
77
|
-
name: "getLogsRange",
|
|
78
|
-
description: "Retrieves logs within a specific time range.",
|
|
79
|
-
parameters: z.object( {
|
|
80
|
-
startTime: z.number().describe( "Required start timestamp (ms) to filter logs after" ),
|
|
81
|
-
endTime: z.number().describe( "Required end timestamp (ms) to filter logs before" ),
|
|
82
|
-
} ),
|
|
83
|
-
execute: async( args ) => {
|
|
84
|
-
const { startTime, endTime } = args;
|
|
85
|
-
|
|
86
|
-
// Validate timestamps
|
|
87
|
-
if ( startTime >= endTime ) {
|
|
88
|
-
throw new Error( "Start time must be before end time." );
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
const filteredLogs = logs.filter( log =>
|
|
92
|
-
log.timestamp >= startTime && log.timestamp <= endTime
|
|
93
|
-
);
|
|
94
|
-
|
|
95
|
-
// Consider adding a safety limit here if the range could be huge
|
|
96
|
-
// const MAX_RANGE_RESULTS = 1000;
|
|
97
|
-
// if (filteredLogs.length > MAX_RANGE_RESULTS) {
|
|
98
|
-
// throw new Error(`Log range too large (${filteredLogs.length} logs). Maximum allowed: ${MAX_RANGE_RESULTS}`);
|
|
99
|
-
// }
|
|
100
|
-
|
|
101
|
-
return JSON.stringify( filteredLogs, null, 2 );
|
|
102
|
-
},
|
|
103
|
-
} );
|
|
104
|
-
|
|
105
|
-
console.log( "MCP Tools defined: getRecentLogs, getLogsInfo, getLogsRange" );
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// Start the fastmcp server
|
|
109
|
-
public async start( port: number = 3000, host: string = "0.0.0.0" ): Promise<void> {
|
|
110
|
-
try {
|
|
111
|
-
// Removed server name from log as config access is different
|
|
112
|
-
console.log( "Attempting to start fastmcp server..." );
|
|
113
|
-
await this.server.start( {
|
|
114
|
-
transportType: "httpStream", // Explicitly use SSE
|
|
115
|
-
httpStream: {
|
|
116
|
-
port,
|
|
117
|
-
host,
|
|
118
|
-
endpoint: "/mcp" // Standard MCP endpoint
|
|
119
|
-
}
|
|
120
|
-
} );
|
|
121
|
-
} catch ( err ) {
|
|
122
|
-
console.error( "Error starting fastmcp server:", err );
|
|
123
|
-
process.exit( 1 );
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// Stop the fastmcp server
|
|
128
|
-
public async stop(): Promise<void> {
|
|
129
|
-
console.log( "Stopping fastmcp server..." );
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
// Method to add a log entry, now with capping
|
|
133
|
-
public addLog( logEntry: any ): void {
|
|
134
|
-
if ( logs.length >= MAX_LOGS ) {
|
|
135
|
-
logs.shift(); // Remove the oldest log if the limit is reached
|
|
136
|
-
}
|
|
137
|
-
logs.push( logEntry );
|
|
138
|
-
}
|
|
139
|
-
}
|
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
import { McpServer } from "./mcp-server";
|
|
2
|
-
|
|
3
|
-
import { EventBus } from "../event-bus/event-bus";
|
|
4
|
-
|
|
5
|
-
import { ServiceBase } from "../service/service-base";
|
|
6
|
-
|
|
7
|
-
// TODO: Get port/host from configuration/environment variables
|
|
8
|
-
const MCP_PORT = 3090;
|
|
9
|
-
const MCP_HOST = "0.0.0.0";
|
|
10
|
-
|
|
11
|
-
export class MCPService extends ServiceBase {
|
|
12
|
-
private static mcpServer: McpServer;
|
|
13
|
-
|
|
14
|
-
public static getName(): string {
|
|
15
|
-
return "ZenFlux/Core/Modules/MCPService";
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
public constructor() {
|
|
19
|
-
super();
|
|
20
|
-
|
|
21
|
-
// Initialization logic is handled in the initialize method by ServiceBase
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
protected async initialize(): Promise<void> {
|
|
25
|
-
this.logger.log( this.initialize, "Initializing MCP Service..." );
|
|
26
|
-
|
|
27
|
-
try {
|
|
28
|
-
MCPService.mcpServer = new McpServer();
|
|
29
|
-
|
|
30
|
-
// Start the MCP server (Fastify instance)
|
|
31
|
-
// Consider adding error handling or status checking
|
|
32
|
-
await MCPService.mcpServer.start( MCP_PORT, MCP_HOST );
|
|
33
|
-
|
|
34
|
-
EventBus.$.on( "ZenFlux/Core/Modules/Logger", "outputInternal", this.onLoggerOutput.bind( this ) );
|
|
35
|
-
|
|
36
|
-
this.logger.info( this.initialize, `MCP Server started on http://${ MCP_HOST }:${ MCP_PORT }` );
|
|
37
|
-
} catch ( error ) {
|
|
38
|
-
this.logger.error( this.initialize, "Failed to start MCP Server", error );
|
|
39
|
-
// Rethrow or handle appropriately - ServiceBase might catch this
|
|
40
|
-
throw error;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Optional: Add a method to explicitly stop the server if needed.
|
|
46
|
-
* ServiceBase doesn't seem to have a standard shutdown hook, so manual call might be necessary.
|
|
47
|
-
*/
|
|
48
|
-
public async stopServer(): Promise<void> {
|
|
49
|
-
if ( MCPService.mcpServer ) {
|
|
50
|
-
this.logger.log( this.stopServer, "Stopping MCP Server..." );
|
|
51
|
-
await MCPService.mcpServer.stop();
|
|
52
|
-
this.logger.info( this.stopServer, "MCP Server stopped." );
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// You can add methods here to interact with McpServer if needed,
|
|
57
|
-
// e.g., retrieving logs or status, although tools will likely handle log retrieval.
|
|
58
|
-
private onLoggerOutput( prefix: string, timeDiff: string, source: string, messagePrefix: string, message: string, params: any[] ) {
|
|
59
|
-
// Create a log entry with all the relevant information
|
|
60
|
-
const logEntry = {
|
|
61
|
-
timestamp: new Date().getTime(),
|
|
62
|
-
prefix,
|
|
63
|
-
timeDiff,
|
|
64
|
-
source,
|
|
65
|
-
messagePrefix,
|
|
66
|
-
message,
|
|
67
|
-
params: params && params.length ? params : [],
|
|
68
|
-
formatted: `${ prefix }[+${ timeDiff }ms][${ source }]${ messagePrefix }: ${ message }`
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
if ( MCPService.mcpServer ) {
|
|
72
|
-
// Call the addLog method directly on the static McpServer instance
|
|
73
|
-
try {
|
|
74
|
-
MCPService.mcpServer.addLog( logEntry );
|
|
75
|
-
} catch ( error ) {
|
|
76
|
-
console.error( "MCPService.onLoggerOutput: Failed to add log via addLog method:", error );
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
}
|
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import { ObjectBase } from "../../bases/object-base";
|
|
2
|
-
|
|
3
|
-
import { Logger } from "../logger";
|
|
4
|
-
|
|
5
|
-
export abstract class ServiceBase extends ObjectBase {
|
|
6
|
-
protected logger: Logger;
|
|
7
|
-
|
|
8
|
-
private readonly initialization: {
|
|
9
|
-
promise: Promise<void>;
|
|
10
|
-
state: "pending" | "resolved" | "rejected";
|
|
11
|
-
reason?: Error;
|
|
12
|
-
};
|
|
13
|
-
|
|
14
|
-
public static getName(): string {
|
|
15
|
-
return "ZenFlux/Core/Modules/ServiceBase";
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
19
|
-
public constructor( ...args: any[] ) {
|
|
20
|
-
super();
|
|
21
|
-
|
|
22
|
-
this.logger = new Logger( this );
|
|
23
|
-
|
|
24
|
-
if ( this.initialize ) {
|
|
25
|
-
this.initialization = {
|
|
26
|
-
promise: this.initialize(),
|
|
27
|
-
state: "pending"
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
this.initialization.promise
|
|
31
|
-
.then( () => ( this.initialization.state = "resolved" ) )
|
|
32
|
-
.catch( ( reason ) => {
|
|
33
|
-
this.initialization.state = "rejected";
|
|
34
|
-
this.initialization.reason = reason;
|
|
35
|
-
} );
|
|
36
|
-
|
|
37
|
-
return;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
this.initialization = {
|
|
41
|
-
promise: Promise.resolve(),
|
|
42
|
-
state: "resolved"
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
protected async initialize?(): Promise<void>;
|
|
47
|
-
|
|
48
|
-
public isWithDependencies() {
|
|
49
|
-
return false;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
public getInitialization() {
|
|
53
|
-
return this.initialization;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
import EventEmitter from "events";
|
|
2
|
-
|
|
3
|
-
import { InitializeBase } from "../../bases/initialize-base";
|
|
4
|
-
|
|
5
|
-
import { ErrorWithMetadata } from "../../errors";
|
|
6
|
-
|
|
7
|
-
import type { ServiceWithDependenciesBase } from "./service-with-dependencies-base";
|
|
8
|
-
|
|
9
|
-
import type { ServiceBase } from "./service-base";
|
|
10
|
-
|
|
11
|
-
// We want is `ServiceLocator` to persist across HMR reloads.
|
|
12
|
-
declare global {
|
|
13
|
-
var __zenflux_base_service_locator__: ServiceLocator | undefined;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export class ServiceLocator extends InitializeBase {
|
|
17
|
-
protected static instance: ServiceLocator | null = null;
|
|
18
|
-
|
|
19
|
-
private emitter: EventEmitter = new EventEmitter();
|
|
20
|
-
|
|
21
|
-
private services: Map<string, ServiceBase> = new Map();
|
|
22
|
-
|
|
23
|
-
private initializing: Set<string> = new Set();
|
|
24
|
-
|
|
25
|
-
public static getName() {
|
|
26
|
-
return "Modules/ServiceLocator";
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
public static get $() {
|
|
30
|
-
if ( !global.__zenflux_base_service_locator__ ) {
|
|
31
|
-
global.__zenflux_base_service_locator__ = new this();
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
return global.__zenflux_base_service_locator__;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
public register<T extends ServiceBase>( service: new ( ...args: any[] ) => T, ...args: any[] ) {
|
|
38
|
-
const serviceAsClass = service as unknown as ServiceBase;
|
|
39
|
-
|
|
40
|
-
if ( this.services.has( serviceAsClass.getName() ) ) {
|
|
41
|
-
throw new Error( `Service '${ serviceAsClass.getName() }' is already registered` );
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const serviceInstance = new service( ...args );
|
|
45
|
-
|
|
46
|
-
this.services.set( serviceInstance.getName(), serviceInstance );
|
|
47
|
-
|
|
48
|
-
if ( serviceInstance.isWithDependencies() ) {
|
|
49
|
-
this.validateCircularDependencies( serviceInstance as unknown as ServiceWithDependenciesBase<any> );
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
this.emitter.emit( "service-registered", serviceInstance.getName() );
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
public unregister( serviceName: string ) {
|
|
56
|
-
return this.services.delete( serviceName );
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
public get<T extends ServiceBase>( serviceName: string, options = { silent: false } ): T {
|
|
60
|
-
if ( !options.silent && !this.services.has( serviceName ) ) {
|
|
61
|
-
throw new Error( `Service '${ serviceName }' is not registered` );
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
return this.services.get( serviceName ) as T;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
public async waitFor<T extends ServiceBase>(
|
|
68
|
-
serviceName: string,
|
|
69
|
-
options: {
|
|
70
|
-
timeout?: number;
|
|
71
|
-
metadata?: any;
|
|
72
|
-
internal?: boolean;
|
|
73
|
-
silent?: boolean;
|
|
74
|
-
} = {}
|
|
75
|
-
): Promise<T> {
|
|
76
|
-
options = {
|
|
77
|
-
silent: false,
|
|
78
|
-
timeout: 0,
|
|
79
|
-
...options
|
|
80
|
-
};
|
|
81
|
-
|
|
82
|
-
const service = this.get( serviceName, {
|
|
83
|
-
silent: !!options.silent
|
|
84
|
-
} );
|
|
85
|
-
|
|
86
|
-
if ( service && service.getInitialization().state === "resolved" ) {
|
|
87
|
-
return service as T;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
this.initializing.add( serviceName );
|
|
91
|
-
|
|
92
|
-
const waitForService = this.createServicePromise<T>( serviceName ),
|
|
93
|
-
waitForTimeout = this.createTimeoutPromise<T>( serviceName, options.timeout, options.metadata );
|
|
94
|
-
|
|
95
|
-
try {
|
|
96
|
-
return await Promise.race( [ waitForService, waitForTimeout ] );
|
|
97
|
-
} finally {
|
|
98
|
-
this.initializing.delete( serviceName );
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
public async waitForAll(
|
|
103
|
-
options: {
|
|
104
|
-
timeout?: number;
|
|
105
|
-
metadata?: any;
|
|
106
|
-
internal?: boolean;
|
|
107
|
-
} = {}
|
|
108
|
-
): Promise<void> {
|
|
109
|
-
options = {
|
|
110
|
-
timeout: 0,
|
|
111
|
-
...options
|
|
112
|
-
};
|
|
113
|
-
|
|
114
|
-
const waitForServices = Array.from( this.services.keys() ).map( ( serviceName ) =>
|
|
115
|
-
this.waitFor( serviceName, options )
|
|
116
|
-
);
|
|
117
|
-
|
|
118
|
-
await Promise.all( waitForServices );
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
private createServicePromise<T extends ServiceBase>( serviceName: string ): Promise<T> {
|
|
122
|
-
return new Promise<T>( ( resolve, reject ) => {
|
|
123
|
-
const listener = ( registeredServiceName: string ) => {
|
|
124
|
-
if ( registeredServiceName === serviceName ) {
|
|
125
|
-
this.emitter.off( "service-registered", listener );
|
|
126
|
-
const service = this.get<T>( serviceName ),
|
|
127
|
-
initialization = service.getInitialization();
|
|
128
|
-
|
|
129
|
-
if ( initialization.state === "resolved" ) {
|
|
130
|
-
resolve( service );
|
|
131
|
-
return;
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
if ( initialization.state === "rejected" ) {
|
|
135
|
-
reject( initialization.reason );
|
|
136
|
-
return;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
initialization.promise.then( () => resolve( service ) ).catch( reject );
|
|
140
|
-
}
|
|
141
|
-
};
|
|
142
|
-
|
|
143
|
-
this.services.has( serviceName ) ? listener( serviceName ) : this.emitter.on( "service-registered", listener );
|
|
144
|
-
} );
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
private createTimeoutPromise<T extends ServiceBase>(
|
|
148
|
-
serviceName: string,
|
|
149
|
-
timeout: number = 0,
|
|
150
|
-
metadata: any
|
|
151
|
-
): Promise<T> {
|
|
152
|
-
return new Promise<T>( ( _, reject ) =>
|
|
153
|
-
setTimeout( () => {
|
|
154
|
-
const error = new ErrorWithMetadata( `Service '${ serviceName }' initialization timed out`, metadata );
|
|
155
|
-
|
|
156
|
-
reject( error );
|
|
157
|
-
}, timeout )
|
|
158
|
-
);
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
private validateCircularDependencies( service: ServiceWithDependenciesBase<any> ) {
|
|
162
|
-
const visited = new Set<string>(),
|
|
163
|
-
stack = new Set<string>();
|
|
164
|
-
|
|
165
|
-
const serviceName = service.getName();
|
|
166
|
-
|
|
167
|
-
const hasCircularDependency = this.performDepthFirstSearch( serviceName, stack, visited );
|
|
168
|
-
|
|
169
|
-
if ( hasCircularDependency ) {
|
|
170
|
-
throw new Error( `Circular dependency detected stack: ${ Array.from( stack ).join( " -> " ) }
|
|
171
|
-
-> [current] -> ${ serviceName }` );
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
private performDepthFirstSearch( currentServiceName: string, stack: Set<string>, visited: Set<string> ): boolean {
|
|
176
|
-
// If the service has been visited before, it means a circular dependency exists.
|
|
177
|
-
if ( visited.has( currentServiceName ) ) {
|
|
178
|
-
// If the service is already on the stack, then it is definitely a circular dependency.
|
|
179
|
-
return stack.has( currentServiceName );
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
visited.add( currentServiceName );
|
|
183
|
-
stack.add( currentServiceName );
|
|
184
|
-
|
|
185
|
-
const service = this.get( currentServiceName, { silent: true } ),
|
|
186
|
-
dependencies = service?.isWithDependencies()
|
|
187
|
-
? this.getDependencies( service as unknown as ServiceWithDependenciesBase<any> )
|
|
188
|
-
: [];
|
|
189
|
-
|
|
190
|
-
// The recursive call will go down the dependency tree to search for circular dependencies.
|
|
191
|
-
for ( const dependency of dependencies ) {
|
|
192
|
-
if ( this.performDepthFirstSearch( dependency, stack, visited ) ) {
|
|
193
|
-
return true;
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
stack.delete( currentServiceName );
|
|
198
|
-
|
|
199
|
-
return false;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
private getDependencies( service: ServiceWithDependenciesBase<any> ): string[] {
|
|
203
|
-
return Object.values( service.getDependencies() );
|
|
204
|
-
}
|
|
205
|
-
}
|
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
import { ServiceLocator } from "./service-locator";
|
|
2
|
-
import { ServiceBase } from "./service-base";
|
|
3
|
-
|
|
4
|
-
type TServicesNonEmpty<T> = keyof T extends never ? "Error: Services are required" : T;
|
|
5
|
-
|
|
6
|
-
type TServiceName = string;
|
|
7
|
-
|
|
8
|
-
type TServiceNameDependencies<T> = {
|
|
9
|
-
[K in keyof T]: TServiceName;
|
|
10
|
-
};
|
|
11
|
-
|
|
12
|
-
export abstract class ServiceWithDependenciesBase<D extends { [key: string]: ServiceBase }> extends ServiceBase {
|
|
13
|
-
protected services = {} as Required<D>;
|
|
14
|
-
|
|
15
|
-
public static getName(): string {
|
|
16
|
-
return "Modules/ServiceBaseWithDependencies";
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
public abstract getDependencies(): TServicesNonEmpty<TServiceNameDependencies<D>>;
|
|
20
|
-
|
|
21
|
-
protected async initialize(): Promise<void> {
|
|
22
|
-
await super.initialize?.();
|
|
23
|
-
|
|
24
|
-
// Wait for all dependencies to be initialized
|
|
25
|
-
const dependencies = Object.entries( this.getDependencies() ).map( async( [ alias, serviceName ] ) => {
|
|
26
|
-
return ServiceLocator.$.waitFor( serviceName, {
|
|
27
|
-
internal: true,
|
|
28
|
-
metadata: {
|
|
29
|
-
source: this,
|
|
30
|
-
fulfilled: this.services
|
|
31
|
-
}
|
|
32
|
-
} ).then( ( service ) => {
|
|
33
|
-
( this.services as any )[ alias ] = service;
|
|
34
|
-
|
|
35
|
-
return service;
|
|
36
|
-
} );
|
|
37
|
-
} );
|
|
38
|
-
|
|
39
|
-
await Promise.all( dependencies );
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
public isWithDependencies() {
|
|
43
|
-
// In order to avoid circular dependencies
|
|
44
|
-
// ! there are better ways to do this, but that just fine for now.
|
|
45
|
-
return true;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
public getServices() {
|
|
49
|
-
return this.services;
|
|
50
|
-
}
|
|
51
|
-
}
|