@vedmalex/statemachine 1.0.0-beta.1
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/LICENSE +21 -0
- package/README.md +75 -0
- package/dist/index.cjs +3989 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +3943 -0
- package/dist/index.js.map +1 -0
- package/package.json +77 -0
- package/types/adapters.d.ts +30 -0
- package/types/config_validator.d.ts +76 -0
- package/types/error_handling.d.ts +124 -0
- package/types/index.d.ts +77 -0
- package/types/lite.d.ts +6 -0
- package/types/logger.d.ts +74 -0
- package/types/monitoring.d.ts +239 -0
- package/types/presets.d.ts +27 -0
- package/types/scheduler.d.ts +65 -0
- package/types/security.d.ts +145 -0
- package/types/state_machine.d.ts +227 -0
- package/types/types.d.ts +250 -0
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import type { ErrorContext, IMonitor, MonitorMetricsSnapshot, TransitionContext } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Performance metrics interface
|
|
4
|
+
*/
|
|
5
|
+
interface PerformanceMetrics {
|
|
6
|
+
transitionTime: number;
|
|
7
|
+
stateChangeCount: number;
|
|
8
|
+
errorCount: number;
|
|
9
|
+
timestamp: number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Health check status
|
|
13
|
+
*/
|
|
14
|
+
export declare const HealthStatus: {
|
|
15
|
+
readonly HEALTHY: "healthy";
|
|
16
|
+
readonly WARNING: "warning";
|
|
17
|
+
readonly CRITICAL: "critical";
|
|
18
|
+
readonly UNKNOWN: "unknown";
|
|
19
|
+
};
|
|
20
|
+
export type HealthStatus = (typeof HealthStatus)[keyof typeof HealthStatus];
|
|
21
|
+
/**
|
|
22
|
+
* Health check result
|
|
23
|
+
*/
|
|
24
|
+
interface HealthCheckResult {
|
|
25
|
+
status: HealthStatus;
|
|
26
|
+
message: string;
|
|
27
|
+
timestamp: number;
|
|
28
|
+
metrics?: Record<string, any>;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Monitoring configuration
|
|
32
|
+
*/
|
|
33
|
+
export interface MonitoringConfig {
|
|
34
|
+
enabled: boolean;
|
|
35
|
+
metricsInterval: number;
|
|
36
|
+
healthCheckInterval: number;
|
|
37
|
+
maxMetricsHistory: number;
|
|
38
|
+
thresholds: {
|
|
39
|
+
transitionTimeWarning: number;
|
|
40
|
+
transitionTimeCritical: number;
|
|
41
|
+
errorRateWarning: number;
|
|
42
|
+
errorRateCritical: number;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Default monitoring configuration
|
|
47
|
+
*/
|
|
48
|
+
export declare const DEFAULT_MONITORING_CONFIG: MonitoringConfig;
|
|
49
|
+
/**
|
|
50
|
+
* Metrics collector for StateMachine performance monitoring
|
|
51
|
+
*/
|
|
52
|
+
export declare class MetricsCollector {
|
|
53
|
+
private metrics;
|
|
54
|
+
private config;
|
|
55
|
+
private startTime;
|
|
56
|
+
private transitionCount;
|
|
57
|
+
private errorCount;
|
|
58
|
+
constructor(config?: Partial<MonitoringConfig>);
|
|
59
|
+
/**
|
|
60
|
+
* Record a state transition
|
|
61
|
+
*/
|
|
62
|
+
recordTransition(transitionTime: number): void;
|
|
63
|
+
/**
|
|
64
|
+
* Record an error
|
|
65
|
+
*/
|
|
66
|
+
recordError(): void;
|
|
67
|
+
/**
|
|
68
|
+
* Get current metrics summary
|
|
69
|
+
*/
|
|
70
|
+
getMetricsSummary(): {
|
|
71
|
+
totalTransitions: number;
|
|
72
|
+
totalErrors: number;
|
|
73
|
+
averageTransitionTime: number;
|
|
74
|
+
errorRate: number;
|
|
75
|
+
uptime: number;
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Get metrics history
|
|
79
|
+
*/
|
|
80
|
+
getMetricsHistory(timeRange?: number): PerformanceMetrics[];
|
|
81
|
+
/**
|
|
82
|
+
* Clear metrics history
|
|
83
|
+
*/
|
|
84
|
+
clearMetrics(): void;
|
|
85
|
+
/**
|
|
86
|
+
* Get recent metrics within time range
|
|
87
|
+
*/
|
|
88
|
+
private getRecentMetrics;
|
|
89
|
+
/**
|
|
90
|
+
* Add metrics to history with size limit
|
|
91
|
+
*/
|
|
92
|
+
private addMetrics;
|
|
93
|
+
/**
|
|
94
|
+
* Log metrics if significant
|
|
95
|
+
*/
|
|
96
|
+
private logMetrics;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Performance monitor for real-time tracking
|
|
100
|
+
*/
|
|
101
|
+
export declare class PerformanceMonitor {
|
|
102
|
+
private metricsCollector;
|
|
103
|
+
private config;
|
|
104
|
+
private intervalId;
|
|
105
|
+
private isRunning;
|
|
106
|
+
constructor(metricsCollector: MetricsCollector, config?: Partial<MonitoringConfig>);
|
|
107
|
+
/**
|
|
108
|
+
* Start performance monitoring
|
|
109
|
+
*/
|
|
110
|
+
start(): void;
|
|
111
|
+
/**
|
|
112
|
+
* Stop performance monitoring
|
|
113
|
+
*/
|
|
114
|
+
stop(): void;
|
|
115
|
+
/**
|
|
116
|
+
* Get current performance status
|
|
117
|
+
*/
|
|
118
|
+
getPerformanceStatus(): {
|
|
119
|
+
status: HealthStatus;
|
|
120
|
+
summary: ReturnType<MetricsCollector['getMetricsSummary']>;
|
|
121
|
+
issues: string[];
|
|
122
|
+
};
|
|
123
|
+
/**
|
|
124
|
+
* Collect current metrics
|
|
125
|
+
*/
|
|
126
|
+
private collectMetrics;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Health checker for StateMachine instances
|
|
130
|
+
*/
|
|
131
|
+
export declare class HealthChecker {
|
|
132
|
+
private performanceMonitor;
|
|
133
|
+
private config;
|
|
134
|
+
private intervalId;
|
|
135
|
+
private isRunning;
|
|
136
|
+
private lastHealthCheck;
|
|
137
|
+
constructor(performanceMonitor: PerformanceMonitor, config?: Partial<MonitoringConfig>);
|
|
138
|
+
/**
|
|
139
|
+
* Start health checking
|
|
140
|
+
*/
|
|
141
|
+
start(): void;
|
|
142
|
+
/**
|
|
143
|
+
* Stop health checking
|
|
144
|
+
*/
|
|
145
|
+
stop(): void;
|
|
146
|
+
/**
|
|
147
|
+
* Perform immediate health check
|
|
148
|
+
*/
|
|
149
|
+
performHealthCheck(): HealthCheckResult;
|
|
150
|
+
/**
|
|
151
|
+
* Get last health check result
|
|
152
|
+
*/
|
|
153
|
+
getLastHealthCheck(): HealthCheckResult | undefined;
|
|
154
|
+
/**
|
|
155
|
+
* Generate health message based on status
|
|
156
|
+
*/
|
|
157
|
+
private generateHealthMessage;
|
|
158
|
+
/**
|
|
159
|
+
* Log health check results
|
|
160
|
+
*/
|
|
161
|
+
private logHealthCheck;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Comprehensive monitoring system
|
|
165
|
+
*/
|
|
166
|
+
export declare class StateMachineMonitor {
|
|
167
|
+
private metricsCollector;
|
|
168
|
+
private performanceMonitor;
|
|
169
|
+
private healthChecker;
|
|
170
|
+
private config;
|
|
171
|
+
constructor(config?: Partial<MonitoringConfig>);
|
|
172
|
+
/**
|
|
173
|
+
* Start all monitoring components
|
|
174
|
+
*/
|
|
175
|
+
start(): void;
|
|
176
|
+
/**
|
|
177
|
+
* Stop all monitoring components
|
|
178
|
+
*/
|
|
179
|
+
stop(): void;
|
|
180
|
+
/**
|
|
181
|
+
* Record a transition for monitoring (F-T4-TS-5 widening: added success + context params)
|
|
182
|
+
*/
|
|
183
|
+
recordTransition(transitionTime: number, success?: boolean, _context?: TransitionContext): void;
|
|
184
|
+
/**
|
|
185
|
+
* Record an error for monitoring (F-T4-TS-5 widening: added error + context params)
|
|
186
|
+
*/
|
|
187
|
+
recordError(_error?: Error, _context?: ErrorContext): void;
|
|
188
|
+
/**
|
|
189
|
+
* Record an event for monitoring (optional IMonitor extension)
|
|
190
|
+
*/
|
|
191
|
+
recordEvent(_eventName: string, _duration: number): void;
|
|
192
|
+
/**
|
|
193
|
+
* Get aggregate metrics snapshot (optional IMonitor extension)
|
|
194
|
+
*/
|
|
195
|
+
getMetrics(): MonitorMetricsSnapshot;
|
|
196
|
+
/**
|
|
197
|
+
* Get comprehensive monitoring report
|
|
198
|
+
*/
|
|
199
|
+
getMonitoringReport(): {
|
|
200
|
+
health: HealthCheckResult;
|
|
201
|
+
performance: ReturnType<PerformanceMonitor['getPerformanceStatus']>;
|
|
202
|
+
metrics: ReturnType<MetricsCollector['getMetricsSummary']>;
|
|
203
|
+
config: MonitoringConfig;
|
|
204
|
+
};
|
|
205
|
+
/**
|
|
206
|
+
* Export metrics for external monitoring systems
|
|
207
|
+
*/
|
|
208
|
+
exportMetrics(): {
|
|
209
|
+
prometheus?: string;
|
|
210
|
+
json: any;
|
|
211
|
+
};
|
|
212
|
+
/**
|
|
213
|
+
* Generate Prometheus-compatible metrics (without memory metrics)
|
|
214
|
+
*/
|
|
215
|
+
private generatePrometheusMetrics;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* @internal — default factory for StateMachine.monitor injection slot.
|
|
219
|
+
* Returns a new StateMachineMonitor instance (NOT a singleton).
|
|
220
|
+
*/
|
|
221
|
+
export declare function createDefaultMonitor(): IMonitor;
|
|
222
|
+
/**
|
|
223
|
+
* Utility functions for monitoring integration
|
|
224
|
+
*/
|
|
225
|
+
export declare const MonitoringUtils: {
|
|
226
|
+
/**
|
|
227
|
+
* Create monitoring decorator for StateMachine methods
|
|
228
|
+
*/
|
|
229
|
+
withMonitoring<T extends (...args: any[]) => any>(fn: T, monitor: StateMachineMonitor, _operationName: string): T;
|
|
230
|
+
/**
|
|
231
|
+
* Create monitoring middleware
|
|
232
|
+
*/
|
|
233
|
+
createMonitoringMiddleware(monitor: StateMachineMonitor): {
|
|
234
|
+
beforeTransition: (context: any) => void;
|
|
235
|
+
afterTransition: (context: any) => void;
|
|
236
|
+
onError: (_context: any, _error: any) => void;
|
|
237
|
+
};
|
|
238
|
+
};
|
|
239
|
+
export {};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ValidationConfig } from './config_validator';
|
|
2
|
+
import { LogLevel } from './logger';
|
|
3
|
+
import type { MonitoringConfig } from './monitoring';
|
|
4
|
+
export interface PresetConfig {
|
|
5
|
+
logger?: {
|
|
6
|
+
level: LogLevel;
|
|
7
|
+
enableStructuredLogging?: boolean;
|
|
8
|
+
};
|
|
9
|
+
monitoring?: Partial<MonitoringConfig>;
|
|
10
|
+
validation?: Partial<ValidationConfig>;
|
|
11
|
+
}
|
|
12
|
+
export declare const Presets: {
|
|
13
|
+
/**
|
|
14
|
+
* Максимальная производительность, минимум логов.
|
|
15
|
+
* Идеально для клиентской части (SPA).
|
|
16
|
+
*/
|
|
17
|
+
Frontend: PresetConfig;
|
|
18
|
+
/**
|
|
19
|
+
* Полный контроль, JSON-логи, метрики.
|
|
20
|
+
* Идеально для Node.js / Microservices.
|
|
21
|
+
*/
|
|
22
|
+
Backend: PresetConfig;
|
|
23
|
+
/**
|
|
24
|
+
* Режим отладки: все проверки включены, подробные логи.
|
|
25
|
+
*/
|
|
26
|
+
Debug: PresetConfig;
|
|
27
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { ITimerScheduler } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Тип для идентификатора таймера
|
|
4
|
+
*/
|
|
5
|
+
type TimerToken = object;
|
|
6
|
+
/**
|
|
7
|
+
* Планировщик таймеров на базе Min-Heap (Двоичная куча).
|
|
8
|
+
* Позволяет эффективно управлять тысячами таймеров, используя единый цикл проверки.
|
|
9
|
+
*/
|
|
10
|
+
export declare class TimerScheduler {
|
|
11
|
+
private heap;
|
|
12
|
+
private activeTokens;
|
|
13
|
+
private intervalId;
|
|
14
|
+
private pollingInterval;
|
|
15
|
+
constructor();
|
|
16
|
+
/**
|
|
17
|
+
* Настройка режима опроса
|
|
18
|
+
* @param interval Интервал проверки в мс. Если 0 или null - авто-тик выключается (ручной режим)
|
|
19
|
+
*/
|
|
20
|
+
setPollingInterval(interval: number | null): void;
|
|
21
|
+
/**
|
|
22
|
+
* Проверка активности планировщика
|
|
23
|
+
*/
|
|
24
|
+
isActive(): boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Запуск единого таймера
|
|
27
|
+
*/
|
|
28
|
+
start(): void;
|
|
29
|
+
/**
|
|
30
|
+
* Остановка единого таймера
|
|
31
|
+
*/
|
|
32
|
+
stop(): void;
|
|
33
|
+
/**
|
|
34
|
+
* Добавить задачу
|
|
35
|
+
* @param delay задержка в мс
|
|
36
|
+
* @param callback функция для выполнения
|
|
37
|
+
* @returns токен для отмены
|
|
38
|
+
*/
|
|
39
|
+
schedule(delay: number, callback: () => void): TimerToken;
|
|
40
|
+
/**
|
|
41
|
+
* Отменить задачу
|
|
42
|
+
* @param token токен задачи
|
|
43
|
+
*/
|
|
44
|
+
cancel(token: TimerToken): void;
|
|
45
|
+
/**
|
|
46
|
+
* Обработать очередь (вызывается таймером или вручную)
|
|
47
|
+
*/
|
|
48
|
+
process(now?: number): void;
|
|
49
|
+
/**
|
|
50
|
+
* Очистить все задачи
|
|
51
|
+
*/
|
|
52
|
+
clear(): void;
|
|
53
|
+
private insert;
|
|
54
|
+
private extractMin;
|
|
55
|
+
private bubbleUp;
|
|
56
|
+
private sinkDown;
|
|
57
|
+
private swap;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* @internal — default factory for StateMachine.scheduler injection slot.
|
|
61
|
+
* Returns a new TimerScheduler instance (NOT a singleton).
|
|
62
|
+
* Same-module placement required: TimerScheduler constructor is public within module.
|
|
63
|
+
*/
|
|
64
|
+
export declare function createDefaultScheduler(): ITimerScheduler;
|
|
65
|
+
export {};
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @deprecated Will be removed in a follow-up task. Security policy enforcement should
|
|
3
|
+
* happen at the host-application layer; this module is a source-tree marker.
|
|
4
|
+
*
|
|
5
|
+
* Post TD-T3-4 pruning, symbols from this module are not reachable from `dist/index.js` —
|
|
6
|
+
* the deprecation has no public deprecation cycle, only source-tree intent.
|
|
7
|
+
*
|
|
8
|
+
* Governance treatments (multi-treatment file, per TASK-003 CODE_REVIEW F-CR3-8):
|
|
9
|
+
* - tsconfig.json `include: ["src/**\/*"]` — typechecked under strict TS for now
|
|
10
|
+
* - vitest.config.ts `coverage.exclude` — excluded from coverage instrumentation
|
|
11
|
+
* - knip.json `ignore` — excluded from unused-export warnings
|
|
12
|
+
* - package.json `files: ["dist", "types", ...]` — NOT shipped to npm (since TASK-003 CODE_REVIEW F-CR3-1)
|
|
13
|
+
*
|
|
14
|
+
* Removal trigger: when no in-tree code references the file (currently `src/tests/security.test.ts`
|
|
15
|
+
* does), delete the file plus its test plus all four governance-list entries above.
|
|
16
|
+
*
|
|
17
|
+
* Security module for safe function serialization and validation
|
|
18
|
+
* Replaces unsafe `new Function()` usage with secure alternatives
|
|
19
|
+
*/
|
|
20
|
+
import type { ActionOrString, ErrorHandler, ErrorHandlerOrString, EventAction } from './types';
|
|
21
|
+
/**
|
|
22
|
+
* @deprecated host-application-level enforcement; this module will be removed in a follow-up task.
|
|
23
|
+
*/
|
|
24
|
+
export interface FunctionSecurityConfig {
|
|
25
|
+
allowedFunctionNames: Set<string>;
|
|
26
|
+
maxFunctionLength: number;
|
|
27
|
+
enableValidation: boolean;
|
|
28
|
+
customPatterns?: DangerousPattern[];
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* @deprecated host-application-level enforcement; this module will be removed in a follow-up task.
|
|
32
|
+
*/
|
|
33
|
+
export type FunctionRiskLevel = 'low' | 'medium' | 'high' | 'critical';
|
|
34
|
+
/**
|
|
35
|
+
* @deprecated host-application-level enforcement; this module will be removed in a follow-up task.
|
|
36
|
+
*/
|
|
37
|
+
export interface DangerousPattern {
|
|
38
|
+
pattern: RegExp;
|
|
39
|
+
risk: FunctionRiskLevel;
|
|
40
|
+
description: string;
|
|
41
|
+
category?: string;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* @deprecated host-application-level enforcement; this module will be removed in a follow-up task.
|
|
45
|
+
*/
|
|
46
|
+
export interface FunctionValidationResult {
|
|
47
|
+
isValid: boolean;
|
|
48
|
+
errors: string[];
|
|
49
|
+
riskLevel: FunctionRiskLevel;
|
|
50
|
+
detectedPatterns: string[];
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* @deprecated host-application-level enforcement; this module will be removed in a follow-up task.
|
|
54
|
+
*/
|
|
55
|
+
export declare const DEFAULT_SECURITY_CONFIG: FunctionSecurityConfig;
|
|
56
|
+
/**
|
|
57
|
+
* @deprecated host-application-level enforcement; this module will be removed in a follow-up task.
|
|
58
|
+
*/
|
|
59
|
+
export type SafeSerializedAction = {
|
|
60
|
+
type: 'string';
|
|
61
|
+
name: string;
|
|
62
|
+
} | {
|
|
63
|
+
type: 'function';
|
|
64
|
+
body: string;
|
|
65
|
+
hash: string;
|
|
66
|
+
metadata: {
|
|
67
|
+
length: number;
|
|
68
|
+
createdAt: number;
|
|
69
|
+
functionName?: string;
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* @deprecated host-application-level enforcement; this module will be removed in a follow-up task.
|
|
74
|
+
*/
|
|
75
|
+
export declare class FunctionValidator {
|
|
76
|
+
private config;
|
|
77
|
+
private allPatterns;
|
|
78
|
+
constructor(config?: Partial<FunctionSecurityConfig>);
|
|
79
|
+
addCustomPattern(pattern: DangerousPattern): void;
|
|
80
|
+
/**
|
|
81
|
+
* Validates function body for security threats.
|
|
82
|
+
*
|
|
83
|
+
* Never throws: returns a structured result.
|
|
84
|
+
*/
|
|
85
|
+
validate(body: string, functionName?: string): FunctionValidationResult;
|
|
86
|
+
/**
|
|
87
|
+
* Validates function body for security threats
|
|
88
|
+
*/
|
|
89
|
+
validateFunctionBody(body: string, functionName?: string): boolean;
|
|
90
|
+
/**
|
|
91
|
+
* Creates a security hash for function validation
|
|
92
|
+
*/
|
|
93
|
+
createSecurityHash(body: string, metadata: any): Promise<string>;
|
|
94
|
+
/**
|
|
95
|
+
* Validates security hash
|
|
96
|
+
*/
|
|
97
|
+
validateSecurityHash(body: string, metadata: any, expectedHash: string): Promise<boolean>;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* @deprecated host-application-level enforcement; this module will be removed in a follow-up task.
|
|
101
|
+
*/
|
|
102
|
+
export declare class SafeFunctionSerializer {
|
|
103
|
+
validator: FunctionValidator;
|
|
104
|
+
constructor(config?: Partial<FunctionSecurityConfig>);
|
|
105
|
+
/**
|
|
106
|
+
* Safely serializes an action with security validation (Async)
|
|
107
|
+
*/
|
|
108
|
+
serializeActionAsync<TOwner extends object, R = void>(action: ActionOrString<TOwner, R> | ErrorHandlerOrString<TOwner>, functionName?: string): Promise<SafeSerializedAction | undefined>;
|
|
109
|
+
/**
|
|
110
|
+
* Legacy synchronous serialization (Uses weak hash, kept for backward compatibility)
|
|
111
|
+
* @deprecated Use serializeActionAsync instead for better security
|
|
112
|
+
*/
|
|
113
|
+
serializeAction<TOwner extends object, R = void>(action: ActionOrString<TOwner, R> | ErrorHandlerOrString<TOwner>, functionName?: string): SafeSerializedAction | undefined;
|
|
114
|
+
/**
|
|
115
|
+
* Safely deserializes an action with security validation (Async)
|
|
116
|
+
*/
|
|
117
|
+
deserializeActionAsync<TOwner extends object, R = void>(serializedAction: SafeSerializedAction | undefined): Promise<ActionOrString<TOwner, R> | ErrorHandlerOrString<TOwner> | undefined>;
|
|
118
|
+
/**
|
|
119
|
+
* Safely deserializes an action (Synchronous - Legacy/Weak)
|
|
120
|
+
*/
|
|
121
|
+
deserializeAction<TOwner extends object, R = void>(serializedAction: SafeSerializedAction | undefined): ActionOrString<TOwner, R> | ErrorHandlerOrString<TOwner> | undefined;
|
|
122
|
+
/**
|
|
123
|
+
* Safely deserializes legacy function strings (without security metadata)
|
|
124
|
+
* This method provides backward compatibility for old string-based function serialization
|
|
125
|
+
* while maintaining security through validation and sandboxing.
|
|
126
|
+
*/
|
|
127
|
+
deserializeLegacyString(action: string): EventAction<any> | ErrorHandler<any> | undefined;
|
|
128
|
+
/**
|
|
129
|
+
* Creates a function safely without using new Function()
|
|
130
|
+
* Uses a whitelist approach with predefined function templates
|
|
131
|
+
*/
|
|
132
|
+
private createSafeFunction;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* @deprecated host-application-level enforcement; this module will be removed in a follow-up task.
|
|
136
|
+
*/
|
|
137
|
+
export declare const safeFunctionSerializer: SafeFunctionSerializer;
|
|
138
|
+
/**
|
|
139
|
+
* @deprecated host-application-level enforcement; this module will be removed in a follow-up task.
|
|
140
|
+
*/
|
|
141
|
+
export declare const serializeAction: <TOwner extends object, R = void>(action: ActionOrString<TOwner, R> | ErrorHandlerOrString<TOwner>, functionName?: string) => SafeSerializedAction | undefined;
|
|
142
|
+
/**
|
|
143
|
+
* @deprecated host-application-level enforcement; this module will be removed in a follow-up task.
|
|
144
|
+
*/
|
|
145
|
+
export declare const deserializeAction: <TOwner extends object, R = void>(serializedAction: SafeSerializedAction | undefined) => ActionOrString<TOwner, R> | ErrorHandlerOrString<TOwner> | undefined;
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { type Adapter, type MethodsOf, type PropertiesOf, type StateMachineConfig, type StateMachineOptions, type StateName, type StatePersistenceAdapter } from './types';
|
|
2
|
+
interface StateInfo {
|
|
3
|
+
name: string;
|
|
4
|
+
display?: string;
|
|
5
|
+
isComposite: boolean;
|
|
6
|
+
regions?: string[];
|
|
7
|
+
parent?: string;
|
|
8
|
+
children?: string[];
|
|
9
|
+
}
|
|
10
|
+
interface QueuedEventInfo {
|
|
11
|
+
id: string;
|
|
12
|
+
event: string;
|
|
13
|
+
age: number;
|
|
14
|
+
type: 'internal' | 'external';
|
|
15
|
+
}
|
|
16
|
+
export declare class StateMachine<TOwner extends object, SMConfig extends StateMachineConfig<TOwner>> {
|
|
17
|
+
private logger;
|
|
18
|
+
private monitor;
|
|
19
|
+
private scheduler;
|
|
20
|
+
private errorHandler;
|
|
21
|
+
private states;
|
|
22
|
+
private events;
|
|
23
|
+
private stateAttribute;
|
|
24
|
+
private onError?;
|
|
25
|
+
private adaptee?;
|
|
26
|
+
private context?;
|
|
27
|
+
private historyMap;
|
|
28
|
+
private initialState;
|
|
29
|
+
private persistenceAdapter?;
|
|
30
|
+
private activeTimers;
|
|
31
|
+
private stateEntryTimes;
|
|
32
|
+
private externalQueue;
|
|
33
|
+
private internalQueue;
|
|
34
|
+
private isProcessing;
|
|
35
|
+
private eventIdCounter;
|
|
36
|
+
private transitionDepth;
|
|
37
|
+
private readonly MAX_TRANSITION_DEPTH;
|
|
38
|
+
private transitionTimeout?;
|
|
39
|
+
private errorState?;
|
|
40
|
+
private abortOnExitError?;
|
|
41
|
+
private maxQueueDepth;
|
|
42
|
+
private _isTransitioning;
|
|
43
|
+
private _targetState;
|
|
44
|
+
get isTransitioning(): boolean;
|
|
45
|
+
get targetState(): string | undefined;
|
|
46
|
+
set currentState(state: StateName);
|
|
47
|
+
get currentState(): string;
|
|
48
|
+
constructor(config: SMConfig, adaptee?: Adapter<PropertiesOf<TOwner>> | PropertiesOf<TOwner>, options?: StateMachineOptions);
|
|
49
|
+
setContext(context: MethodsOf<TOwner>): void;
|
|
50
|
+
private enqueueEvent;
|
|
51
|
+
private raiseEvent;
|
|
52
|
+
private scheduleProcessing;
|
|
53
|
+
private processQueues;
|
|
54
|
+
private executeQueuedTransition;
|
|
55
|
+
/**
|
|
56
|
+
* Fires an event to trigger a state transition.
|
|
57
|
+
*
|
|
58
|
+
* @param eventName - The name of the event to fire. Use '*' for wildcard events.
|
|
59
|
+
* @param args - Additional arguments to pass to guards, actions, and callbacks.
|
|
60
|
+
* @returns Promise<boolean> - True if a transition occurred, false otherwise.
|
|
61
|
+
*
|
|
62
|
+
* @throws StateMachineError if the event is invalid or no transition is possible (unless configured otherwise).
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* const success = await sm.fireEvent('submit', payload);
|
|
66
|
+
*/
|
|
67
|
+
fireEvent(eventName: keyof SMConfig['events'] | '*', ...args: any[]): Promise<boolean>;
|
|
68
|
+
getQueueDepth(): {
|
|
69
|
+
internal: number;
|
|
70
|
+
external: number;
|
|
71
|
+
total: number;
|
|
72
|
+
};
|
|
73
|
+
getQueuedEvents(): QueuedEventInfo[];
|
|
74
|
+
isProcessingEvents(): boolean;
|
|
75
|
+
/**
|
|
76
|
+
* Checks if an event can be fired in the current state.
|
|
77
|
+
*
|
|
78
|
+
* @param eventName - The name of the event to check.
|
|
79
|
+
* @param adaptee - Optional adapter/object to check against (defaults to internal adaptee).
|
|
80
|
+
* @returns boolean - True if the event has a valid transition from the current state (guards are not executed).
|
|
81
|
+
*/
|
|
82
|
+
canFireEvent(eventName: keyof SMConfig['events'] | '*', adaptee?: Adapter<PropertiesOf<TOwner>>): boolean;
|
|
83
|
+
getAvailableEvents(adaptee?: Adapter<PropertiesOf<TOwner>>): string[];
|
|
84
|
+
reset(adaptee?: Adapter<PropertiesOf<TOwner>>): Promise<void>;
|
|
85
|
+
getStateHistory(): Record<string, string>;
|
|
86
|
+
getCurrentStateInfo(): StateInfo | undefined;
|
|
87
|
+
/**
|
|
88
|
+
* Checks if the machine is in a specific state.
|
|
89
|
+
* Supports hierarchical states (e.g. 'parent' matches 'parent.child').
|
|
90
|
+
*
|
|
91
|
+
* @param expectedState - The state name to check.
|
|
92
|
+
* @param adaptee - Optional adapter to check against.
|
|
93
|
+
* @returns boolean - True if the current state matches or is a substate of the expected state.
|
|
94
|
+
*/
|
|
95
|
+
isInState(expectedState: StateName, adaptee?: Adapter<PropertiesOf<TOwner>>): boolean;
|
|
96
|
+
attachToObject(object: any, eventMap: {
|
|
97
|
+
[key: string]: string;
|
|
98
|
+
}): void;
|
|
99
|
+
saveState(adapter?: StatePersistenceAdapter): Promise<void>;
|
|
100
|
+
restoreState(adapter?: StatePersistenceAdapter): Promise<void>;
|
|
101
|
+
static fromData<TOwner extends object, SMConfig extends StateMachineConfig<TOwner>>(config: SMConfig, initialState?: string, context?: TOwner, options?: StateMachineOptions): StateMachine<TOwner, SMConfig>;
|
|
102
|
+
static fromJSON<TOwner extends object, SMConfig extends StateMachineConfig<TOwner>>(jsonData: string, obj?: TOwner | Adapter<TOwner>, options?: StateMachineOptions): StateMachine<TOwner, SMConfig>;
|
|
103
|
+
/**
|
|
104
|
+
* Securely deserializes a StateMachine from JSON string (Async).
|
|
105
|
+
* Verifies cryptographic hashes of serialized functions.
|
|
106
|
+
*/
|
|
107
|
+
static fromSecureJSON<TOwner extends object, SMConfig extends StateMachineConfig<TOwner>>(jsonData: string, obj?: TOwner | Adapter<TOwner>, options?: StateMachineOptions): Promise<StateMachine<TOwner, SMConfig>>;
|
|
108
|
+
/**
|
|
109
|
+
* Deserialize states configuration (Async)
|
|
110
|
+
*/
|
|
111
|
+
private static deserializeStatesAsync;
|
|
112
|
+
/**
|
|
113
|
+
* Deserialize states configuration
|
|
114
|
+
*/
|
|
115
|
+
private static deserializeStates;
|
|
116
|
+
/**
|
|
117
|
+
* Deserialize events configuration (Async)
|
|
118
|
+
*/
|
|
119
|
+
private static deserializeEventsAsync;
|
|
120
|
+
/**
|
|
121
|
+
* Deserialize events configuration
|
|
122
|
+
*/
|
|
123
|
+
private static deserializeEvents;
|
|
124
|
+
/**
|
|
125
|
+
* Deserialize transition configuration (Async)
|
|
126
|
+
*/
|
|
127
|
+
private static deserializeTransitionAsync;
|
|
128
|
+
/**
|
|
129
|
+
* Deserialize transition configuration
|
|
130
|
+
*/
|
|
131
|
+
private static deserializeTransition;
|
|
132
|
+
/**
|
|
133
|
+
* Static method for deserializing actions (Async)
|
|
134
|
+
*/
|
|
135
|
+
private static deserializeActionAsync;
|
|
136
|
+
/**
|
|
137
|
+
* Static method for deserializing actions (now using safe deserializer)
|
|
138
|
+
*/
|
|
139
|
+
private static deserializeAction;
|
|
140
|
+
static fromJSONWithContext<TOwner extends object, SMConfig extends StateMachineConfig<TOwner>>(jsonData: string, context?: MethodsOf<TOwner>, options?: StateMachineOptions): StateMachine<TOwner, SMConfig>;
|
|
141
|
+
private setCurrentState;
|
|
142
|
+
private setCurrentStateInternal;
|
|
143
|
+
getCurrentState(adaptee?: Adapter<PropertiesOf<TOwner>>): string | undefined;
|
|
144
|
+
private setInitialState;
|
|
145
|
+
private getInitialCompositeState;
|
|
146
|
+
private getDirectChildren;
|
|
147
|
+
private getInitialStatesForRegions;
|
|
148
|
+
private validateCompositeState;
|
|
149
|
+
private processStates;
|
|
150
|
+
private processRegions;
|
|
151
|
+
private processError;
|
|
152
|
+
private callAction;
|
|
153
|
+
private getAllowedTransitions;
|
|
154
|
+
private isTransitionPossible;
|
|
155
|
+
private isParentState;
|
|
156
|
+
private applyTransition;
|
|
157
|
+
/**
|
|
158
|
+
* Execute exit actions for a state
|
|
159
|
+
*/
|
|
160
|
+
private executeExitActions;
|
|
161
|
+
/**
|
|
162
|
+
* Execute enter actions for a state
|
|
163
|
+
*/
|
|
164
|
+
private executeEnterActions;
|
|
165
|
+
/**
|
|
166
|
+
* Helper to set timer (native or scheduled)
|
|
167
|
+
*/
|
|
168
|
+
private setTimer;
|
|
169
|
+
/**
|
|
170
|
+
* Helper to clear timer
|
|
171
|
+
*/
|
|
172
|
+
private clearTimer;
|
|
173
|
+
/**
|
|
174
|
+
* Manage state history for transitions
|
|
175
|
+
*/
|
|
176
|
+
private manageStateHistory;
|
|
177
|
+
private findParentStateWithHistory;
|
|
178
|
+
private updatePartialState;
|
|
179
|
+
private updateState;
|
|
180
|
+
/**
|
|
181
|
+
* Remove conflicting states from the state map
|
|
182
|
+
*/
|
|
183
|
+
private removeConflictingStates;
|
|
184
|
+
/**
|
|
185
|
+
* Add region states to the state map
|
|
186
|
+
*/
|
|
187
|
+
private addRegionStates;
|
|
188
|
+
/**
|
|
189
|
+
* Clean up root states from the state map
|
|
190
|
+
*/
|
|
191
|
+
private cleanupRootStates;
|
|
192
|
+
private parseCompositeState;
|
|
193
|
+
private getRegionKey;
|
|
194
|
+
private resumeTimers;
|
|
195
|
+
toJSON(): string;
|
|
196
|
+
/**
|
|
197
|
+
* Securely serializes the StateMachine to JSON (Async).
|
|
198
|
+
* Generates cryptographic hashes for all functions.
|
|
199
|
+
*/
|
|
200
|
+
toSecureJSON(): Promise<string>;
|
|
201
|
+
/**
|
|
202
|
+
* Serialize state with optimized performance (Async)
|
|
203
|
+
*/
|
|
204
|
+
private serializeStateAsync;
|
|
205
|
+
/**
|
|
206
|
+
* Serialize state with optimized performance
|
|
207
|
+
*/
|
|
208
|
+
private serializeState;
|
|
209
|
+
/**
|
|
210
|
+
* Serialize event with optimized performance (Async)
|
|
211
|
+
*/
|
|
212
|
+
private serializeEventAsync;
|
|
213
|
+
/**
|
|
214
|
+
* Serialize transition (Async)
|
|
215
|
+
*/
|
|
216
|
+
private serializeTransitionAsync;
|
|
217
|
+
/**
|
|
218
|
+
* Serialize event with optimized performance
|
|
219
|
+
*/
|
|
220
|
+
private serializeEvent;
|
|
221
|
+
private serializeActionAsync;
|
|
222
|
+
/**
|
|
223
|
+
* Optimized action serialization using safe serializer
|
|
224
|
+
*/
|
|
225
|
+
private serializeAction;
|
|
226
|
+
}
|
|
227
|
+
export {};
|