@affectively/aeon-pages-runtime 0.1.0

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.
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Aeon Navigation Engine
3
+ *
4
+ * Cutting-edge navigation with:
5
+ * - Speculative prefetching
6
+ * - Total preload capability
7
+ * - View transitions
8
+ * - Presence awareness
9
+ * - Predictive navigation
10
+ */
11
+ import { AeonRouter } from './router.js';
12
+ import { NavigationCache, type CachedSession } from './cache';
13
+ export interface NavigationOptions {
14
+ transition?: 'slide' | 'fade' | 'morph' | 'none';
15
+ replace?: boolean;
16
+ }
17
+ export interface PrefetchOptions {
18
+ data?: boolean;
19
+ presence?: boolean;
20
+ priority?: 'high' | 'normal' | 'low';
21
+ }
22
+ export interface NavigationState {
23
+ current: string;
24
+ previous: string | null;
25
+ history: string[];
26
+ isNavigating: boolean;
27
+ }
28
+ export interface PresenceInfo {
29
+ route: string;
30
+ count: number;
31
+ editing: number;
32
+ hot: boolean;
33
+ users?: {
34
+ userId: string;
35
+ name?: string;
36
+ }[];
37
+ }
38
+ export interface PredictedRoute {
39
+ route: string;
40
+ probability: number;
41
+ reason: 'history' | 'hover' | 'visibility' | 'community';
42
+ }
43
+ type NavigationListener = (state: NavigationState) => void;
44
+ type PresenceListener = (route: string, presence: PresenceInfo) => void;
45
+ export declare class AeonNavigationEngine {
46
+ private router;
47
+ private cache;
48
+ private state;
49
+ private navigationListeners;
50
+ private presenceListeners;
51
+ private presenceCache;
52
+ private navigationHistory;
53
+ private pendingPrefetches;
54
+ private observer;
55
+ private sessionFetcher?;
56
+ private presenceFetcher?;
57
+ constructor(options?: {
58
+ router?: AeonRouter;
59
+ cache?: NavigationCache;
60
+ initialRoute?: string;
61
+ sessionFetcher?: (sessionId: string) => Promise<CachedSession>;
62
+ presenceFetcher?: (route: string) => Promise<PresenceInfo>;
63
+ });
64
+ /**
65
+ * Navigate to a route with optional view transition
66
+ */
67
+ navigate(href: string, options?: NavigationOptions): Promise<void>;
68
+ /**
69
+ * Prefetch a route
70
+ */
71
+ prefetch(href: string, options?: PrefetchOptions): Promise<void>;
72
+ /**
73
+ * Prefetch presence for a route
74
+ */
75
+ prefetchPresence(route: string): Promise<PresenceInfo | null>;
76
+ /**
77
+ * Check if a route is preloaded
78
+ */
79
+ isPreloaded(href: string): boolean;
80
+ /**
81
+ * Get cached presence for a route
82
+ */
83
+ getPresence(route: string): PresenceInfo | null;
84
+ /**
85
+ * Observe links for visibility-based prefetch
86
+ */
87
+ observeLinks(container: Element): () => void;
88
+ /**
89
+ * Predict next navigation destinations
90
+ */
91
+ predict(currentRoute: string): PredictedRoute[];
92
+ /**
93
+ * Go back in navigation history
94
+ */
95
+ back(): Promise<void>;
96
+ /**
97
+ * Get current navigation state
98
+ */
99
+ getState(): NavigationState;
100
+ /**
101
+ * Subscribe to navigation changes
102
+ */
103
+ subscribe(listener: NavigationListener): () => void;
104
+ /**
105
+ * Subscribe to presence changes for a route
106
+ */
107
+ subscribePresence(listener: PresenceListener): () => void;
108
+ /**
109
+ * Preload all routes (total preload strategy)
110
+ */
111
+ preloadAll(onProgress?: (loaded: number, total: number) => void): Promise<void>;
112
+ /**
113
+ * Get cache statistics
114
+ */
115
+ getCacheStats(): import("./cache").CacheStats;
116
+ private getSession;
117
+ private updateDOM;
118
+ private recordNavigation;
119
+ private notifyListeners;
120
+ private notifyPresenceListeners;
121
+ }
122
+ export declare function getNavigator(): AeonNavigationEngine;
123
+ export declare function setNavigator(navigator: AeonNavigationEngine): void;
124
+ export {};
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Aeon Navigation Predictor
3
+ *
4
+ * Predicts where users will navigate next based on:
5
+ * 1. Personal navigation history (Markov chain)
6
+ * 2. Collaborative signals (where is the community going?)
7
+ * 3. Time-based patterns (Monday morning vs Friday afternoon)
8
+ * 4. Content signals (came from search → exploring)
9
+ *
10
+ * The predictor itself is an Aeon entity - it syncs across nodes
11
+ * to build community navigation patterns.
12
+ */
13
+ export interface PredictedRoute {
14
+ route: string;
15
+ probability: number;
16
+ reason: 'history' | 'hover' | 'visibility' | 'community' | 'time' | 'content';
17
+ confidence: number;
18
+ }
19
+ export interface NavigationRecord {
20
+ from: string;
21
+ to: string;
22
+ timestamp: number;
23
+ duration: number;
24
+ source?: 'click' | 'back' | 'forward' | 'direct';
25
+ }
26
+ export interface CommunityPattern {
27
+ route: string;
28
+ popularity: number;
29
+ avgTimeSpent: number;
30
+ nextRoutes: {
31
+ route: string;
32
+ count: number;
33
+ }[];
34
+ }
35
+ export interface PredictorConfig {
36
+ historyWeight: number;
37
+ communityWeight: number;
38
+ timeWeight: number;
39
+ decayFactor: number;
40
+ minProbability: number;
41
+ maxPredictions: number;
42
+ }
43
+ export declare class NavigationPredictor {
44
+ private config;
45
+ private history;
46
+ private transitionMatrix;
47
+ private communityPatterns;
48
+ private timePatterns;
49
+ constructor(config?: Partial<PredictorConfig>);
50
+ /**
51
+ * Record a navigation event
52
+ */
53
+ record(record: NavigationRecord): void;
54
+ /**
55
+ * Predict next navigation destinations from current route
56
+ */
57
+ predict(currentRoute: string): PredictedRoute[];
58
+ /**
59
+ * Predict from personal navigation history (Markov chain)
60
+ */
61
+ private predictFromHistory;
62
+ /**
63
+ * Predict from community patterns
64
+ */
65
+ private predictFromCommunity;
66
+ /**
67
+ * Predict from time-based patterns
68
+ */
69
+ private predictFromTime;
70
+ /**
71
+ * Merge a prediction into the predictions map
72
+ */
73
+ private mergePrediction;
74
+ /**
75
+ * Apply decay to old history records
76
+ */
77
+ private applyDecay;
78
+ /**
79
+ * Update community patterns from external sync
80
+ */
81
+ updateCommunityPatterns(patterns: Map<string, CommunityPattern>): void;
82
+ /**
83
+ * Get current transition matrix (for syncing)
84
+ */
85
+ getTransitionMatrix(): Map<string, Map<string, number>>;
86
+ /**
87
+ * Import transition matrix from sync
88
+ */
89
+ importTransitionMatrix(matrix: Map<string, Map<string, number>>): void;
90
+ /**
91
+ * Get statistics about the predictor
92
+ */
93
+ getStats(): {
94
+ totalRecords: number;
95
+ uniqueRoutes: number;
96
+ transitionPairs: number;
97
+ communityPatterns: number;
98
+ };
99
+ /**
100
+ * Clear all data
101
+ */
102
+ clear(): void;
103
+ /**
104
+ * Export for persistence
105
+ */
106
+ export(): {
107
+ history: NavigationRecord[];
108
+ transitionMatrix: [string, [string, number][]][];
109
+ timePatterns: [string, [number, number][]][];
110
+ };
111
+ /**
112
+ * Import from persistence
113
+ */
114
+ import(data: {
115
+ history?: NavigationRecord[];
116
+ transitionMatrix?: [string, [string, number][]][];
117
+ timePatterns?: [string, [number, number][]][];
118
+ }): void;
119
+ }
120
+ export declare function getPredictor(): NavigationPredictor;
121
+ export declare function setPredictor(predictor: NavigationPredictor): void;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Aeon Route Registry - Collaborative route management
3
+ *
4
+ * Routes are stored as Aeon entities, enabling:
5
+ * - Distributed sync across nodes
6
+ * - Conflict resolution for concurrent route mutations
7
+ * - Schema versioning for route structure changes
8
+ */
9
+ import type { RouteMetadata, RouteOperation } from './types';
10
+ interface RegistryOptions {
11
+ syncMode: 'distributed' | 'local';
12
+ versioningEnabled: boolean;
13
+ }
14
+ interface AeonRoute {
15
+ path: string;
16
+ component: string;
17
+ metadata: RouteMetadata;
18
+ version: string;
19
+ }
20
+ /**
21
+ * Collaborative route registry using Aeon distributed sync
22
+ */
23
+ export declare class AeonRouteRegistry {
24
+ private routes;
25
+ private coordinator;
26
+ private reconciler;
27
+ private versions;
28
+ private syncMode;
29
+ private versioningEnabled;
30
+ private mutationCallbacks;
31
+ private connectedSockets;
32
+ constructor(options: RegistryOptions);
33
+ private initializeAeonModules;
34
+ /**
35
+ * Add a new route collaboratively
36
+ */
37
+ addRoute(path: string, component: string, metadata: RouteMetadata): Promise<void>;
38
+ /**
39
+ * Update an existing route
40
+ */
41
+ updateRoute(path: string, updates: Partial<AeonRoute>): Promise<void>;
42
+ /**
43
+ * Remove a route
44
+ */
45
+ removeRoute(path: string): Promise<void>;
46
+ /**
47
+ * Get a route by path
48
+ */
49
+ getRoute(path: string): AeonRoute | undefined;
50
+ /**
51
+ * Get session ID for a path
52
+ */
53
+ getSessionId(path: string): string;
54
+ /**
55
+ * Get all routes
56
+ */
57
+ getAllRoutes(): AeonRoute[];
58
+ /**
59
+ * Subscribe to route mutations
60
+ */
61
+ subscribeToMutations(callback: (operation: RouteOperation) => void): () => void;
62
+ /**
63
+ * Handle WebSocket connection for Aeon sync
64
+ */
65
+ handleConnect(ws: unknown): void;
66
+ /**
67
+ * Handle WebSocket disconnection
68
+ */
69
+ handleDisconnect(ws: unknown): void;
70
+ /**
71
+ * Handle incoming sync message
72
+ */
73
+ handleSyncMessage(ws: unknown, message: unknown): void;
74
+ private notifyMutation;
75
+ private handleSyncCompleted;
76
+ private applyRemoteOperation;
77
+ private persistRoute;
78
+ }
79
+ export {};
@@ -0,0 +1,31 @@
1
+ /**
2
+ * User Context Extractor
3
+ *
4
+ * Middleware that extracts UserContext from HTTP requests.
5
+ * Gathers signals from headers, cookies, and request properties.
6
+ */
7
+ import type { EmotionState, UserContext, UserTier } from './types';
8
+ export interface ContextExtractorOptions {
9
+ /** Custom emotion detector (e.g., call edge-workers) */
10
+ detectEmotion?: (request: Request) => Promise<EmotionState | undefined>;
11
+ /** Custom user tier resolver (e.g., from database) */
12
+ resolveUserTier?: (userId: string) => Promise<UserTier>;
13
+ /** Additional context enrichment */
14
+ enrich?: (context: UserContext, request: Request) => Promise<UserContext>;
15
+ }
16
+ /**
17
+ * Extract UserContext from an HTTP request
18
+ */
19
+ export declare function extractUserContext(request: Request, options?: ContextExtractorOptions): Promise<UserContext>;
20
+ /**
21
+ * Create middleware for user context extraction
22
+ */
23
+ export declare function createContextMiddleware(options?: ContextExtractorOptions): (request: Request) => Promise<UserContext>;
24
+ /**
25
+ * Set context tracking cookies in response
26
+ */
27
+ export declare function setContextCookies(response: Response, context: UserContext, currentPath: string): Response;
28
+ /**
29
+ * Add speculation hints to response headers
30
+ */
31
+ export declare function addSpeculationHeaders(response: Response, prefetch: string[], prerender: string[]): Response;
@@ -0,0 +1,248 @@
1
+ /**
2
+ * ESI Control Components (React)
3
+ *
4
+ * Control flow, Zod validation, and Presence-aware collaborative ESI.
5
+ *
6
+ * @example
7
+ * ```tsx
8
+ * // Conditional rendering based on inference
9
+ * <ESI.If
10
+ * prompt="Should we show a discount?"
11
+ * schema={z.object({ show: z.boolean(), reason: z.string() })}
12
+ * when={(r) => r.show}
13
+ * >
14
+ * <DiscountBanner />
15
+ * </ESI.If>
16
+ *
17
+ * // Presence-aware collaborative content
18
+ * <ESI.Collaborative
19
+ * schema={z.object({ summary: z.string(), highlights: z.array(z.string()) })}
20
+ * >
21
+ * Summarize this for {presence.length} viewers with roles: {roles}
22
+ * </ESI.Collaborative>
23
+ *
24
+ * // Structured output with Zod
25
+ * <ESI.Structured
26
+ * schema={z.object({
27
+ * sentiment: z.enum(['positive', 'negative', 'neutral']),
28
+ * topics: z.array(z.string()),
29
+ * })}
30
+ * >
31
+ * Analyze: {text}
32
+ * </ESI.Structured>
33
+ * ```
34
+ */
35
+ import { type ReactNode, type JSX } from 'react';
36
+ import type { ZodType, ZodTypeDef } from 'zod';
37
+ import type { PresenceUser } from './types';
38
+ import { type ESICondition } from './esi-control';
39
+ export interface ESIStructuredProps<T> {
40
+ /** The prompt - can be children or explicit prop */
41
+ children?: ReactNode;
42
+ prompt?: string;
43
+ /** Zod schema for output validation */
44
+ schema: ZodType<T, ZodTypeDef, unknown>;
45
+ /** Render function for validated data */
46
+ render?: (data: T, meta: {
47
+ cached: boolean;
48
+ latencyMs: number;
49
+ }) => ReactNode;
50
+ /** Fallback if validation fails */
51
+ fallback?: ReactNode;
52
+ /** Loading state */
53
+ loading?: ReactNode;
54
+ /** Retry on validation failure */
55
+ retryOnFail?: boolean;
56
+ /** Max retries */
57
+ maxRetries?: number;
58
+ /** Additional inference params */
59
+ temperature?: number;
60
+ maxTokens?: number;
61
+ cacheTtl?: number;
62
+ /** Callbacks */
63
+ onSuccess?: (data: T) => void;
64
+ onValidationError?: (errors: string[], rawOutput: string) => void;
65
+ onError?: (error: string) => void;
66
+ /** Class name */
67
+ className?: string;
68
+ }
69
+ export declare function ESIStructured<T>({ children, prompt, schema, render, fallback, loading, retryOnFail, maxRetries, temperature, maxTokens, cacheTtl, onSuccess, onValidationError, onError, className, }: ESIStructuredProps<T>): JSX.Element;
70
+ export interface ESIIfProps<T> {
71
+ /** The prompt to evaluate */
72
+ children?: ReactNode;
73
+ prompt?: string;
74
+ /** Zod schema for the condition evaluation */
75
+ schema: ZodType<T, ZodTypeDef, unknown>;
76
+ /** Condition function - if true, render `then` */
77
+ when: ESICondition<T>;
78
+ /** Content to render if condition is true */
79
+ then: ReactNode;
80
+ /** Content to render if condition is false */
81
+ else?: ReactNode;
82
+ /** Loading state */
83
+ loading?: ReactNode;
84
+ /** Additional params */
85
+ temperature?: number;
86
+ cacheTtl?: number;
87
+ /** Callbacks */
88
+ onEvaluate?: (result: T, conditionMet: boolean) => void;
89
+ /** Class name */
90
+ className?: string;
91
+ }
92
+ export declare function ESIIf<T>({ children, prompt, schema, when, then: thenContent, else: elseContent, loading, temperature, cacheTtl, onEvaluate, className, }: ESIIfProps<T>): JSX.Element | null;
93
+ export interface ESICaseProps<T> {
94
+ /** Match condition */
95
+ match: ESICondition<T>;
96
+ /** Content to render if matched */
97
+ children: ReactNode;
98
+ }
99
+ export declare function ESICase<T>({ children }: ESICaseProps<T>): JSX.Element;
100
+ export interface ESIDefaultProps {
101
+ children: ReactNode;
102
+ }
103
+ export declare function ESIDefault({ children }: ESIDefaultProps): JSX.Element;
104
+ export interface ESIMatchProps<T> {
105
+ /** The prompt to evaluate */
106
+ children: ReactNode;
107
+ prompt?: string;
108
+ /** Zod schema */
109
+ schema: ZodType<T, ZodTypeDef, unknown>;
110
+ /** Loading state */
111
+ loading?: ReactNode;
112
+ /** Additional params */
113
+ temperature?: number;
114
+ cacheTtl?: number;
115
+ /** Callback */
116
+ onMatch?: (data: T, matchedIndex: number) => void;
117
+ /** Class name */
118
+ className?: string;
119
+ }
120
+ export declare function ESIMatch<T>({ children, prompt, schema, loading, temperature, cacheTtl, onMatch, className, }: ESIMatchProps<T>): JSX.Element | null;
121
+ export interface ESICollaborativeProps<T> {
122
+ /** Base prompt - presence info will be injected */
123
+ children?: ReactNode;
124
+ prompt?: string;
125
+ /** Zod schema for output */
126
+ schema: ZodType<T, ZodTypeDef, unknown>;
127
+ /** Custom render function */
128
+ render?: (data: T, presence: PresenceUser[]) => ReactNode;
129
+ /** Fallback content */
130
+ fallback?: ReactNode;
131
+ /** Loading state */
132
+ loading?: ReactNode;
133
+ /** How to describe users in the prompt */
134
+ describeUsers?: (users: PresenceUser[]) => string;
135
+ /** Re-infer when presence changes */
136
+ reactToPresenceChange?: boolean;
137
+ /** Debounce time for presence changes (ms) */
138
+ presenceDebounce?: number;
139
+ /** Additional params */
140
+ temperature?: number;
141
+ maxTokens?: number;
142
+ cacheTtl?: number;
143
+ /** Callbacks */
144
+ onSuccess?: (data: T, presence: PresenceUser[]) => void;
145
+ /** Class name */
146
+ className?: string;
147
+ }
148
+ export declare function ESICollaborative<T>({ children, prompt, schema, render, fallback, loading, describeUsers, reactToPresenceChange, presenceDebounce, temperature, maxTokens, cacheTtl, onSuccess, className, }: ESICollaborativeProps<T>): JSX.Element;
149
+ export interface ESIReflectProps<T> {
150
+ /** The prompt */
151
+ children?: ReactNode;
152
+ prompt?: string;
153
+ /** Schema must include a quality/confidence field */
154
+ schema: ZodType<T, ZodTypeDef, unknown>;
155
+ /** Continue until this condition is met */
156
+ until: (result: T, iteration: number) => boolean;
157
+ /** Max iterations */
158
+ maxIterations?: number;
159
+ /** Custom render */
160
+ render?: (data: T, iterations: number) => ReactNode;
161
+ /** Show intermediate results */
162
+ showProgress?: boolean;
163
+ /** Fallback */
164
+ fallback?: ReactNode;
165
+ /** Loading */
166
+ loading?: ReactNode;
167
+ /** Callbacks */
168
+ onIteration?: (data: T, iteration: number) => void;
169
+ onComplete?: (data: T, totalIterations: number) => void;
170
+ /** Class name */
171
+ className?: string;
172
+ }
173
+ export declare function ESIReflect<T>({ children, prompt, schema, until, maxIterations, render, showProgress, fallback, loading, onIteration, onComplete, className, }: ESIReflectProps<T>): JSX.Element;
174
+ export interface ESIOptimizeProps<T> {
175
+ /** The prompt */
176
+ children?: ReactNode;
177
+ prompt?: string;
178
+ /** Schema for output */
179
+ schema: ZodType<T, ZodTypeDef, unknown>;
180
+ /** Quality criteria to optimize for */
181
+ criteria?: string[];
182
+ /** Target quality score (0-1) */
183
+ targetQuality?: number;
184
+ /** Max optimization rounds */
185
+ maxRounds?: number;
186
+ /** Only optimize when user is alone (no other presence) */
187
+ onlyWhenAlone?: boolean;
188
+ /** Custom render */
189
+ render?: (data: T, meta: OptimizeMeta) => ReactNode;
190
+ /** Fallback */
191
+ fallback?: ReactNode;
192
+ /** Loading */
193
+ loading?: ReactNode;
194
+ /** Callbacks */
195
+ onImprove?: (data: T, round: number, quality: number) => void;
196
+ onOptimized?: (data: T, totalRounds: number, finalQuality: number) => void;
197
+ /** Class name */
198
+ className?: string;
199
+ }
200
+ export interface OptimizeMeta {
201
+ rounds: number;
202
+ quality: number;
203
+ improvements: string[];
204
+ wasOptimized: boolean;
205
+ }
206
+ export declare function ESIOptimize<T>({ children, prompt, schema, criteria, targetQuality, maxRounds, onlyWhenAlone, render, fallback, loading, onImprove, onOptimized, className, }: ESIOptimizeProps<T>): JSX.Element;
207
+ export interface ESIAutoProps<T> {
208
+ /** The prompt */
209
+ children?: ReactNode;
210
+ prompt?: string;
211
+ /** Schema for output */
212
+ schema: ZodType<T, ZodTypeDef, unknown>;
213
+ /** Custom render */
214
+ render?: (data: T, mode: 'collaborative' | 'optimized' | 'basic') => ReactNode;
215
+ /** Minimum users for collaborative mode */
216
+ collaborativeThreshold?: number;
217
+ /** Optimization settings */
218
+ optimizeSettings?: {
219
+ criteria?: string[];
220
+ targetQuality?: number;
221
+ maxRounds?: number;
222
+ };
223
+ /** Fallback */
224
+ fallback?: ReactNode;
225
+ /** Loading */
226
+ loading?: ReactNode;
227
+ /** Class name */
228
+ className?: string;
229
+ }
230
+ /**
231
+ * ESI.Auto - Automatically selects the best mode:
232
+ * - Multiple users → Collaborative (presence-aware)
233
+ * - Single user → Optimize (self-improving)
234
+ * - Quick mode → Basic (fast, single pass)
235
+ */
236
+ export declare function ESIAuto<T>({ children, prompt, schema, render, collaborativeThreshold, optimizeSettings, fallback, loading, className, }: ESIAutoProps<T>): JSX.Element;
237
+ export declare const ESIControl: {
238
+ Structured: typeof ESIStructured;
239
+ If: typeof ESIIf;
240
+ Match: typeof ESIMatch;
241
+ Case: typeof ESICase;
242
+ Default: typeof ESIDefault;
243
+ Collaborative: typeof ESICollaborative;
244
+ Reflect: typeof ESIReflect;
245
+ Optimize: typeof ESIOptimize;
246
+ Auto: typeof ESIAuto;
247
+ };
248
+ export default ESIControl;