qnce-engine 1.3.2 → 1.4.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.
Files changed (166) hide show
  1. package/README.md +134 -2
  2. package/dist/adapters/contracts.d.ts +1 -1
  3. package/dist/adapters/contracts.d.ts.map +1 -1
  4. package/dist/adapters/storage/MockAdapters.d.ts +89 -0
  5. package/dist/adapters/storage/MockAdapters.d.ts.map +1 -0
  6. package/dist/adapters/storage/MockAdapters.js +109 -0
  7. package/dist/adapters/storage/MockAdapters.js.map +1 -0
  8. package/dist/adapters/story/CustomJSONAdapter.d.ts +1 -1
  9. package/dist/adapters/story/CustomJSONAdapter.d.ts.map +1 -1
  10. package/dist/adapters/story/CustomJSONAdapter.js +20 -14
  11. package/dist/adapters/story/CustomJSONAdapter.js.map +1 -1
  12. package/dist/adapters/story/InkAdapter.d.ts +1 -1
  13. package/dist/adapters/story/InkAdapter.d.ts.map +1 -1
  14. package/dist/adapters/story/InkAdapter.js +7 -10
  15. package/dist/adapters/story/InkAdapter.js.map +1 -1
  16. package/dist/adapters/story/TwisonAdapter.d.ts +1 -1
  17. package/dist/adapters/story/TwisonAdapter.d.ts.map +1 -1
  18. package/dist/adapters/story/TwisonAdapter.js +2 -2
  19. package/dist/adapters/story/TwisonAdapter.js.map +1 -1
  20. package/dist/cli/audit.js +1 -0
  21. package/dist/cli/audit.js.map +1 -1
  22. package/dist/cli/import.d.ts.map +1 -1
  23. package/dist/cli/import.js +31 -20
  24. package/dist/cli/import.js.map +1 -1
  25. package/dist/cli/init.js +1 -0
  26. package/dist/cli/init.js.map +1 -1
  27. package/dist/cli/perf.d.ts.map +1 -1
  28. package/dist/cli/perf.js +30 -0
  29. package/dist/cli/perf.js.map +1 -1
  30. package/dist/cli/play.d.ts.map +1 -1
  31. package/dist/cli/play.js +90 -77
  32. package/dist/cli/play.js.map +1 -1
  33. package/dist/engine/condition.d.ts +25 -3
  34. package/dist/engine/condition.d.ts.map +1 -1
  35. package/dist/engine/condition.js +358 -64
  36. package/dist/engine/condition.js.map +1 -1
  37. package/dist/engine/core.d.ts +93 -1
  38. package/dist/engine/core.d.ts.map +1 -1
  39. package/dist/engine/core.js +405 -33
  40. package/dist/engine/core.js.map +1 -1
  41. package/dist/engine/demo-story.d.ts +1 -0
  42. package/dist/engine/demo-story.d.ts.map +1 -1
  43. package/dist/engine/demo-story.js +1 -0
  44. package/dist/engine/demo-story.js.map +1 -1
  45. package/dist/engine/error-factory.d.ts +86 -0
  46. package/dist/engine/error-factory.d.ts.map +1 -0
  47. package/dist/engine/error-factory.js +87 -0
  48. package/dist/engine/error-factory.js.map +1 -0
  49. package/dist/engine/errors.d.ts +3 -0
  50. package/dist/engine/errors.d.ts.map +1 -1
  51. package/dist/engine/errors.js +3 -0
  52. package/dist/engine/errors.js.map +1 -1
  53. package/dist/engine/validation.js +1 -1
  54. package/dist/engine/validation.js.map +1 -1
  55. package/dist/index.d.ts +20 -0
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +29 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/integrations/react.d.ts +20 -3
  60. package/dist/integrations/react.d.ts.map +1 -1
  61. package/dist/integrations/react.js +15 -2
  62. package/dist/integrations/react.js.map +1 -1
  63. package/dist/narrative/branching/models.d.ts +1 -0
  64. package/dist/narrative/branching/models.d.ts.map +1 -1
  65. package/dist/narrative/branching/models.js.map +1 -1
  66. package/dist/performance/AdaptiveControllers.d.ts +51 -0
  67. package/dist/performance/AdaptiveControllers.d.ts.map +1 -0
  68. package/dist/performance/AdaptiveControllers.js +87 -0
  69. package/dist/performance/AdaptiveControllers.js.map +1 -0
  70. package/dist/performance/ContextPool.d.ts +1 -0
  71. package/dist/performance/ContextPool.d.ts.map +1 -0
  72. package/dist/performance/ContextPool.js +2 -0
  73. package/dist/performance/ContextPool.js.map +1 -0
  74. package/dist/performance/HotReloadDelta.d.ts +5 -0
  75. package/dist/performance/HotReloadDelta.d.ts.map +1 -1
  76. package/dist/performance/HotReloadDelta.js +18 -4
  77. package/dist/performance/HotReloadDelta.js.map +1 -1
  78. package/dist/performance/ObjectPool.d.ts.map +1 -1
  79. package/dist/performance/ObjectPool.js +4 -1
  80. package/dist/performance/ObjectPool.js.map +1 -1
  81. package/dist/performance/PerfReporter.d.ts +69 -0
  82. package/dist/performance/PerfReporter.d.ts.map +1 -1
  83. package/dist/performance/PerfReporter.js +314 -28
  84. package/dist/performance/PerfReporter.js.map +1 -1
  85. package/dist/performance/ThreadPool.d.ts +5 -0
  86. package/dist/performance/ThreadPool.d.ts.map +1 -1
  87. package/dist/performance/ThreadPool.js +33 -5
  88. package/dist/performance/ThreadPool.js.map +1 -1
  89. package/dist/persistence/StorageAdapters.d.ts.map +1 -1
  90. package/dist/persistence/StorageAdapters.js +13 -19
  91. package/dist/persistence/StorageAdapters.js.map +1 -1
  92. package/dist/qnce-engine.d.ts +2258 -0
  93. package/dist/quantum/entangler.d.ts +13 -0
  94. package/dist/quantum/entangler.d.ts.map +1 -0
  95. package/dist/quantum/entangler.js +24 -0
  96. package/dist/quantum/entangler.js.map +1 -0
  97. package/dist/quantum/flags.d.ts +24 -0
  98. package/dist/quantum/flags.d.ts.map +1 -0
  99. package/dist/quantum/flags.js +29 -0
  100. package/dist/quantum/flags.js.map +1 -0
  101. package/dist/quantum/integration.d.ts +26 -0
  102. package/dist/quantum/integration.d.ts.map +1 -0
  103. package/dist/quantum/integration.js +38 -0
  104. package/dist/quantum/integration.js.map +1 -0
  105. package/dist/quantum/measurement.d.ts +22 -0
  106. package/dist/quantum/measurement.d.ts.map +1 -0
  107. package/dist/quantum/measurement.js +44 -0
  108. package/dist/quantum/measurement.js.map +1 -0
  109. package/dist/quantum/phase.d.ts +20 -0
  110. package/dist/quantum/phase.d.ts.map +1 -0
  111. package/dist/quantum/phase.js +22 -0
  112. package/dist/quantum/phase.js.map +1 -0
  113. package/dist/quantum/types.d.ts +12 -0
  114. package/dist/quantum/types.d.ts.map +1 -0
  115. package/dist/quantum/types.js +5 -0
  116. package/dist/quantum/types.js.map +1 -0
  117. package/dist/schemas/validateStoryData.d.ts.map +1 -1
  118. package/dist/schemas/validateStoryData.js +8 -2
  119. package/dist/schemas/validateStoryData.js.map +1 -1
  120. package/dist/telemetry/core.d.ts +27 -1
  121. package/dist/telemetry/core.d.ts.map +1 -1
  122. package/dist/telemetry/core.js +63 -8
  123. package/dist/telemetry/core.js.map +1 -1
  124. package/dist/telemetry/types.d.ts +27 -0
  125. package/dist/telemetry/types.d.ts.map +1 -1
  126. package/dist/tsdoc-metadata.json +11 -0
  127. package/dist/ui/__tests__/AutosaveIndicator.test.js +10 -13
  128. package/dist/ui/__tests__/AutosaveIndicator.test.js.map +1 -1
  129. package/dist/ui/__tests__/UndoRedoControls.test.js +7 -9
  130. package/dist/ui/__tests__/UndoRedoControls.test.js.map +1 -1
  131. package/dist/ui/components/AutosaveIndicator.d.ts +1 -0
  132. package/dist/ui/components/AutosaveIndicator.d.ts.map +1 -1
  133. package/dist/ui/components/AutosaveIndicator.js +2 -1
  134. package/dist/ui/components/AutosaveIndicator.js.map +1 -1
  135. package/dist/ui/components/UndoRedoControls.d.ts +1 -0
  136. package/dist/ui/components/UndoRedoControls.d.ts.map +1 -1
  137. package/dist/ui/components/UndoRedoControls.js +1 -0
  138. package/dist/ui/components/UndoRedoControls.js.map +1 -1
  139. package/dist/ui/hooks/useKeyboardShortcuts.d.ts +1 -0
  140. package/dist/ui/hooks/useKeyboardShortcuts.d.ts.map +1 -1
  141. package/dist/ui/hooks/useKeyboardShortcuts.js +17 -5
  142. package/dist/ui/hooks/useKeyboardShortcuts.js.map +1 -1
  143. package/dist/ui/types.d.ts +6 -0
  144. package/dist/ui/types.d.ts.map +1 -1
  145. package/dist/ui/types.js +1 -0
  146. package/dist/ui/types.js.map +1 -1
  147. package/dist/utils/debug-logger.d.ts +20 -0
  148. package/dist/utils/debug-logger.d.ts.map +1 -0
  149. package/dist/utils/debug-logger.js +24 -0
  150. package/dist/utils/debug-logger.js.map +1 -0
  151. package/dist/utils/hot-profiler.d.ts +21 -0
  152. package/dist/utils/hot-profiler.d.ts.map +1 -0
  153. package/dist/utils/hot-profiler.js +36 -0
  154. package/dist/utils/hot-profiler.js.map +1 -0
  155. package/dist/utils/intern.d.ts +11 -0
  156. package/dist/utils/intern.d.ts.map +1 -0
  157. package/dist/utils/intern.js +45 -0
  158. package/dist/utils/intern.js.map +1 -0
  159. package/dist/utils/logger.d.ts +34 -0
  160. package/dist/utils/logger.d.ts.map +1 -0
  161. package/dist/utils/logger.js +115 -0
  162. package/dist/utils/logger.js.map +1 -0
  163. package/docs/PERFORMANCE.md +330 -0
  164. package/examples/fluent-builder-prototype.ts +71 -0
  165. package/examples/quantum-integration-demo.ts +51 -0
  166. package/package.json +25 -9
