qnce-engine
Version:
Core QNCE (Quantum Narrative Convergence Engine) - Framework agnostic narrative engine with performance optimization
452 lines • 14.6 kB
TypeScript
import { ThreadPoolConfig } from '../performance/ThreadPool';
import { QNCEBranchingEngine } from '../narrative/branching';
import { QNCEStory } from '../narrative/branching/models';
import { ChoiceValidator, ValidationResult } from './validation';
export { QNCENavigationError, ChoiceValidationError } from './errors';
import { SerializedState, Checkpoint, SerializationOptions, LoadOptions, PersistenceResult, CheckpointOptions } from './types';
import { StorageAdapter } from './types';
import { CustomEvaluatorFunction } from './condition';
import { AutosaveConfig, UndoRedoConfig, UndoRedoResult, AutosaveResult } from './types';
export interface Choice {
text: string;
nextNodeId: string;
flagEffects?: Record<string, unknown>;
flagRequirements?: Record<string, unknown>;
timeRequirements?: {
minTime?: number;
maxTime?: number;
availableAfter?: Date;
availableBefore?: Date;
};
inventoryRequirements?: Record<string, number>;
enabled?: boolean;
condition?: string;
}
export interface NarrativeNode {
id: string;
text: string;
choices: Choice[];
meta?: {
tags?: string[];
};
}
export { QNCEStory };
export interface QNCEState {
currentNodeId: string;
flags: Record<string, unknown>;
history: string[];
}
export interface FlowEvent {
id: string;
fromNodeId: string;
toNodeId: string;
timestamp: number;
metadata?: Record<string, unknown>;
}
export interface StoryData {
nodes: NarrativeNode[];
initialNodeId: string;
}
/**
* QNCE Engine - Core narrative state management
* Framework agnostic implementation with object pooling integration
*/
export declare class QNCEEngine {
private state;
storyData: StoryData;
private activeFlowEvents;
private performanceMode;
private enableProfiling;
private branchingEngine?;
private choiceValidator;
private checkpoints;
private maxCheckpoints;
private autoCheckpointEnabled;
private checkpointManager?;
private undoStack;
private redoStack;
private autosaveConfig;
private undoRedoConfig;
private lastAutosaveTime;
private isUndoRedoOperation;
private storageAdapter?;
private telemetry?;
private defaultTelemetryCtx?;
get flags(): Record<string, unknown>;
get history(): string[];
get isComplete(): boolean;
constructor(storyData: StoryData, initialState?: Partial<QNCEState>, performanceMode?: boolean, threadPoolConfig?: Partial<ThreadPoolConfig>, options?: {
telemetry?: import('../telemetry/types').Telemetry;
env?: 'dev' | 'test' | 'prod';
appVersion?: string;
sessionId?: string;
});
/** Attach a storage adapter for persistence */
attachStorageAdapter(adapter: StorageAdapter): void;
/** Save current state through the attached storage adapter */
saveToStorage(key: string, options?: SerializationOptions): Promise<PersistenceResult>;
/** Load state from the attached storage adapter */
loadFromStorage(key: string, options?: LoadOptions): Promise<PersistenceResult>;
/** Delete a stored state via the adapter */
deleteFromStorage(key: string): Promise<boolean>;
/** List keys from the adapter */
listStorageKeys(): Promise<string[]>;
/** Check if a key exists via the adapter */
storageExists(key: string): Promise<boolean>;
/** Clear all stored data via the adapter */
clearStorage(): Promise<boolean>;
/** Get storage statistics from the adapter */
getStorageStats(): Promise<{
totalSize: number;
keyCount: number;
[key: string]: unknown;
} | null>;
/**
* Navigate directly to a specific node by ID
* @param nodeId - The ID of the node to navigate to
* @throws {QNCENavigationError} When nodeId is invalid or not found
*/
goToNodeById(nodeId: string): void;
/**
* Get the current narrative node
* @returns The current node object
*/
getCurrentNode(): NarrativeNode;
/**
* Get available choices from the current node with validation and conditional filtering
* @returns Array of available choices
*/
getAvailableChoices(): Choice[];
makeChoice(choiceIndex: number): void;
getState(): QNCEState;
getFlags(): Record<string, unknown>;
setFlag(key: string, value: unknown): void;
getHistory(): string[];
selectChoice(choice: Choice): void;
/** Flush telemetry (useful before process exit) */
flushTelemetry(): Promise<void>;
resetNarrative(): void;
/**
* Load simple state (legacy method for backward compatibility)
* @param state - QNCEState to load
*/
loadSimpleState(state: QNCEState): void;
/**
* Save current engine state to a serialized format
* @param options - Serialization options
* @returns Promise resolving to serialized state
*/
saveState(options?: SerializationOptions): Promise<SerializedState>;
/**
* Load engine state from serialized format
* @param serializedState - The serialized state to load
* @param options - Load options
* @returns Promise resolving to persistence result
*/
loadState(serializedState: SerializedState, options?: LoadOptions): Promise<PersistenceResult>;
/**
* Create a lightweight checkpoint of current state
* @param name - Optional checkpoint name
* @param options - Checkpoint options
* @returns Promise resolving to created checkpoint
*/
createCheckpoint(name?: string, options?: CheckpointOptions): Promise<Checkpoint>;
/**
* Restore engine state from a checkpoint
* @param checkpointId - ID of checkpoint to restore
* @returns Promise resolving to persistence result
*/
restoreFromCheckpoint(checkpointId: string): Promise<PersistenceResult>;
checkFlag(flagName: string, expectedValue?: unknown): boolean;
/**
* Get the choice validator instance
* @returns The current choice validator
*/
getChoiceValidator(): ChoiceValidator;
/**
* Validate a specific choice without executing it
* @param choice - The choice to validate
* @returns Validation result with details
*/
validateChoice(choice: Choice): ValidationResult;
/**
* Check if a specific choice is valid without executing it
* @param choice - The choice to check
* @returns True if the choice is valid, false otherwise
*/
isChoiceValid(choice: Choice): boolean;
/**
* Create a flow event using pooled objects for performance tracking
*/
private createFlowEvent;
/**
* Record and manage flow events
*/
private recordFlowEvent;
/**
* Get current flow events (for debugging/monitoring)
*/
getActiveFlows(): FlowEvent[];
/**
* Get object pool statistics for performance monitoring
*/
getPoolStats(): {
flows: {
poolSize: number;
maxSize: number;
created: number;
borrowed: number;
returned: number;
inUse: number;
hitRate: number;
};
nodes: {
poolSize: number;
maxSize: number;
created: number;
borrowed: number;
returned: number;
inUse: number;
hitRate: number;
};
assets: {
poolSize: number;
maxSize: number;
created: number;
borrowed: number;
returned: number;
inUse: number;
hitRate: number;
};
} | null;
/**
* Return all pooled objects (cleanup method)
*/
private cleanupPools;
/**
* Preload next possible nodes in background using ThreadPool
*/
preloadNextNodes(choice?: Choice): Promise<void>;
/**
* Write telemetry data in background using ThreadPool
*/
backgroundTelemetryWrite(eventData: Record<string, unknown>): Promise<void>;
/**
* Enable advanced branching capabilities for this story
* Integrates the QNCE Branching API with the core engine
*/
enableBranching(story: QNCEStory): QNCEBranchingEngine;
/**
* Get the branching engine if enabled
*/
getBranchingEngine(): QNCEBranchingEngine | undefined;
/**
* Check if branching is enabled
*/
isBranchingEnabled(): boolean;
/**
* Sync core engine state with branching engine
* Call this when core state changes to keep branching engine updated
*/
syncBranchingState(): void;
/**
* Disable branching and cleanup resources
*/
disableBranching(): void;
/**
* Background cache warming for story data
*/
warmCache(): Promise<void>;
/**
* Deep copy utility for state objects
* @param obj - Object to deep copy
* @returns Deep copied object
*/
private deepCopy;
/**
* Generate a hash for the current story data
* @returns Story hash string
*/
private generateStoryHash;
/**
* Generate a unique checkpoint ID
* @returns Unique checkpoint ID
*/
private generateCheckpointId;
/**
* Generate checksum for data integrity
* @param data - Data to generate checksum for
* @returns Promise resolving to checksum string
*/
private generateChecksum;
/**
* Verify checksum integrity
* @param serializedState - State with checksum to verify
* @returns Promise resolving to verification result
*/
private verifyChecksum;
/**
* Validate the structure of the serialized state object
* @param serializedState - State to validate
* @returns Validation result
*/
private validateSerializedState;
/**
* Check version compatibility
* @param metadata - Serialization metadata
* @returns Compatibility check result
*/
private checkCompatibility;
/**
* Cleanup old checkpoints based on strategy
* @param strategy - Cleanup strategy
* @param maxCheckpoints - Maximum number of checkpoints to keep
* @returns Promise resolving to number of cleaned checkpoints
*/
private cleanupCheckpoints;
/**
* Get all checkpoints
* @returns Array of all checkpoints
*/
getCheckpoints(): Checkpoint[];
/**
* Get specific checkpoint by ID
* @param id - Checkpoint ID
* @returns Checkpoint or undefined
*/
getCheckpoint(id: string): Checkpoint | undefined;
/**
* Delete a checkpoint
* @param id - Checkpoint ID to delete
* @returns Whether checkpoint was deleted
*/
deleteCheckpoint(id: string): boolean;
/**
* Enable/disable automatic checkpointing
* @param enabled - Whether to enable auto-checkpointing
*/
setAutoCheckpoint(enabled: boolean): void;
/**
* Configure autosave settings
* @param config - Autosave configuration
*/
configureAutosave(config: Partial<AutosaveConfig>): void;
/**
* Configure undo/redo settings
* @param config - Undo/redo configuration
*/
configureUndoRedo(config: Partial<UndoRedoConfig>): void;
/**
* Push a state to the undo stack
* @param state - State to save
* @param action - Action that caused this state change
* @param metadata - Optional metadata about the change
*/
private pushToUndoStack;
/**
* Undo the last operation
* @returns Result of undo operation
*/
undo(): UndoRedoResult;
/**
* Redo the last undone operation
* @returns Result of redo operation
*/
redo(): UndoRedoResult;
/**
* Check if undo is available
* @returns True if undo is possible
*/
canUndo(): boolean;
/**
* Check if redo is available
* @returns True if redo is possible
*/
canRedo(): boolean;
/**
* Get the number of available undo operations
* @returns Number of undo entries
*/
getUndoCount(): number;
/**
* Get the number of available redo operations
* @returns Number of redo entries
*/
getRedoCount(): number;
/**
* Clear all undo/redo history
*/
clearHistory(): void;
/**
* Get history summary for debugging
* @returns Summary of undo/redo history
*/
getHistorySummary(): {
undoEntries: {
id: string;
timestamp: string;
action?: string;
}[];
redoEntries: {
id: string;
timestamp: string;
action?: string;
}[];
};
/**
* Trigger an autosave operation
* @param trigger - What triggered the autosave
* @param metadata - Optional metadata about the trigger
* @returns Promise resolving to autosave result
*/
private triggerAutosave;
/**
* Manually trigger an autosave
* @param metadata - Optional metadata
* @returns Promise resolving to autosave result
*/
manualAutosave(metadata?: Record<string, unknown>): Promise<AutosaveResult>;
/**
* Generate a unique history entry ID
* @returns Unique ID string
*/
private generateHistoryId;
/**
* Set a custom condition evaluator function for complex choice logic
* @param evaluator - Custom evaluator function
*/
setConditionEvaluator(evaluator: CustomEvaluatorFunction): void;
/**
* Clear the custom condition evaluator
*/
clearConditionEvaluator(): void;
/**
* Validate a condition expression without evaluating it
* @param expression - Condition expression to validate
* @returns Validation result
*/
validateCondition(expression: string): {
valid: boolean;
error?: string;
};
/**
* Get flags referenced in a condition expression
* @param expression - Condition expression to analyze
* @returns Array of flag names referenced
*/
getConditionFlags(expression: string): string[];
}
/**
* Factory function to create a QNCE engine instance
*/
export declare function createQNCEEngine(storyData: StoryData, initialState?: Partial<QNCEState>, performanceMode?: boolean, threadPoolConfig?: Partial<ThreadPoolConfig>, options?: {
telemetry?: import('../telemetry/types').Telemetry;
env?: 'dev' | 'test' | 'prod';
appVersion?: string;
sessionId?: string;
}): QNCEEngine;
/**
* Load story data from JSON
*/
export declare function loadStoryData(jsonData: unknown): StoryData;
//# sourceMappingURL=core.d.ts.map