@@ -0,0 +1,2258 @@
1
+ import { default as React_2 } from 'react';
2
+
3
+ /**
4
+ * Interfaces for AI-driven content generation and branching
5
+ */
6
+ declare interface AIBranchingContext {
7
+ playerProfile: PlayerProfile;
8
+ narrativeContext: NarrativeContext;
9
+ generationHints: AIGenerationHints;
10
+ }
11
+
12
+ declare interface AIGenerationHints {
13
+ maxBranchDepth: number;
14
+ desiredComplexity: number;
15
+ contentThemes: string[];
16
+ avoidElements: string[];
17
+ }
18
+
19
+ /**
20
+ * Attach optional quantum helpers to an engine instance. No-ops unless the corresponding
21
+ * feature flags are enabled. This does not mutate engine behavior; it only provides
22
+ * opt-in utilities that operate against engine.flags.
23
+ */
24
+ /** @beta @experimental */
25
+ export declare function attachQuantumFeatures(engine: Pick<QNCEEngine, 'flags'>, flagsConfig?: FeatureFlags | FeatureFlagsConfig): QuantumIntegration;
26
+
27
+ /**
28
+ * Configuration for autosave functionality
29
+ */
30
+ declare interface AutosaveConfig {
31
+ /** Whether autosave is enabled */
32
+ enabled: boolean;
33
+ /** Triggers that should cause an autosave */
34
+ triggers: ('choice' | 'flag-change' | 'state-load' | 'branch-exit' | 'custom')[];
35
+ /** Maximum number of autosave entries to keep */
36
+ maxEntries: number;
37
+ /** Minimum time between autosaves (ms) to prevent spam */
38
+ throttleMs: number;
39
+ /** Whether to include metadata in autosave entries */
40
+ includeMetadata: boolean;
41
+ /** Custom autosave naming pattern */
42
+ namePattern?: string;
43
+ }
44
+
45
+ /**
46
+ * AutosaveIndicator Component
47
+ *
48
+ * Visual indicator showing autosave status with animated feedback,
49
+ * timestamp display, and customizable positioning.
50
+ *
51
+ * Features:
52
+ * - Real-time autosave status updates (idle, saving, saved, error)
53
+ * - Animated visual feedback with spinner and status icons
54
+ * - Configurable positioning (corners, inline)
55
+ * - Timestamp of last successful save
56
+ * - Auto-hide functionality
57
+ * - Accessible with proper ARIA labels
58
+ * @public
59
+ */
60
+ export declare const AutosaveIndicator: React_2.FC<AutosaveIndicatorProps>;
61
+
62
+ /**
63
+ * Props for AutosaveIndicator component
64
+ * @public
65
+ */
66
+ export declare interface AutosaveIndicatorProps {
67
+ /** QNCE Engine instance */
68
+ engine: QNCEEngine;
69
+ /** Custom theme (optional, uses default if not provided) */
70
+ theme?: Partial<QNCETheme>;
71
+ /** Additional CSS class name */
72
+ className?: string;
73
+ /** Custom styling */
74
+ style?: React.CSSProperties;
75
+ /** Indicator variant */
76
+ variant?: 'minimal' | 'detailed' | 'icon-only';
77
+ /** Position of the indicator */
78
+ position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'inline';
79
+ /** Custom status messages */
80
+ messages?: {
81
+ idle: string;
82
+ saving: string;
83
+ saved: string;
84
+ error: string;
85
+ };
86
+ /** Show timestamp of last save */
87
+ showTimestamp?: boolean;
88
+ /** Auto-hide after successful save (ms) */
89
+ autoHideDelay?: number;
90
+ }
91
+
92
+ /**
93
+ * Autosave operation result
94
+ */
95
+ declare interface AutosaveResult {
96
+ /** Whether the autosave succeeded */
97
+ success: boolean;
98
+ /** Error message if autosave failed */
99
+ error?: string;
100
+ /** The checkpoint ID created by autosave */
101
+ checkpointId?: string;
102
+ /** Trigger that caused this autosave */
103
+ trigger?: string;
104
+ /** Time taken for autosave operation (ms) */
105
+ duration?: number;
106
+ /** Size of the autosaved data */
107
+ size?: number;
108
+ }
109
+
110
+ declare interface BranchAnalytics {
111
+ totalBranchesTraversed: number;
112
+ avgBranchDecisionTime: number;
113
+ mostPopularBranches: string[];
114
+ abandonmentPoints: string[];
115
+ completionRate: number;
116
+ sessionStartTime: Date;
117
+ }
118
+
119
+ declare interface BranchCondition {
120
+ type: 'flag' | 'choice' | 'time' | 'random' | 'custom';
121
+ operator: 'equals' | 'not_equals' | 'greater' | 'less' | 'contains' | 'exists';
122
+ key: string;
123
+ value: unknown;
124
+ evaluator?: (state: QNCEState, context: BranchContext) => boolean;
125
+ }
126
+
127
+ /**
128
+ * BranchContext: Runtime state for branch evaluation and tracking
129
+ */
130
+ declare interface BranchContext {
131
+ currentStory: QNCEStory;
132
+ currentChapter: Chapter;
133
+ currentFlow: NarrativeFlow;
134
+ activeState: QNCEState;
135
+ branchHistory: BranchHistoryEntry[];
136
+ pendingBranches: PendingBranch[];
137
+ analytics: BranchAnalytics;
138
+ }
139
+
140
+ declare interface BranchHistoryEntry {
141
+ id: string;
142
+ branchPointId: string;
143
+ chosenOptionId: string;
144
+ timestamp: Date;
145
+ executionTime: number;
146
+ context: Partial<QNCEState>;
147
+ }
148
+
149
+ declare interface BranchingConfig {
150
+ maxActiveBranches: number;
151
+ branchCacheSize: number;
152
+ enableDynamicInsertion: boolean;
153
+ enableAnalytics: boolean;
154
+ performanceMode: boolean;
155
+ }
156
+
157
+ declare interface BranchLocation {
158
+ chapterId: string;
159
+ flowId: string;
160
+ nodeId: string;
161
+ insertionPoint: 'before' | 'after' | 'replace';
162
+ }
163
+
164
+ declare interface BranchMetadata {
165
+ usageCount: number;
166
+ avgTraversalTime: number;
167
+ playerPreference: number;
168
+ lastUsed: Date;
169
+ }
170
+
171
+ declare interface BranchOption {
172
+ id: string;
173
+ targetFlowId: string;
174
+ targetNodeId?: string;
175
+ displayText: string;
176
+ conditions?: BranchCondition[];
177
+ flagEffects?: Record<string, unknown>;
178
+ weight: number;
179
+ }
180
+
181
+ /**
182
+ * BranchPoint: Dynamic branching logic between flows
183
+ */
184
+ declare interface BranchPoint {
185
+ id: string;
186
+ name: string;
187
+ sourceFlowId: string;
188
+ sourceNodeId: string;
189
+ branchOptions: BranchOption[];
190
+ branchType: BranchType;
191
+ conditions?: BranchCondition[];
192
+ metadata: BranchMetadata;
193
+ }
194
+
195
+ declare type BranchType = 'choice-driven' | 'flag-conditional' | 'time-based' | 'procedural' | 'conditional';
196
+
197
+ /**
198
+ * Chapter: Logical grouping of narrative flows with branching points
199
+ */
200
+ declare interface Chapter {
201
+ id: string;
202
+ title: string;
203
+ description?: string;
204
+ flows: NarrativeFlow[];
205
+ branches: BranchPoint[];
206
+ prerequisites?: ChapterPrerequisites;
207
+ metadata: ChapterMetadata;
208
+ }
209
+
210
+ declare interface ChapterMetadata {
211
+ difficulty: 'easy' | 'medium' | 'hard';
212
+ themes: string[];
213
+ estimatedDuration: number;
214
+ branchComplexity: number;
215
+ }
216
+
217
+ declare interface ChapterPrerequisites {
218
+ requiredFlags: Record<string, unknown>;
219
+ requiredChoices: string[];
220
+ minPlaytime?: number;
221
+ }
222
+
223
+ /**
224
+ * Lightweight checkpoint for quick save/restore operations
225
+ * Contains minimal data for fast state snapshots
226
+ */
227
+ declare interface Checkpoint {
228
+ /** Unique checkpoint identifier */
229
+ id: string;
230
+ /** Human-readable checkpoint name/label */
231
+ name?: string;
232
+ /** Core state snapshot (deep copied) */
233
+ state: QNCEState;
234
+ /** Checkpoint creation timestamp */
235
+ timestamp: string;
236
+ /** Optional description or context */
237
+ description?: string;
238
+ /** Tags for checkpoint organization */
239
+ tags?: string[];
240
+ /** Lightweight metadata */
241
+ metadata?: {
242
+ nodeTitle?: string;
243
+ choiceCount?: number;
244
+ flagCount?: number;
245
+ historyLength?: number;
246
+ [key: string]: unknown;
247
+ };
248
+ }
249
+
250
+ /**
251
+ * Checkpoint management options
252
+ */
253
+ declare interface CheckpointOptions {
254
+ /** Maximum number of checkpoints to keep */
255
+ maxCheckpoints?: number;
256
+ /** Auto-cleanup strategy */
257
+ cleanupStrategy?: 'lru' | 'fifo' | 'timestamp' | 'manual';
258
+ /** Include metadata in checkpoint */
259
+ includeMetadata?: boolean;
260
+ /** Tags to automatically apply */
261
+ autoTags?: string[];
262
+ }
263
+
264
+ /** Narrative choice presented to user */
265
+ /** @public */
266
+ export declare interface Choice {
267
+ text: string;
268
+ nextNodeId: string;
269
+ flagEffects?: Record<string, unknown>;
270
+ flagRequirements?: Record<string, unknown>;
271
+ timeRequirements?: {
272
+ minTime?: number;
273
+ maxTime?: number;
274
+ availableAfter?: Date;
275
+ availableBefore?: Date;
276
+ };
277
+ inventoryRequirements?: Record<string, number>;
278
+ enabled?: boolean;
279
+ condition?: string;
280
+ }
281
+
282
+ /**
283
+ * Error thrown when choice validation fails
284
+ * Provides detailed information about why the choice is invalid
285
+ * @public
286
+ */
287
+ export declare class ChoiceValidationError extends QNCEError {
288
+ readonly choice: Choice;
289
+ readonly validationResult: ValidationResult;
290
+ readonly availableChoices?: Choice[];
291
+ constructor(choice: Choice, validationResult: ValidationResult, availableChoices?: Choice[]);
292
+ /**
293
+ * Get a user-friendly error message with suggestions
294
+ */
295
+ getUserFriendlyMessage(): string;
296
+ /**
297
+ * Get debugging information for developers
298
+ */
299
+ getDebugInfo(): Record<string, unknown>;
300
+ }
301
+
302
+ /**
303
+ * Core ChoiceValidator interface
304
+ * Provides validation logic for choice execution and availability filtering
305
+ */
306
+ declare interface ChoiceValidator {
307
+ /**
308
+ * Validate a specific choice against current state
309
+ * @param choice - The choice to validate
310
+ * @param context - Current validation context
311
+ * @returns Validation result with details
312
+ */
313
+ validate(choice: Choice, context: ValidationContext): ValidationResult;
314
+ /**
315
+ * Get all currently available/valid choices
316
+ * @param context - Current validation context
317
+ * @returns Array of valid choices
318
+ */
319
+ getAvailableChoices(context: ValidationContext): Choice[];
320
+ /**
321
+ * Add a validation rule to the validator
322
+ * @param rule - Validation rule to add
323
+ */
324
+ addRule(rule: ValidationRule): void;
325
+ /**
326
+ * Remove a validation rule by name
327
+ * @param ruleName - Name of the rule to remove
328
+ */
329
+ removeRule(ruleName: string): void;
330
+ /**
331
+ * Get all registered validation rules
332
+ * @returns Array of validation rules sorted by priority
333
+ */
334
+ getRules(): ValidationRule[];
335
+ }
336
+
337
+ /**
338
+ * Context object passed to condition evaluators
339
+ * @public
340
+ */
341
+ export declare interface ConditionContext {
342
+ /** Current engine state */
343
+ state: QNCEState;
344
+ /** Current timestamp for time-based conditions */
345
+ timestamp: number;
346
+ /** Additional custom context data */
347
+ customData?: Record<string, unknown>;
348
+ }
349
+
350
+ /**
351
+ * Error thrown when condition evaluation fails
352
+ * @public
353
+ */
354
+ export declare class ConditionEvaluationError extends Error {
355
+ readonly expression?: string | undefined;
356
+ readonly cause?: Error | undefined;
357
+ constructor(message: string, expression?: string | undefined, cause?: Error | undefined);
358
+ }
359
+
360
+ /**
361
+ * Condition evaluator service for parsing and executing conditional expressions
362
+ * @public
363
+ */
364
+ export declare class ConditionEvaluator {
365
+ private customEvaluator?;
366
+ private functionCache;
367
+ private maxCacheSize;
368
+ private expressionCache;
369
+ private maxExpressionCacheSize;
370
+ private contextPool;
371
+ private maxContextPoolSize;
372
+ private poolingEnabled;
373
+ /** @internal Enable/disable context pooling (engine toggles in perf mode) */
374
+ enablePooling(enable: boolean): void;
375
+ /** @internal Adjust pool cap during tuning */
376
+ setMaxContextPoolSize(size: number): void;
377
+ /**
378
+ * Set a custom evaluator function for handling complex conditions
379
+ */
380
+ setCustomEvaluator(evaluator: CustomEvaluatorFunction): void;
381
+ /**
382
+ * Clear the custom evaluator
383
+ */
384
+ clearCustomEvaluator(): void;
385
+ /**
386
+ * Evaluate a condition expression against the provided context
387
+ */
388
+ evaluate(expression: string, context: ConditionContext): boolean;
389
+ /**
390
+ * Built-in expression evaluator with support for common patterns
391
+ */
392
+ private evaluateBuiltIn;
393
+ /**
394
+ * Sanitize expression to prevent code injection
395
+ */
396
+ private sanitizeExpression;
397
+ /** Normalize + intern expression with LRU retention */
398
+ private internAndNormalize;
399
+ /**
400
+ * Create a safe evaluation context from the condition context
401
+ */
402
+ private createEvaluationContext;
403
+ private releaseEvaluationContext;
404
+ /**
405
+ * Validate that an expression is syntactically correct without evaluating it
406
+ */
407
+ validateExpression(expression: string): {
408
+ valid: boolean;
409
+ error?: string;
410
+ };
411
+ /**
412
+ * Get list of flag names referenced in an expression
413
+ */
414
+ getReferencedFlags(expression: string): string[];
415
+ }
416
+
417
+ /** @public */
418
+ export declare const conditionEvaluator: ConditionEvaluator;
419
+
420
+ /**
421
+ * Built-in console adapter (dev-friendly pretty print)
422
+ * @beta
423
+ * @experimental
424
+ */
425
+ export declare class ConsoleAdapter implements TelemetryAdapter {
426
+ configure(): void;
427
+ send(batch: QEvent[]): Promise<void>;
428
+ }
429
+
430
+ /**
431
+ * Factory function to create a QNCE engine instance
432
+ */
433
+ /**
434
+ * Factory to create a QNCE engine instance.
435
+ * @public
436
+ */
437
+ export declare function createQNCEEngine(storyData: StoryData, initialState?: Partial<QNCEState>, performanceMode?: boolean, threadPoolConfig?: Partial<ThreadPoolConfig>, options?: {
438
+ telemetry?: Telemetry;
439
+ env?: 'dev' | 'test' | 'prod';
440
+ appVersion?: string;
441
+ sessionId?: string;
442
+ suppressTelemetryWarnings?: boolean;
443
+ logger?: Logger;
444
+ minimalTelemetry?: boolean;
445
+ }): QNCEEngine;
446
+
447
+ /**
448
+ * Core factory – always returns a StructuredQNCEError.
449
+ * Prefer this over direct `new QNCEError` when emitting from engine internals.
450
+ * @public
451
+ */
452
+ export declare function createStructuredError(kind: QNCEErrorKind, message: string, context?: QNCEErrorContext): StructuredQNCEError;
453
+
454
+ /**
455
+ * Create a telemetry instance; pass adapter + options
456
+ * @beta
457
+ * @experimental
458
+ */
459
+ export declare function createTelemetry(options: TelemetryOptions): Telemetry;
460
+
461
+ /**
462
+ * Factory for built-in telemetry adapters
463
+ * @beta
464
+ * @experimental
465
+ */
466
+ export declare function createTelemetryAdapter(kind: 'console' | 'file', opts?: {
467
+ path?: string;
468
+ }): TelemetryAdapter;
469
+
470
+ /**
471
+ * Custom evaluator function signature
472
+ * @public
473
+ */
474
+ export declare type CustomEvaluatorFunction = (expression: string, context: ConditionContext) => boolean;
475
+
476
+ /** Lightweight ring-buffer debug logger (opt-in at runtime). */
477
+ declare interface DebugLogEntry {
478
+ ts: number;
479
+ level: 'debug';
480
+ event: string;
481
+ data?: Record<string, unknown>;
482
+ }
483
+
484
+ /** @public */
485
+ export declare const DEMO_STORY: StoryData;
486
+
487
+ /**
488
+ * Dynamic branching operations for runtime story modification
489
+ */
490
+ declare interface DynamicBranchOperation {
491
+ type: 'insert' | 'remove' | 'modify';
492
+ branchId: string;
493
+ targetLocation: BranchLocation;
494
+ payload?: Partial<BranchPoint>;
495
+ conditions?: BranchCondition[];
496
+ }
497
+
498
+ /** Engine hook context */
499
+ /** @public */
500
+ export declare interface EngineHookContext {
501
+ engine: QNCEEngine;
502
+ node: NarrativeNode;
503
+ choice?: Choice;
504
+ }
505
+
506
+ /** @beta @experimental */
507
+ export declare class Entangler<TKey extends string = string> {
508
+ private bindings;
509
+ bind(from: TKey, to: TKey, transform?: TransformFn): this;
510
+ apply(flags: Record<string, unknown>): void;
511
+ }
512
+
513
+ /** @beta @experimental */
514
+ export declare type EntangleTransform = (value: unknown) => unknown;
515
+
516
+ /**
517
+ * Environment identifier for telemetry context
518
+ * @beta
519
+ * @experimental
520
+ */
521
+ declare type Env = 'dev' | 'test' | 'prod';
522
+
523
+ /**
524
+ * Convenience helpers by category
525
+ * @public
526
+ */
527
+ export declare const ErrorFactory: {
528
+ navigation: (msg: string, ctx?: QNCEErrorContext) => StructuredQNCEError;
529
+ choiceValidation: (msg: string, ctx?: QNCEErrorContext) => StructuredQNCEError;
530
+ storyData: (msg: string, ctx?: QNCEErrorContext) => StructuredQNCEError;
531
+ state: (msg: string, ctx?: QNCEErrorContext) => StructuredQNCEError;
532
+ hook: (msg: string, ctx?: QNCEErrorContext) => StructuredQNCEError;
533
+ condition: (msg: string, ctx?: QNCEErrorContext) => StructuredQNCEError;
534
+ persistence: (msg: string, ctx?: QNCEErrorContext) => StructuredQNCEError;
535
+ telemetry: (msg: string, ctx?: QNCEErrorContext) => StructuredQNCEError;
536
+ adapter: (msg: string, ctx?: QNCEErrorContext) => StructuredQNCEError;
537
+ unknown: (msg: string, ctx?: QNCEErrorContext) => StructuredQNCEError;
538
+ };
539
+
540
+ /** @beta @experimental */
541
+ export declare type FeatureFlagKey = string;
542
+
543
+ /** @beta @experimental */
544
+ export declare class FeatureFlags {
545
+ private flags;
546
+ constructor(initial?: FeatureFlagsConfig);
547
+ enable(flag: string): void;
548
+ disable(flag: string): void;
549
+ isEnabled(flag: string): boolean;
550
+ getAll(): {
551
+ [x: string]: boolean;
552
+ };
553
+ }
554
+
555
+ /**
556
+ * Feature flags utility to gate experimental behavior
557
+ * @beta
558
+ * @experimental
559
+ */
560
+ /**
561
+ * @beta
562
+ * @experimental
563
+ */
564
+ export declare type FeatureFlagsConfig = {
565
+ [flag: string]: boolean;
566
+ };
567
+
568
+ /**
569
+ * File adapter writing newline-delimited JSON events
570
+ * @beta
571
+ * @experimental
572
+ */
573
+ export declare class FileAdapter implements TelemetryAdapter {
574
+ private opts;
575
+ private stream;
576
+ constructor(opts: FileAdapterOptions);
577
+ send(batch: QEvent[]): Promise<void>;
578
+ flush(): Promise<void>;
579
+ dispose(): Promise<void>;
580
+ }
581
+
582
+ declare interface FileAdapterOptions {
583
+ path: string;
584
+ rotateBytes?: number;
585
+ }
586
+
587
+ declare interface FlowEntryPoint {
588
+ id: string;
589
+ nodeId: string;
590
+ conditions?: BranchCondition[];
591
+ priority: number;
592
+ }
593
+
594
+ /** Flow event captured during narrative traversal */
595
+ /** @public */
596
+ export declare interface FlowEvent {
597
+ id: string;
598
+ fromNodeId: string;
599
+ toNodeId: string;
600
+ timestamp: number;
601
+ metadata?: Record<string, unknown>;
602
+ }
603
+
604
+ declare interface FlowExitPoint {
605
+ id: string;
606
+ nodeId: string;
607
+ targetFlowId?: string;
608
+ conditions?: BranchCondition[];
609
+ }
610
+
611
+ declare interface FlowMetadata {
612
+ complexity: number;
613
+ avgCompletionTime: number;
614
+ playerChoiceCount: number;
615
+ aiGeneratedContent: boolean;
616
+ }
617
+
618
+ declare type FlowType = 'linear' | 'branching' | 'conditional' | 'procedural';
619
+
620
+ /**
621
+ * @beta
622
+ */
623
+ export declare function getPerfReporter(config?: Partial<PerfReporterConfig>): PerfReporter;
624
+
625
+ /**
626
+ * History summary for undo/redo state
627
+ * @public
628
+ */
629
+ export declare interface HistorySummary {
630
+ undoCount: number;
631
+ redoCount: number;
632
+ canUndo: boolean;
633
+ canRedo: boolean;
634
+ }
635
+
636
+ /** Hook execution stage for errors arising inside hooks */
637
+ /** @public */
638
+ export declare type HookStage = 'pre-choice' | 'post-choice';
639
+
640
+ /**
641
+ * Keyboard shortcuts configuration
642
+ * @public
643
+ */
644
+ export declare interface KeyboardShortcutsConfig {
645
+ /** Enable/disable keyboard shortcuts */
646
+ enabled?: boolean;
647
+ /** Custom key bindings */
648
+ bindings?: {
649
+ undo?: string[];
650
+ redo?: string[];
651
+ save?: string[];
652
+ reset?: string[];
653
+ };
654
+ /** Prevent default browser behavior */
655
+ preventDefault?: boolean;
656
+ /** Element to attach listeners to (defaults to document) */
657
+ target?: HTMLElement | Document;
658
+ }
659
+
660
+ /**
661
+ * Options for state loading/deserialization
662
+ */
663
+ declare interface LoadOptions {
664
+ /** Verify checksum integrity before loading */
665
+ verifyChecksum?: boolean;
666
+ /** Skip compatibility checks (dangerous) */
667
+ skipCompatibilityCheck?: boolean;
668
+ /** Restore performance state */
669
+ restorePerformanceState?: boolean;
670
+ /** Restore flow events */
671
+ restoreFlowEvents?: boolean;
672
+ /** Restore branching context */
673
+ restoreBranchingContext?: boolean;
674
+ /** Restore validation state */
675
+ restoreValidationState?: boolean;
676
+ /** Migration function for version compatibility */
677
+ migrationFunction?: (serializedState: SerializedState) => SerializedState;
678
+ }
679
+
680
+ /**
681
+ * Load story data from JSON
682
+ */
683
+ /**
684
+ * Load and validate StoryData from JSON-like input.
685
+ * @public
686
+ */
687
+ export declare function loadStoryData(jsonData: unknown): StoryData;
688
+
689
+ declare interface Logger {
690
+ level: LogLevelName;
691
+ setLevel(lvl: LogLevelName): void;
692
+ error(msg: string): void;
693
+ warn(msg: string): void;
694
+ info(msg: string): void;
695
+ success(msg: string): void;
696
+ debug(msg: string): void;
697
+ child(pfx: string): Logger;
698
+ }
699
+
700
+ /** Lightweight logger with level filtering and pluggable sink (no external deps). */
701
+ declare type LogLevelName = 'silent' | 'error' | 'warn' | 'info' | 'success' | 'debug';
702
+
703
+ /** @beta @experimental */
704
+ export declare class Measurement {
705
+ readonly name: string;
706
+ private sampler?;
707
+ private trials;
708
+ private successes;
709
+ constructor(name: string, sampler?: Sampler);
710
+ sample(ctx?: MeasurementContext): boolean;
711
+ getStats(): {
712
+ trials: number;
713
+ successes: number;
714
+ rate: number;
715
+ };
716
+ }
717
+
718
+ /** @beta @experimental */
719
+ export declare type MeasurementContext = {
720
+ flags: Record<string, unknown>;
721
+ nodeId?: string;
722
+ };
723
+
724
+ declare interface NarrativeContext {
725
+ currentTone: string;
726
+ thematicElements: string[];
727
+ characterRelationships: Record<string, number>;
728
+ plotTension: number;
729
+ }
730
+
731
+ /**
732
+ * NarrativeFlow: Sequence of connected nodes with entry/exit points
733
+ */
734
+ declare interface NarrativeFlow {
735
+ id: string;
736
+ name: string;
737
+ description?: string;
738
+ nodes: NarrativeNode[];
739
+ entryPoints: FlowEntryPoint[];
740
+ exitPoints: FlowExitPoint[];
741
+ flowType: FlowType;
742
+ metadata: FlowMetadata;
743
+ }
744
+
745
+ /** Story node containing narrative text and available choices */
746
+ /** @public */
747
+ export declare interface NarrativeNode {
748
+ id: string;
749
+ text: string;
750
+ choices: Choice[];
751
+ meta?: {
752
+ tags?: string[];
753
+ };
754
+ }
755
+
756
+ declare interface PendingBranch {
757
+ id: string;
758
+ branchPointId: string;
759
+ triggerConditions: BranchCondition[];
760
+ timeoutMs?: number;
761
+ createdAt: Date;
762
+ }
763
+
764
+ declare interface PerfEvent {
765
+ id: string;
766
+ type: 'flow-start' | 'flow-complete' | 'cache-hit' | 'cache-miss' | 'hot-reload-start' | 'hot-reload-end' | 'state-transition' | 'custom';
767
+ timestamp: number;
768
+ duration?: number;
769
+ metadata: Record<string, unknown>;
770
+ category: 'engine' | 'cache' | 'hot-reload' | 'user' | 'system';
771
+ }
772
+
773
+ /**
774
+ * Flush metrics snapshot returned by getPerfFlushMetrics().
775
+ * Designed to be immutable from consumer perspective (frozen object returned).
776
+ */
777
+ /**
778
+ * @beta
779
+ */
780
+ export declare interface PerfFlushMetrics {
781
+ totalFlushAttempts: number;
782
+ successfulFlushes: number;
783
+ rejectedFlushes: number;
784
+ rejectedFlushesSinceLastSuccess?: number;
785
+ totalBatchesDispatched: number;
786
+ totalEventsDispatched: number;
787
+ lastFlushDurationMs: number;
788
+ avgEventsPerBatch: number;
789
+ p50DispatchLatencyMs: number;
790
+ p95DispatchLatencyMs: number;
791
+ smoothedP95DispatchLatencyMs?: number;
792
+ histogramBuckets: ReadonlyArray<{
793
+ upperBoundMs: number;
794
+ count: number;
795
+ }>;
796
+ rejectionRate: number;
797
+ lastEffectiveBatchSize?: number;
798
+ lastUpdated: number;
799
+ adaptiveEnabled: boolean;
800
+ backoffActive?: boolean;
801
+ consecutiveRejects?: number;
802
+ backoffDelayMs?: number;
803
+ }
804
+
805
+ /**
806
+ * PerfReporter - Batched performance event collection and analysis
807
+ * Designed to work off main thread for minimal performance impact
808
+ */
809
+ declare class PerfReporter {
810
+ private events;
811
+ private config;
812
+ private flushTimer;
813
+ private nextAllowedFlushTime;
814
+ private consecutiveRejects;
815
+ private backoffDelayMs;
816
+ private startTime;
817
+ private activeSpans;
818
+ private sampler;
819
+ private metrics;
820
+ private static readonly MAX_LATENCY_SAMPLES;
821
+ constructor(config?: Partial<PerfReporterConfig>);
822
+ /**
823
+ * Internal override hook for tests to inject a deterministic thread pool implementation.
824
+ * Not part of public API surface; subject to change without notice.
825
+ */
826
+ private static __threadPoolOverride;
827
+ static __setThreadPoolOverride(override: {
828
+ writeTelemetry: (payload: unknown) => Promise<unknown>;
829
+ } | null): void;
830
+ /**
831
+ * Record a performance event
832
+ */
833
+ record(type: PerfEvent['type'], metadata?: Record<string, unknown>, category?: PerfEvent['category']): string;
834
+ /**
835
+ * Start a performance span (for measuring duration)
836
+ */
837
+ startSpan(type: PerfEvent['type'], metadata?: Record<string, unknown>, category?: PerfEvent['category']): string;
838
+ /**
839
+ * End a performance span and record the complete event
840
+ */
841
+ endSpan(spanId: string, additionalMetadata?: Record<string, unknown>): void;
842
+ /**
843
+ * Record flow start event (S2-T4 requirement)
844
+ */
845
+ recordFlowStart(nodeId: string, metadata?: Record<string, unknown>): string;
846
+ /**
847
+ * Record flow completion event (S2-T4 requirement)
848
+ */
849
+ recordFlowComplete(spanId: string, nextNodeId: string, metadata?: Record<string, unknown>): void;
850
+ /**
851
+ * Record cache hit event (S2-T4 requirement)
852
+ */
853
+ recordCacheHit(cacheKey: string, metadata?: Record<string, unknown>): string;
854
+ /**
855
+ * Record cache miss event (S2-T4 requirement)
856
+ */
857
+ recordCacheMiss(cacheKey: string, metadata?: Record<string, unknown>): string;
858
+ /**
859
+ * Record hot-reload start event (S2-T4 requirement)
860
+ */
861
+ recordHotReloadStart(deltaSize: number, metadata?: Record<string, unknown>): string;
862
+ /**
863
+ * Record hot-reload completion event (S2-T4 requirement)
864
+ */
865
+ recordHotReloadEnd(spanId: string, success: boolean, metadata?: Record<string, unknown>): void;
866
+ /**
867
+ * Generate performance summary for CLI dashboard
868
+ */
869
+ summary(): PerfSummary;
870
+ /**
871
+ * Get raw events for detailed analysis
872
+ */
873
+ getEvents(): PerfEvent[];
874
+ /**
875
+ * Clear event history
876
+ */
877
+ clear(): void;
878
+ /**
879
+ * Flush events to background processing
880
+ */
881
+ flush(): void;
882
+ /**
883
+ * Start automatic flush timer
884
+ */
885
+ private startFlushTimer;
886
+ /**
887
+ * Stop automatic flush timer
888
+ */
889
+ stopFlushTimer(): void;
890
+ /** Dispose reporter (stop timers) */
891
+ dispose(): void;
892
+ /**
893
+ * Generate unique event ID
894
+ */
895
+ private generateEventId;
896
+ /** Internal: record dispatch latency after counters were eagerly incremented */
897
+ private recordDispatchSuccessPostLatency;
898
+ /** Internal: record dispatch failure */
899
+ private recordDispatchFailure;
900
+ /** Compute derived metrics (avg, percentiles) */
901
+ private recomputeDerivedMetrics;
902
+ /** Public snapshot accessor (frozen copy) */
903
+ getFlushMetrics(): PerfFlushMetrics;
904
+ /** @internal Debug accessor for tests (not part of public API surface) */
905
+ __getInternalPerfDebug(): {
906
+ consecutiveRejects: number;
907
+ backoffDelayMs: number;
908
+ nextAllowedFlushTime: number;
909
+ lastEffectiveBatchSize: number;
910
+ };
911
+ /** @internal Inject a synthetic dispatch latency sample (test helper) */
912
+ __injectLatencySample(latencyMs: number): void;
913
+ }
914
+
915
+ declare interface PerfReporterConfig {
916
+ batchSize: number;
917
+ flushInterval: number;
918
+ enableBackgroundFlush: boolean;
919
+ maxEventHistory: number;
920
+ enableConsoleOutput: boolean;
921
+ disableAdaptiveBatch?: boolean;
922
+ smoothingAlpha?: number;
923
+ }
924
+
925
+ declare interface PerfSummary {
926
+ totalEvents: number;
927
+ eventsByType: Record<string, number>;
928
+ avgDurations: Record<string, number>;
929
+ maxDurations: Record<string, number>;
930
+ minDurations: Record<string, number>;
931
+ cacheHitRate: number;
932
+ hotReloadPerformance: {
933
+ avgTime: number;
934
+ maxTime: number;
935
+ totalReloads: number;
936
+ };
937
+ timeRange: {
938
+ start: number;
939
+ end: number;
940
+ duration: number;
941
+ };
942
+ }
943
+
944
+ /**
945
+ * State persistence result with success/error information
946
+ */
947
+ declare interface PersistenceResult {
948
+ /** Whether the operation succeeded */
949
+ success: boolean;
950
+ /** Error message if operation failed */
951
+ error?: string;
952
+ /** Operation-specific data */
953
+ data?: {
954
+ /** Serialized state size in bytes */
955
+ size?: number;
956
+ /** Compression ratio achieved */
957
+ compressionRatio?: number;
958
+ /** Checksum of saved data */
959
+ checksum?: string;
960
+ /** Time taken for operation (ms) */
961
+ duration?: number;
962
+ };
963
+ /** Warnings or informational messages */
964
+ warnings?: string[];
965
+ }
966
+
967
+ /** @beta @experimental */
968
+ export declare class Phase {
969
+ readonly name: string;
970
+ when?: PhasePredicate_2 | undefined;
971
+ constructor(name: string, when?: PhasePredicate_2 | undefined);
972
+ isActive(ctx: PhaseContext): boolean;
973
+ }
974
+
975
+ /**
976
+ * Phase primitive representing a labeled coexistence region
977
+ * @beta
978
+ * @experimental
979
+ */
980
+ /** @beta @experimental */
981
+ export declare interface PhaseContext {
982
+ flags: Record<string, unknown>;
983
+ nodeId?: string;
984
+ }
985
+
986
+ /** @beta @experimental */
987
+ export declare type PhasePredicate = (ctx: PhasePredicateContext) => boolean;
988
+
989
+ /** @beta @experimental */
990
+ declare type PhasePredicate_2 = (ctx: PhaseContext) => boolean;
991
+
992
+ /** @beta @experimental */
993
+ export declare interface PhasePredicateContext {
994
+ flags: Record<string, unknown>;
995
+ nodeId?: string;
996
+ }
997
+
998
+ declare interface PlayerProfile {
999
+ playStyle: 'explorer' | 'achiever' | 'socializer' | 'killer';
1000
+ preferences: Record<string, number>;
1001
+ historicalChoices: string[];
1002
+ averageDecisionTime: number;
1003
+ }
1004
+
1005
+ /** @public */
1006
+ export declare type PostChoiceHook = (ctx: EngineHookContext) => void;
1007
+
1008
+ /** @public */
1009
+ export declare type PreChoiceHook = (ctx: EngineHookContext) => void | boolean;
1010
+
1011
+ /**
1012
+ * Generic telemetry event shape emitted by the engine
1013
+ * @beta
1014
+ * @experimental
1015
+ */
1016
+ export declare interface QEvent<T extends string = string, P = unknown> {
1017
+ type: T;
1018
+ payload: P;
1019
+ ts: number;
1020
+ ctx: {
1021
+ sessionId: string;
1022
+ storyId?: string;
1023
+ appVersion?: string;
1024
+ engineVersion: string;
1025
+ env?: Env;
1026
+ };
1027
+ meta?: {
1028
+ seq?: number;
1029
+ source?: 'engine' | 'cli' | 'ui';
1030
+ };
1031
+ }
1032
+
1033
+ /**
1034
+ * QNCE Branching Engine - Core API for dynamic narrative branching
1035
+ * Simplified implementation focusing on core functionality
1036
+ */
1037
+ declare class QNCEBranchingEngine {
1038
+ private story;
1039
+ private context;
1040
+ private aiContext?;
1041
+ constructor(story: QNCEStory, initialState: QNCEState);
1042
+ /**
1043
+ * Evaluate available branches from current position
1044
+ */
1045
+ evaluateAvailableBranches(): Promise<BranchOption[]>;
1046
+ /**
1047
+ * Execute a branch transition
1048
+ */
1049
+ executeBranch(optionId: string): Promise<boolean>;
1050
+ /**
1051
+ * Dynamic branch insertion at runtime
1052
+ */
1053
+ insertDynamicBranch(operation: DynamicBranchOperation): Promise<boolean>;
1054
+ /**
1055
+ * Remove dynamic branch
1056
+ */
1057
+ removeDynamicBranch(branchId: string): Promise<boolean>;
1058
+ /**
1059
+ * Set AI context for enhanced branching decisions
1060
+ */
1061
+ setAIContext(aiContext: AIBranchingContext): void;
1062
+ /**
1063
+ * Generate AI-driven branch options
1064
+ */
1065
+ generateAIBranches(maxOptions?: number): Promise<BranchOption[]>;
1066
+ /**
1067
+ * Get current branching analytics
1068
+ */
1069
+ getBranchingAnalytics(): {
1070
+ currentChapter: string;
1071
+ currentFlow: string;
1072
+ historyLength: number;
1073
+ pendingBranches: number;
1074
+ totalBranchesTraversed: number;
1075
+ avgBranchDecisionTime: number;
1076
+ mostPopularBranches: string[];
1077
+ abandonmentPoints: string[];
1078
+ completionRate: number;
1079
+ sessionStartTime: Date;
1080
+ };
1081
+ /**
1082
+ * Export branching data for external analysis
1083
+ */
1084
+ exportBranchingData(): {
1085
+ story: {
1086
+ id: string;
1087
+ title: string;
1088
+ version: string;
1089
+ };
1090
+ session: {
1091
+ startTime: Date;
1092
+ currentState: QNCEState;
1093
+ branchHistory: BranchHistoryEntry[];
1094
+ analytics: BranchAnalytics;
1095
+ };
1096
+ };
1097
+ private createBranchContext;
1098
+ private getCurrentNode;
1099
+ private findBranchPointsForNode;
1100
+ private evaluateConditions;
1101
+ private evaluateCondition;
1102
+ private findBranchOption;
1103
+ private findFlow;
1104
+ private findChapter;
1105
+ private transitionToFlow;
1106
+ private recordBranchHistory;
1107
+ private updateBranchAnalytics;
1108
+ }
1109
+
1110
+ /**
1111
+ * QNCE Engine - Core narrative state management
1112
+ * Framework agnostic implementation with object pooling integration
1113
+ */
1114
+ /**
1115
+ * Main engine class.
1116
+ * @public
1117
+ */
1118
+ export declare class QNCEEngine {
1119
+ private state;
1120
+ storyData: StoryData;
1121
+ private activeFlowEvents;
1122
+ private performanceMode;
1123
+ private enableProfiling;
1124
+ private debugMode;
1125
+ private branchingEngine?;
1126
+ private choiceValidator;
1127
+ private checkpoints;
1128
+ private maxCheckpoints;
1129
+ private autoCheckpointEnabled;
1130
+ private flagKeyPool;
1131
+ private flagValuePool;
1132
+ private internFlagKey;
1133
+ private internFlagValue;
1134
+ private checkpointManager?;
1135
+ private undoStack;
1136
+ private redoStack;
1137
+ private autosaveConfig;
1138
+ private undoRedoConfig;
1139
+ private lastAutosaveTime;
1140
+ private isUndoRedoOperation;
1141
+ private storageAdapter?;
1142
+ private storageRetryPolicy;
1143
+ private telemetry?;
1144
+ private defaultTelemetryCtx?;
1145
+ private preChoiceHooks;
1146
+ private postChoiceHooks;
1147
+ private hookCounter;
1148
+ private logger;
1149
+ private engineOptions?;
1150
+ private minimalTelemetry;
1151
+ get flags(): Record<string, unknown>;
1152
+ get history(): string[];
1153
+ /** Access the engine logger (public read-only) */
1154
+ getLogger(): Logger;
1155
+ get isComplete(): boolean;
1156
+ constructor(storyData: StoryData, initialState?: Partial<QNCEState>, performanceMode?: boolean, threadPoolConfig?: Partial<ThreadPoolConfig>, options?: {
1157
+ telemetry?: Telemetry;
1158
+ env?: 'dev' | 'test' | 'prod';
1159
+ appVersion?: string;
1160
+ sessionId?: string;
1161
+ logger?: Logger;
1162
+ suppressTelemetryWarnings?: boolean;
1163
+ minimalTelemetry?: boolean;
1164
+ });
1165
+ /**
1166
+ * Dispose engine resources (telemetry, performance reporter, background thread pool in perf mode)
1167
+ * @public
1168
+ */
1169
+ dispose(): Promise<void>;
1170
+ /** Attach a storage adapter for persistence */
1171
+ attachStorageAdapter(adapter: StorageAdapter): void;
1172
+ /**
1173
+ * Configure storage retry policy for transient save failures.
1174
+ * @param policy - Partial policy overriding defaults. Set maxAttempts to 1 to disable retries.
1175
+ * @beta
1176
+ */
1177
+ setStorageRetryPolicy(policy: Partial<{
1178
+ maxAttempts: number;
1179
+ baseDelayMs: number;
1180
+ factor: number;
1181
+ maxDelayMs: number;
1182
+ jitter: boolean;
1183
+ }>): void;
1184
+ private sleep;
1185
+ private computeBackoff;
1186
+ /** Save current state through the attached storage adapter */
1187
+ saveToStorage(key: string, options?: SerializationOptions): Promise<PersistenceResult>;
1188
+ /** Load state from the attached storage adapter */
1189
+ loadFromStorage(key: string, options?: LoadOptions): Promise<PersistenceResult>;
1190
+ /** Delete a stored state via the adapter */
1191
+ deleteFromStorage(key: string): Promise<boolean>;
1192
+ /** List keys from the adapter */
1193
+ listStorageKeys(): Promise<string[]>;
1194
+ /** Check if a key exists via the adapter */
1195
+ storageExists(key: string): Promise<boolean>;
1196
+ /** Clear all stored data via the adapter */
1197
+ clearStorage(): Promise<boolean>;
1198
+ /** Get storage statistics from the adapter */
1199
+ getStorageStats(): Promise<{
1200
+ totalSize: number;
1201
+ keyCount: number;
1202
+ [key: string]: unknown;
1203
+ } | null>;
1204
+ /**
1205
+ * Navigate directly to a specific node by ID
1206
+ * @param nodeId - The ID of the node to navigate to
1207
+ * @throws \{QNCENavigationError\} When nodeId is invalid or not found
1208
+ */
1209
+ goToNodeById(nodeId: string): void;
1210
+ /**
1211
+ * Get the current narrative node
1212
+ * @returns The current node object
1213
+ */
1214
+ getCurrentNode(): NarrativeNode;
1215
+ /**
1216
+ * Get available choices from the current node with validation and conditional filtering
1217
+ * @returns Array of available choices
1218
+ */
1219
+ getAvailableChoices(): Choice[];
1220
+ makeChoice(choiceIndex: number): void;
1221
+ getState(): QNCEState;
1222
+ getFlags(): Record<string, unknown>;
1223
+ setFlag(key: string, value: unknown): void;
1224
+ getHistory(): string[];
1225
+ selectChoice(choice: Choice): void;
1226
+ /** Register a hook */
1227
+ registerHook(type: 'pre-choice', handler: PreChoiceHook, priority?: number): () => void;
1228
+ registerHook(type: 'post-choice', handler: PostChoiceHook, priority?: number): () => void;
1229
+ /** Clear all hooks (testing / reset) */
1230
+ clearHooks(): void;
1231
+ /** Enable verbose debug logging (stored in ring buffer) */
1232
+ enableDebug(): void;
1233
+ disableDebug(): void;
1234
+ getDebugLogs(): DebugLogEntry[];
1235
+ clearDebugLogs(): void;
1236
+ /** Enable aggregated hot path profiling */
1237
+ enableHotProfiling(): void;
1238
+ disableHotProfiling(): void;
1239
+ getHotProfileSummary(): Record<string, {
1240
+ count: number;
1241
+ avgMs: number;
1242
+ maxMs: number;
1243
+ }>;
1244
+ resetHotProfile(): void;
1245
+ /** Flush telemetry (useful before process exit) */
1246
+ flushTelemetry(): Promise<void>;
1247
+ resetNarrative(): void;
1248
+ /**
1249
+ * Load simple state (legacy method for backward compatibility)
1250
+ * @param state - QNCEState to load
1251
+ */
1252
+ loadSimpleState(state: QNCEState): void;
1253
+ /**
1254
+ * Save current engine state to a serialized format
1255
+ * @param options - Serialization options
1256
+ * @returns Promise resolving to serialized state
1257
+ */
1258
+ saveState(options?: SerializationOptions): Promise<SerializedState>;
1259
+ /**
1260
+ * Load engine state from serialized format
1261
+ * @param serializedState - The serialized state to load
1262
+ * @param options - Load options
1263
+ * @returns Promise resolving to persistence result
1264
+ */
1265
+ loadState(serializedState: SerializedState, options?: LoadOptions): Promise<PersistenceResult>;
1266
+ /**
1267
+ * Create a lightweight checkpoint of current state
1268
+ * @param name - Optional checkpoint name
1269
+ * @param options - Checkpoint options
1270
+ * @returns Promise resolving to created checkpoint
1271
+ */
1272
+ createCheckpoint(name?: string, options?: CheckpointOptions): Promise<Checkpoint>;
1273
+ /**
1274
+ * Restore engine state from a checkpoint
1275
+ * @param checkpointId - ID of checkpoint to restore
1276
+ * @returns Promise resolving to persistence result
1277
+ */
1278
+ restoreFromCheckpoint(checkpointId: string): Promise<PersistenceResult>;
1279
+ checkFlag(flagName: string, expectedValue?: unknown): boolean;
1280
+ /**
1281
+ * Get the choice validator instance
1282
+ * @returns The current choice validator
1283
+ */
1284
+ getChoiceValidator(): ChoiceValidator;
1285
+ /**
1286
+ * Validate a specific choice without executing it
1287
+ * @param choice - The choice to validate
1288
+ * @returns Validation result with details
1289
+ */
1290
+ validateChoice(choice: Choice): ValidationResult;
1291
+ /**
1292
+ * Check if a specific choice is valid without executing it
1293
+ * @param choice - The choice to check
1294
+ * @returns True if the choice is valid, false otherwise
1295
+ */
1296
+ isChoiceValid(choice: Choice): boolean;
1297
+ /**
1298
+ * Create a flow event using pooled objects for performance tracking
1299
+ */
1300
+ private createFlowEvent;
1301
+ /**
1302
+ * Record and manage flow events
1303
+ */
1304
+ private recordFlowEvent;
1305
+ /**
1306
+ * Get current flow events (for debugging/monitoring)
1307
+ */
1308
+ getActiveFlows(): FlowEvent[];
1309
+ /**
1310
+ * Get object pool statistics for performance monitoring
1311
+ */
1312
+ getPoolStats(): {
1313
+ flows: {
1314
+ poolSize: number;
1315
+ maxSize: number;
1316
+ created: number;
1317
+ borrowed: number;
1318
+ returned: number;
1319
+ inUse: number;
1320
+ hitRate: number;
1321
+ };
1322
+ nodes: {
1323
+ poolSize: number;
1324
+ maxSize: number;
1325
+ created: number;
1326
+ borrowed: number;
1327
+ returned: number;
1328
+ inUse: number;
1329
+ hitRate: number;
1330
+ };
1331
+ assets: {
1332
+ poolSize: number;
1333
+ maxSize: number;
1334
+ created: number;
1335
+ borrowed: number;
1336
+ returned: number;
1337
+ inUse: number;
1338
+ hitRate: number;
1339
+ };
1340
+ } | null;
1341
+ /**
1342
+ * Return all pooled objects (cleanup method)
1343
+ */
1344
+ private cleanupPools;
1345
+ /**
1346
+ * Preload next possible nodes in background using ThreadPool
1347
+ */
1348
+ preloadNextNodes(choice?: Choice): Promise<void>;
1349
+ /**
1350
+ * Write telemetry data in background using ThreadPool
1351
+ */
1352
+ backgroundTelemetryWrite(eventData: Record<string, unknown>): Promise<void>;
1353
+ /**
1354
+ * Enable advanced branching capabilities for this story
1355
+ * Integrates the QNCE Branching API with the core engine
1356
+ */
1357
+ enableBranching(story: QNCEStory): QNCEBranchingEngine;
1358
+ /**
1359
+ * Get the branching engine if enabled
1360
+ */
1361
+ getBranchingEngine(): QNCEBranchingEngine | undefined;
1362
+ /**
1363
+ * Check if branching is enabled
1364
+ */
1365
+ isBranchingEnabled(): boolean;
1366
+ /**
1367
+ * Sync core engine state with branching engine
1368
+ * Call this when core state changes to keep branching engine updated
1369
+ */
1370
+ syncBranchingState(): void;
1371
+ /**
1372
+ * Disable branching and cleanup resources
1373
+ */
1374
+ disableBranching(): void;
1375
+ /**
1376
+ * Background cache warming for story data
1377
+ */
1378
+ warmCache(): Promise<void>;
1379
+ /**
1380
+ * Deep copy utility for state objects
1381
+ * @param obj - Object to deep copy
1382
+ * @returns Deep copied object
1383
+ */
1384
+ private deepCopy;
1385
+ /**
1386
+ * Generate a hash for the current story data
1387
+ * @returns Story hash string
1388
+ */
1389
+ private generateStoryHash;
1390
+ /**
1391
+ * Generate a unique checkpoint ID
1392
+ * @returns Unique checkpoint ID
1393
+ */
1394
+ private generateCheckpointId;
1395
+ /**
1396
+ * Generate checksum for data integrity
1397
+ * @param data - Data to generate checksum for
1398
+ * @returns Promise resolving to checksum string
1399
+ */
1400
+ private generateChecksum;
1401
+ /**
1402
+ * Verify checksum integrity
1403
+ * @param serializedState - State with checksum to verify
1404
+ * @returns Promise resolving to verification result
1405
+ */
1406
+ private verifyChecksum;
1407
+ /**
1408
+ * Validate the structure of the serialized state object
1409
+ * @param serializedState - State to validate
1410
+ * @returns Validation result
1411
+ */
1412
+ private validateSerializedState;
1413
+ /**
1414
+ * Check version compatibility
1415
+ * @param metadata - Serialization metadata
1416
+ * @returns Compatibility check result
1417
+ */
1418
+ private checkCompatibility;
1419
+ /**
1420
+ * Cleanup old checkpoints based on strategy
1421
+ * @param strategy - Cleanup strategy
1422
+ * @param maxCheckpoints - Maximum number of checkpoints to keep
1423
+ * @returns Promise resolving to number of cleaned checkpoints
1424
+ */
1425
+ private cleanupCheckpoints;
1426
+ /**
1427
+ * Get all checkpoints
1428
+ * @returns Array of all checkpoints
1429
+ */
1430
+ getCheckpoints(): Checkpoint[];
1431
+ /**
1432
+ * Get specific checkpoint by ID
1433
+ * @param id - Checkpoint ID
1434
+ * @returns Checkpoint or undefined
1435
+ */
1436
+ getCheckpoint(id: string): Checkpoint | undefined;
1437
+ /**
1438
+ * Delete a checkpoint
1439
+ * @param id - Checkpoint ID to delete
1440
+ * @returns Whether checkpoint was deleted
1441
+ */
1442
+ deleteCheckpoint(id: string): boolean;
1443
+ /**
1444
+ * Enable/disable automatic checkpointing
1445
+ * @param enabled - Whether to enable auto-checkpointing
1446
+ */
1447
+ setAutoCheckpoint(enabled: boolean): void;
1448
+ /**
1449
+ * Configure autosave settings
1450
+ * @param config - Autosave configuration
1451
+ */
1452
+ configureAutosave(config: Partial<AutosaveConfig>): void;
1453
+ /**
1454
+ * Configure undo/redo settings
1455
+ * @param config - Undo/redo configuration
1456
+ */
1457
+ configureUndoRedo(config: Partial<UndoRedoConfig>): void;
1458
+ /**
1459
+ * Push a state to the undo stack
1460
+ * @param state - State to save
1461
+ * @param action - Action that caused this state change
1462
+ * @param metadata - Optional metadata about the change
1463
+ */
1464
+ private pushToUndoStack;
1465
+ /**
1466
+ * Undo the last operation
1467
+ * @returns Result of undo operation
1468
+ */
1469
+ undo(): UndoRedoResult_2;
1470
+ /**
1471
+ * Redo the last undone operation
1472
+ * @returns Result of redo operation
1473
+ */
1474
+ redo(): UndoRedoResult_2;
1475
+ /**
1476
+ * Check if undo is available
1477
+ * @returns True if undo is possible
1478
+ */
1479
+ canUndo(): boolean;
1480
+ /**
1481
+ * Check if redo is available
1482
+ * @returns True if redo is possible
1483
+ */
1484
+ canRedo(): boolean;
1485
+ /**
1486
+ * Get the number of available undo operations
1487
+ * @returns Number of undo entries
1488
+ */
1489
+ getUndoCount(): number;
1490
+ /**
1491
+ * Get the number of available redo operations
1492
+ * @returns Number of redo entries
1493
+ */
1494
+ getRedoCount(): number;
1495
+ /**
1496
+ * Clear all undo/redo history
1497
+ */
1498
+ clearHistory(): void;
1499
+ /**
1500
+ * Get history summary for debugging
1501
+ * @returns Summary of undo/redo history
1502
+ */
1503
+ getHistorySummary(): {
1504
+ undoEntries: {
1505
+ id: string;
1506
+ timestamp: string;
1507
+ action?: string;
1508
+ }[];
1509
+ redoEntries: {
1510
+ id: string;
1511
+ timestamp: string;
1512
+ action?: string;
1513
+ }[];
1514
+ };
1515
+ /**
1516
+ * Trigger an autosave operation
1517
+ * @param trigger - What triggered the autosave
1518
+ * @param metadata - Optional metadata about the trigger
1519
+ * @returns Promise resolving to autosave result
1520
+ */
1521
+ private triggerAutosave;
1522
+ /**
1523
+ * Manually trigger an autosave
1524
+ * @param metadata - Optional metadata
1525
+ * @returns Promise resolving to autosave result
1526
+ */
1527
+ manualAutosave(metadata?: Record<string, unknown>): Promise<AutosaveResult>;
1528
+ /**
1529
+ * Generate a unique history entry ID
1530
+ * @returns Unique ID string
1531
+ */
1532
+ private generateHistoryId;
1533
+ /**
1534
+ * Set a custom condition evaluator function for complex choice logic
1535
+ * @param evaluator - Custom evaluator function
1536
+ */
1537
+ setConditionEvaluator(evaluator: CustomEvaluatorFunction): void;
1538
+ /**
1539
+ * Clear the custom condition evaluator
1540
+ */
1541
+ clearConditionEvaluator(): void;
1542
+ /**
1543
+ * Validate a condition expression without evaluating it
1544
+ * @param expression - Condition expression to validate
1545
+ * @returns Validation result
1546
+ */
1547
+ validateCondition(expression: string): {
1548
+ valid: boolean;
1549
+ error?: string;
1550
+ };
1551
+ /**
1552
+ * Get flags referenced in a condition expression
1553
+ * @param expression - Condition expression to analyze
1554
+ * @returns Array of flag names referenced
1555
+ */
1556
+ getConditionFlags(expression: string): string[];
1557
+ }
1558
+
1559
+ /**
1560
+ * Base class for all QNCE-specific errors
1561
+ * @public
1562
+ */
1563
+ declare class QNCEError extends Error {
1564
+ readonly errorCode: string;
1565
+ readonly timestamp: number;
1566
+ readonly metadata?: Record<string, unknown>;
1567
+ constructor(message: string, errorCode: string, metadata?: Record<string, unknown>);
1568
+ }
1569
+
1570
+ /** Standardized context captured with every structured error */
1571
+ /** @public */
1572
+ export declare interface QNCEErrorContext {
1573
+ storyId?: string;
1574
+ nodeId?: string;
1575
+ fromNodeId?: string;
1576
+ toNodeId?: string;
1577
+ choiceText?: string;
1578
+ hookStage?: HookStage;
1579
+ adapter?: string;
1580
+ operation?: string;
1581
+ conditionExpression?: string;
1582
+ flagKey?: string;
1583
+ flagValue?: unknown;
1584
+ serialized?: boolean;
1585
+ retryable?: boolean;
1586
+ cause?: unknown;
1587
+ [extra: string]: unknown;
1588
+ }
1589
+
1590
+ /** @public */
1591
+ export declare type QNCEErrorKind = 'navigation' | 'choice-validation' | 'story-data' | 'state' | 'hook' | 'condition' | 'persistence' | 'telemetry' | 'adapter' | 'unknown';
1592
+
1593
+ /**
1594
+ * Error thrown when navigation to a node fails
1595
+ * Used by goToNodeById() and related navigation methods
1596
+ * @public
1597
+ */
1598
+ export declare class QNCENavigationError extends QNCEError {
1599
+ readonly nodeId?: string;
1600
+ constructor(message: string, nodeId?: string, metadata?: Record<string, unknown>);
1601
+ }
1602
+
1603
+ /** Serializable engine state snapshot */
1604
+ /** @public */
1605
+ export declare interface QNCEState {
1606
+ currentNodeId: string;
1607
+ flags: Record<string, unknown>;
1608
+ history: string[];
1609
+ }
1610
+
1611
+ /**
1612
+ * Top-level story container with branching metadata
1613
+ * @public
1614
+ */
1615
+ export declare interface QNCEStory {
1616
+ id: string;
1617
+ title: string;
1618
+ version: string;
1619
+ metadata: StoryMetadata;
1620
+ chapters: Chapter[];
1621
+ branchingConfig: BranchingConfig;
1622
+ }
1623
+
1624
+ /**
1625
+ * Theme configuration for QNCE UI components
1626
+ * @public
1627
+ */
1628
+ export declare interface QNCETheme {
1629
+ colors: {
1630
+ primary: string;
1631
+ secondary: string;
1632
+ success: string;
1633
+ warning: string;
1634
+ error: string;
1635
+ disabled: string;
1636
+ background: string;
1637
+ surface: string;
1638
+ text: string;
1639
+ textSecondary: string;
1640
+ };
1641
+ spacing: {
1642
+ xs: string;
1643
+ sm: string;
1644
+ md: string;
1645
+ lg: string;
1646
+ xl: string;
1647
+ };
1648
+ borderRadius: {
1649
+ sm: string;
1650
+ md: string;
1651
+ lg: string;
1652
+ };
1653
+ typography: {
1654
+ fontFamily: string;
1655
+ fontSize: {
1656
+ sm: string;
1657
+ md: string;
1658
+ lg: string;
1659
+ };
1660
+ fontWeight: {
1661
+ normal: number;
1662
+ medium: number;
1663
+ semibold: number;
1664
+ };
1665
+ };
1666
+ shadows: {
1667
+ sm: string;
1668
+ md: string;
1669
+ lg: string;
1670
+ };
1671
+ }
1672
+
1673
+ /** @beta @experimental */
1674
+ export declare type QuantumIntegration = {
1675
+ isPhaseActive: (phase: Phase, ctx?: {
1676
+ nodeId?: string;
1677
+ }) => boolean;
1678
+ entangle: (configure: (e: Entangler) => Entangler) => void;
1679
+ detach: () => void;
1680
+ flags: FeatureFlags;
1681
+ };
1682
+
1683
+ /** @beta @experimental */
1684
+ export declare type Sampler = (ctx: MeasurementContext) => boolean | number;
1685
+
1686
+ /**
1687
+ * Metadata about the serialization process and compatibility
1688
+ */
1689
+ declare interface SerializationMetadata {
1690
+ /** Engine version that created this serialized state */
1691
+ engineVersion: string;
1692
+ /** Timestamp when the state was serialized (ISO string) */
1693
+ timestamp: string;
1694
+ /** Story identifier/hash for compatibility checking */
1695
+ storyId?: string;
1696
+ /** Custom metadata for application-specific use */
1697
+ customMetadata?: Record<string, unknown>;
1698
+ /** Compression level used (if any) */
1699
+ compression?: 'none' | 'gzip' | 'lz4';
1700
+ /** Checksum for integrity verification */
1701
+ checksum?: string;
1702
+ }
1703
+
1704
+ /**
1705
+ * Options for state serialization
1706
+ */
1707
+ declare interface SerializationOptions {
1708
+ /** Include performance data in serialization */
1709
+ includePerformanceData?: boolean;
1710
+ /** Include flow events in serialization */
1711
+ includeFlowEvents?: boolean;
1712
+ /** Include branching context */
1713
+ includeBranchingContext?: boolean;
1714
+ /** Include validation state */
1715
+ includeValidationState?: boolean;
1716
+ /** Compression to apply */
1717
+ compression?: 'none' | 'gzip' | 'lz4';
1718
+ /** Generate integrity checksum */
1719
+ generateChecksum?: boolean;
1720
+ /** Custom metadata to include */
1721
+ customMetadata?: Record<string, unknown>;
1722
+ /** Pretty print JSON (increases size but improves readability) */
1723
+ prettyPrint?: boolean;
1724
+ }
1725
+
1726
+ /**
1727
+ * Complete serialized state that can be saved/restored
1728
+ * Includes all necessary data to fully reconstruct engine state
1729
+ */
1730
+ declare interface SerializedState {
1731
+ /** Core narrative state (current node, flags, history) */
1732
+ state: QNCEState;
1733
+ /** Active flow events for performance tracking */
1734
+ flowEvents: FlowEvent[];
1735
+ /** Performance and pool statistics snapshot */
1736
+ poolStats?: Record<string, unknown>;
1737
+ /** Branching context and branch state */
1738
+ branchingContext?: {
1739
+ activeBranches: string[];
1740
+ branchStates: Record<string, unknown>;
1741
+ convergencePoints: string[];
1742
+ };
1743
+ /** Validation state and rule overrides */
1744
+ validationState?: {
1745
+ disabledRules: string[];
1746
+ customRules: Record<string, unknown>;
1747
+ validationErrors: string[];
1748
+ };
1749
+ /** Thread pool and background operation state */
1750
+ performanceState?: {
1751
+ performanceMode: boolean;
1752
+ enableProfiling: boolean;
1753
+ backgroundTasks: string[];
1754
+ telemetryData: Record<string, unknown>[];
1755
+ };
1756
+ /** Serialization metadata */
1757
+ metadata: SerializationMetadata;
1758
+ }
1759
+
1760
+ /** Serialize a structured error into a safe plain object for logging or transport */
1761
+ /** @public */
1762
+ export declare function serializeStructuredError(struct: StructuredQNCEError): {
1763
+ code: string;
1764
+ kind: QNCEErrorKind;
1765
+ message: string;
1766
+ timestamp: number;
1767
+ context: {
1768
+ cause: undefined;
1769
+ storyId?: string;
1770
+ nodeId?: string;
1771
+ fromNodeId?: string;
1772
+ toNodeId?: string;
1773
+ choiceText?: string;
1774
+ hookStage?: HookStage;
1775
+ adapter?: string;
1776
+ operation?: string;
1777
+ conditionExpression?: string;
1778
+ flagKey?: string;
1779
+ flagValue?: unknown;
1780
+ serialized?: boolean;
1781
+ retryable?: boolean;
1782
+ };
1783
+ stack: string | undefined;
1784
+ };
1785
+
1786
+ /**
1787
+ * Storage adapter interface for different persistence backends
1788
+ */
1789
+ declare interface StorageAdapter {
1790
+ /** Save serialized state */
1791
+ save(key: string, data: SerializedState, options?: SerializationOptions): Promise<PersistenceResult>;
1792
+ /** Load serialized state */
1793
+ load(key: string, options?: LoadOptions): Promise<SerializedState | null>;
1794
+ /** Delete stored state */
1795
+ delete(key: string): Promise<boolean>;
1796
+ /** List all stored keys */
1797
+ list(): Promise<string[]>;
1798
+ /** Check if key exists */
1799
+ exists(key: string): Promise<boolean>;
1800
+ /** Get storage statistics */
1801
+ getStats(): Promise<{
1802
+ totalSize: number;
1803
+ keyCount: number;
1804
+ [key: string]: unknown;
1805
+ }>;
1806
+ /** Clear all stored data */
1807
+ clear(): Promise<boolean>;
1808
+ }
1809
+
1810
+ /** Full story data input structure */
1811
+ /** @public */
1812
+ export declare interface StoryData {
1813
+ nodes: NarrativeNode[];
1814
+ initialNodeId: string;
1815
+ }
1816
+
1817
+ declare interface StoryMetadata {
1818
+ author: string;
1819
+ description: string;
1820
+ tags: string[];
1821
+ createDate: Date;
1822
+ lastModified: Date;
1823
+ estimatedPlaytime: number;
1824
+ }
1825
+
1826
+ /** Shape returned by factory functions */
1827
+ /** @public */
1828
+ export declare interface StructuredQNCEError {
1829
+ error: QNCEError;
1830
+ kind: QNCEErrorKind;
1831
+ code: string;
1832
+ message: string;
1833
+ timestamp: number;
1834
+ context: QNCEErrorContext;
1835
+ }
1836
+
1837
+ /**
1838
+ * Public telemetry facade used by engine and consumers
1839
+ * @beta
1840
+ * @experimental
1841
+ */
1842
+ export declare interface Telemetry {
1843
+ configure(opts: Partial<TelemetryOptions>): void;
1844
+ emit<T extends string, P>(event: QEvent<T, P>): void;
1845
+ flush(): Promise<void>;
1846
+ stats(): {
1847
+ queued: number;
1848
+ dropped: number;
1849
+ sent: number;
1850
+ lastFlushTs: number | null;
1851
+ p50?: number;
1852
+ p95?: number;
1853
+ };
1854
+ dispose(): Promise<void>;
1855
+ }
1856
+
1857
+ /**
1858
+ * Adapter contract for delivering batched telemetry events
1859
+ * @beta
1860
+ * @experimental
1861
+ */
1862
+ export declare interface TelemetryAdapter {
1863
+ configure?(opts: Record<string, unknown>): void;
1864
+ send(batch: QEvent[]): Promise<void>;
1865
+ flush?(): Promise<void>;
1866
+ dispose?(): Promise<void>;
1867
+ }
1868
+
1869
+ /**
1870
+ * Configuration options for telemetry system
1871
+ * @beta
1872
+ * @experimental
1873
+ */
1874
+ export declare interface TelemetryOptions {
1875
+ adapter: TelemetryAdapter;
1876
+ sampleRate?: number;
1877
+ maxQueue?: number;
1878
+ batchSize?: number;
1879
+ flushIntervalMs?: number;
1880
+ onDrop?: (reason: 'queue_full' | 'filter') => void;
1881
+ enabled?: boolean;
1882
+ defaultCtx?: Partial<QEvent['ctx']>;
1883
+ sampleSeed?: number;
1884
+ /** Overflow strategy when queue is full (default 'drop') */
1885
+ overflowStrategy?: 'drop' | 'drop-oldest' | 'error';
1886
+ }
1887
+
1888
+ declare interface ThreadPoolConfig {
1889
+ maxWorkers: number;
1890
+ queueLimit: number;
1891
+ idleTimeout: number;
1892
+ enableProfiling: boolean;
1893
+ }
1894
+
1895
+ /** Try to unwrap unknown thrown values into a structured error (best effort) */
1896
+ /** @public */
1897
+ export declare function toStructuredError(input: unknown, fallbackMessage?: string): StructuredQNCEError;
1898
+
1899
+ /**
1900
+ * Entangler primitive for declarative variable binding
1901
+ * @beta
1902
+ * @experimental
1903
+ */
1904
+ declare type TransformFn = (value: unknown) => unknown;
1905
+
1906
+ /**
1907
+ * Configuration for undo/redo history
1908
+ */
1909
+ declare interface UndoRedoConfig {
1910
+ /** Whether undo/redo is enabled */
1911
+ enabled: boolean;
1912
+ /** Maximum number of undo entries to keep */
1913
+ maxUndoEntries: number;
1914
+ /** Maximum number of redo entries to keep */
1915
+ maxRedoEntries: number;
1916
+ /** Whether to track flag changes for undo metadata */
1917
+ trackFlagChanges: boolean;
1918
+ /** Whether to track choice text for undo metadata */
1919
+ trackChoiceText: boolean;
1920
+ /** Actions that should create undo entries */
1921
+ trackActions: ('choice' | 'flag-change' | 'state-load' | 'reset' | 'custom')[];
1922
+ }
1923
+
1924
+ /**
1925
+ * UndoRedoControls Component
1926
+ *
1927
+ * Provides accessible undo/redo buttons with real-time state updates,
1928
+ * tooltips, keyboard support, and customizable theming.
1929
+ *
1930
+ * Features:
1931
+ * - Real-time enable/disable based on undo/redo availability
1932
+ * - Accessible with ARIA labels and keyboard navigation
1933
+ * - Customizable themes and layouts
1934
+ * - Integration with QNCE Engine undo/redo system
1935
+ * @public
1936
+ */
1937
+ export declare const UndoRedoControls: React_2.FC<UndoRedoControlsProps>;
1938
+
1939
+ /**
1940
+ * Props for UndoRedoControls component
1941
+ * @public
1942
+ */
1943
+ export declare interface UndoRedoControlsProps {
1944
+ /** QNCE Engine instance */
1945
+ engine: QNCEEngine;
1946
+ /** Custom theme (optional, uses default if not provided) */
1947
+ theme?: Partial<QNCETheme>;
1948
+ /** Additional CSS class name */
1949
+ className?: string;
1950
+ /** Custom styling */
1951
+ style?: React.CSSProperties;
1952
+ /** Disable the controls */
1953
+ disabled?: boolean;
1954
+ /** Show labels on buttons */
1955
+ showLabels?: boolean;
1956
+ /** Custom button labels */
1957
+ labels?: {
1958
+ undo: string;
1959
+ redo: string;
1960
+ };
1961
+ /** Button size variant */
1962
+ size?: 'sm' | 'md' | 'lg';
1963
+ /** Button layout */
1964
+ layout?: 'horizontal' | 'vertical';
1965
+ /** Callback when undo is performed */
1966
+ onUndo?: (result: {
1967
+ success: boolean;
1968
+ description?: string;
1969
+ error?: string;
1970
+ }) => void;
1971
+ /** Callback when redo is performed */
1972
+ onRedo?: (result: {
1973
+ success: boolean;
1974
+ description?: string;
1975
+ error?: string;
1976
+ }) => void;
1977
+ }
1978
+
1979
+ /**
1980
+ * Result type for undo/redo operations
1981
+ * @public
1982
+ */
1983
+ export declare interface UndoRedoResult {
1984
+ success: boolean;
1985
+ description?: string;
1986
+ error?: string;
1987
+ }
1988
+
1989
+ /**
1990
+ * Result of undo/redo operations
1991
+ */
1992
+ declare interface UndoRedoResult_2 {
1993
+ /** Whether the operation succeeded */
1994
+ success: boolean;
1995
+ /** Error message if operation failed */
1996
+ error?: string;
1997
+ /** The state that was restored */
1998
+ restoredState?: QNCEState;
1999
+ /** Information about the restored entry */
2000
+ entry?: {
2001
+ id: string;
2002
+ timestamp: string;
2003
+ action?: string;
2004
+ nodeId?: string;
2005
+ };
2006
+ /** Current undo/redo stack sizes after operation */
2007
+ stackSizes?: {
2008
+ undoCount: number;
2009
+ redoCount: number;
2010
+ };
2011
+ }
2012
+
2013
+ /**
2014
+ * Hook for managing autosave functionality
2015
+ *
2016
+ * Provides control over the autosave system for fine-grained management.
2017
+ *
2018
+ * @param engine - The QNCE Engine instance
2019
+ * @param config - Autosave configuration
2020
+ * @returns Autosave state and actions
2021
+ *
2022
+ * @example
2023
+ * ```tsx
2024
+ * function AutosaveIndicator({ engine }: { engine: QNCEEngine }) {
2025
+ * const { autosave, configure, isEnabled } = useAutosave(engine, {
2026
+ * throttleMs: 200,
2027
+ * triggers: ['choice', 'flag-change']
2028
+ * });
2029
+ *
2030
+ * return (
2031
+ * <div>
2032
+ * <span>Autosave: {isEnabled ? 'ON' : 'OFF'}</span>
2033
+ * <button onClick={autosave}>Save Now</button>
2034
+ * </div>
2035
+ * );
2036
+ * }
2037
+ * ```
2038
+ */
2039
+ /**
2040
+ * React hook enabling autosave behavior with throttle and event triggers.
2041
+ * @public
2042
+ */
2043
+ export declare function useAutosave(engine: QNCEEngine, config?: {
2044
+ throttleMs?: number;
2045
+ triggers?: ('choice' | 'flag-change' | 'state-load' | 'branch-exit' | 'custom')[];
2046
+ enabled?: boolean;
2047
+ }): {
2048
+ autosave: () => Promise<void>;
2049
+ configure: (config: Partial<AutosaveConfig>) => void;
2050
+ isEnabled: boolean;
2051
+ lastAutosave: Date | null;
2052
+ isSaving: boolean;
2053
+ };
2054
+
2055
+ /**
2056
+ * useKeyboardShortcuts Hook
2057
+ *
2058
+ * Provides keyboard shortcuts for common QNCE operations like undo/redo and autosave.
2059
+ *
2060
+ * Features:
2061
+ * - Configurable key bindings
2062
+ * - Support for modifier keys (Ctrl, Alt, Shift, Meta)
2063
+ * - Automatic cleanup on unmount
2064
+ * - Prevention of default browser behavior
2065
+ * - Accessibility-friendly implementation
2066
+ *
2067
+ * Default shortcuts:
2068
+ * - Ctrl+Z / Cmd+Z: Undo
2069
+ * - Ctrl+Y / Cmd+Y / Ctrl+Shift+Z: Redo
2070
+ * - Ctrl+S / Cmd+S: Manual autosave
2071
+ * - Ctrl+R / Cmd+R: Reset narrative (disabled by default)
2072
+ * @public
2073
+ */
2074
+ export declare function useKeyboardShortcuts(engine: QNCEEngine, config?: KeyboardShortcutsConfig): void;
2075
+
2076
+ /**
2077
+ * React hook for QNCE Engine integration
2078
+ *
2079
+ * Provides a complete interface for managing QNCE Engine state in React applications,
2080
+ * including undo/redo functionality, autosave, and automatic re-renders.
2081
+ *
2082
+ * @param engine - The QNCE Engine instance
2083
+ * @param config - Configuration options for the hook
2084
+ * @returns Hook return object with state and actions
2085
+ *
2086
+ * @example
2087
+ * ```tsx
2088
+ * function NarrativeComponent() {
2089
+ * const engine = useMemo(() => createQNCEEngine(DEMO_STORY), []);
2090
+ * const {
2091
+ * currentNode,
2092
+ * availableChoices,
2093
+ * selectChoice,
2094
+ * undo,
2095
+ * redo,
2096
+ * canUndo,
2097
+ * canRedo
2098
+ * } = useQNCE(engine, {
2099
+ * enableUndoRedo: true,
2100
+ * enableAutosave: true,
2101
+ * maxUndoEntries: 50
2102
+ * });
2103
+ *
2104
+ * return (
2105
+ * <div>
2106
+ * <p>{currentNode?.text}</p>
2107
+ *
2108
+ * <div>
2109
+ * {availableChoices.map(choice => (
2110
+ * <button key={choice.text} onClick={() => selectChoice(choice)}>
2111
+ * {choice.text}
2112
+ * </button>
2113
+ * ))}
2114
+ * </div>
2115
+ *
2116
+ * <div>
2117
+ * <button onClick={undo} disabled={!canUndo}>
2118
+ * Undo
2119
+ * </button>
2120
+ * <button onClick={redo} disabled={!canRedo}>
2121
+ * Redo
2122
+ * </button>
2123
+ * </div>
2124
+ * </div>
2125
+ * );
2126
+ * }
2127
+ * ```
2128
+ */
2129
+ /** React integration hook for QNCE engine */
2130
+ /** @public */
2131
+ /** React integration hook for QNCE engine
2132
+ * @public
2133
+ */
2134
+ export declare function useQNCE(engine: QNCEEngine, config?: UseQNCEConfig): UseQNCEReturn;
2135
+
2136
+ /**
2137
+ * Configuration for the useQNCE hook
2138
+ * @public
2139
+ */
2140
+ export declare interface UseQNCEConfig {
2141
+ /** Enable automatic re-renders when state changes */
2142
+ autoUpdate?: boolean;
2143
+ /** Enable undo/redo functionality */
2144
+ enableUndoRedo?: boolean;
2145
+ /** Maximum number of undo operations to track */
2146
+ maxUndoEntries?: number;
2147
+ /** Maximum number of redo operations to track */
2148
+ maxRedoEntries?: number;
2149
+ /** Enable autosave functionality */
2150
+ enableAutosave?: boolean;
2151
+ /** Autosave throttle time in milliseconds */
2152
+ autosaveThrottleMs?: number;
2153
+ }
2154
+
2155
+ /**
2156
+ * Return type for the useQNCE hook
2157
+ * @public
2158
+ */
2159
+ export declare interface UseQNCEReturn {
2160
+ engine: QNCEEngine;
2161
+ currentNode: NarrativeNode | null;
2162
+ availableChoices: Choice[];
2163
+ flags: Record<string, unknown>;
2164
+ selectChoice: (choice: Choice | string) => Promise<void>;
2165
+ setFlag: (key: string, value: unknown) => void;
2166
+ resetNarrative: () => void;
2167
+ undo: () => UndoRedoResult;
2168
+ redo: () => UndoRedoResult;
2169
+ canUndo: boolean;
2170
+ canRedo: boolean;
2171
+ undoCount: number;
2172
+ redoCount: number;
2173
+ clearHistory: () => void;
2174
+ autosave: () => Promise<void>;
2175
+ configureAutosave: (config: Partial<AutosaveConfig>) => void;
2176
+ saveState: () => Promise<SerializedState>;
2177
+ loadState: (serializedState: SerializedState) => Promise<void>;
2178
+ refresh: () => void;
2179
+ }
2180
+
2181
+ /**
2182
+ * Hook for managing just undo/redo functionality
2183
+ *
2184
+ * A lightweight hook focused specifically on undo/redo operations.
2185
+ * Useful when you want to add undo/redo to an existing QNCE integration.
2186
+ *
2187
+ * @param engine - The QNCE Engine instance
2188
+ * @param config - Undo/redo configuration
2189
+ * @returns Undo/redo state and actions
2190
+ *
2191
+ * @example
2192
+ * ```tsx
2193
+ * function UndoRedoControls({ engine }: { engine: QNCEEngine }) {
2194
+ * const { undo, redo, canUndo, canRedo, undoCount, redoCount } = useUndoRedo(engine);
2195
+ *
2196
+ * return (
2197
+ * <div className="undo-redo-controls">
2198
+ * <button onClick={undo} disabled={!canUndo}>
2199
+ * ← Undo ({undoCount})
2200
+ * </button>
2201
+ * <button onClick={redo} disabled={!canRedo}>
2202
+ * Redo ({redoCount}) →
2203
+ * </button>
2204
+ * </div>
2205
+ * );
2206
+ * }
2207
+ * ```
2208
+ */
2209
+ /**
2210
+ * React hook providing undo/redo state and actions for a QNCE engine instance.
2211
+ * @public
2212
+ */
2213
+ export declare function useUndoRedo(engine: QNCEEngine, config?: {
2214
+ maxUndoEntries?: number;
2215
+ maxRedoEntries?: number;
2216
+ }): {
2217
+ undo: () => UndoRedoResult;
2218
+ redo: () => UndoRedoResult;
2219
+ canUndo: boolean;
2220
+ canRedo: boolean;
2221
+ undoCount: number;
2222
+ redoCount: number;
2223
+ clearHistory: () => void;
2224
+ historySummary: HistorySummary;
2225
+ };
2226
+
2227
+ /**
2228
+ * Validation context containing all state needed for choice validation
2229
+ */
2230
+ declare interface ValidationContext {
2231
+ currentNode: NarrativeNode;
2232
+ state: QNCEState;
2233
+ availableChoices: Choice[];
2234
+ timestamp?: number;
2235
+ metadata?: Record<string, unknown>;
2236
+ }
2237
+
2238
+ /**
2239
+ * Result of choice validation with detailed information
2240
+ */
2241
+ declare interface ValidationResult {
2242
+ isValid: boolean;
2243
+ reason?: string;
2244
+ failedConditions?: string[];
2245
+ suggestedChoices?: Choice[];
2246
+ metadata?: Record<string, unknown>;
2247
+ }
2248
+
2249
+ /**
2250
+ * Choice validation rule interface for extensible validation logic
2251
+ */
2252
+ declare interface ValidationRule {
2253
+ name: string;
2254
+ priority: number;
2255
+ validate(choice: Choice, context: ValidationContext): ValidationResult;
2256
+ }
2257
+
2258
+ export { }