Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.report-event.ts

247 lines7.8 KB

1import { createFileRoute } from '@tanstack/react-router'
2import type {
3 HandlerResult,
4 RefreshResult,
5 UIEffect,
6 UIUpdate,
7} from '@/lib/reports/types'
8import {
9 getReportState,
10 applyReportUIUpdates,
11} from '@/lib/reports/report-storage'
12import {
13 createHandlerBindings,
14 getInvalidatedSignals,
15} from '@/lib/reports/create-handler-bindings'
16import { refreshComponent } from '@/lib/reports/refresh-component'
17import { evaluateWatchersForSignals } from '@/lib/reports/evaluate-watchers'
18​
19export const Route = createFileRoute('/_reporting/api/report-event')({
20 server: {
21 handlers: {
22 POST: async ({ request }) => {
23 const body = await request.json()
24 const { reportId, componentId, handlerName, eventData } = body
25​
26 if (!reportId || !componentId || !handlerName) {
27 return new Response(
28 JSON.stringify({
29 error: 'Missing reportId, componentId, or handlerName',
30 }),
31 { status: 400, headers: { 'Content-Type': 'application/json' } },
32 )
33 }
34​
35 const reportState = getReportState(reportId)
36 if (!reportState) {
37 return new Response(JSON.stringify({ error: 'Report not found' }), {
38 status: 404,
39 headers: { 'Content-Type': 'application/json' },
40 })
41 }
42​
43 const component = reportState.nodes.get(componentId)
44 if (!component) {
45 return new Response(
46 JSON.stringify({ error: 'Component not found' }),
47 {
48 status: 404,
49 headers: { 'Content-Type': 'application/json' },
50 },
51 )
52 }
53​
54 const handlerCode = component.handlers?.[handlerName]
55 if (!handlerCode) {
56 return new Response(
57 JSON.stringify({
58 error: `No handler '${handlerName}' on component`,
59 }),
60 { status: 400, headers: { 'Content-Type': 'application/json' } },
61 )
62 }
63​
64 console.log('[HandlerExec] ========================================')
65 console.log('[HandlerExec] Component:', componentId)
66 console.log('[HandlerExec] Handler:', handlerName)
67 console.log('[HandlerExec] Code:\n', handlerCode)
68 console.log('[HandlerExec] ----------------------------------------')
69​
70 const { createIsolateDriver } =
71 await import('@/lib/create-isolate-driver')
72 const driver = await createIsolateDriver()
73 const effects: UIEffect[] = []
74 const uiUpdates: UIUpdate[] = []
75 const calledBindings: string[] = []
76​
77 const bindings = createHandlerBindings({
78 report: reportState.report,
79 onEffect: (effect) => {
80 console.log('[HandlerExec] Effect:', effect)
81 effects.push(effect)
82 },
83 onUIUpdate: (update) => {
84 console.log('[HandlerExec] UI Update:', update)
85 uiUpdates.push(update)
86 },
87 onBindingCall: (name) => {
88 console.log('[HandlerExec] Binding called:', name)
89 calledBindings.push(name)
90 },
91 })
92​
93 const isolateContext = await driver.createContext({
94 bindings,
95 timeout: 5000,
96 memoryLimit: 64,
97 })
98​
99 let result: HandlerResult
100​
101 try {
102 const event = {
103 componentId,
104 handlerName,
105 data: eventData || {},
106 }
107 const wrappedCode = `
108const event = ${JSON.stringify(event)};
109(async () => {
110 ${handlerCode}
111})()
113 const executionResult = await isolateContext.execute(wrappedCode)
114 console.log('[HandlerExec] Execution result:', executionResult)
115​
116 if (executionResult.success) {
117 result = {
118 success: true,
119 result: executionResult.value,
120 effects,
121 uiUpdates,
122 }
123 } else {
124 console.log(
125 '[HandlerExec] Execution failed:',
126 executionResult.error,
127 )
128 result = {
129 success: false,
130 error:
131 executionResult.error?.message ?? 'Unknown execution error',
132 effects,
133 uiUpdates,
134 }
135 }
136 } catch (error) {
137 console.log('[HandlerExec] Exception:', error)
138 result = {
139 success: false,
140 error: error instanceof Error ? error.message : String(error),
141 effects,
142 uiUpdates,
143 }
144 } finally {
145 await isolateContext.dispose()
146 }
147​
148 console.log('[HandlerExec] Final result:', {
149 success: result.success,
150 error: result.error,
151 })
152 console.log('[HandlerExec] ========================================')
153​
154 if (uiUpdates.length > 0) {
155 applyReportUIUpdates(reportId, uiUpdates)
156 }
157​
158 // Collect all invalidated signals from called bindings
159 const invalidatedSignals = new Set<string>()
160 console.log('[HandlerExec] Called bindings:', calledBindings)
161 for (const bindingName of calledBindings) {
162 const signals = getInvalidatedSignals(bindingName)
163 console.log(
164 '[HandlerExec] Binding',
165 bindingName,
166 'invalidates:',
167 signals,
168 )
169 for (const signal of signals) {
170 invalidatedSignals.add(signal)
171 }
172 }
173 console.log(
174 '[HandlerExec] Total invalidated signals:',
175 Array.from(invalidatedSignals),
176 )
177​
178 // Refresh all subscribers of invalidated signals
179 const refreshResults: RefreshResult[] = []
180 if (invalidatedSignals.size > 0 && reportState.signalRegistry) {
181 const subscribersToRefresh = new Set<string>()
182 for (const signal of invalidatedSignals) {
183 const subscribers =
184 reportState.signalRegistry.getSubscribers(signal)
185 console.log(
186 '[HandlerExec] Signal',
187 signal,
188 'has subscribers:',
189 subscribers,
190 )
191 for (const subscriberId of subscribers) {
192 subscribersToRefresh.add(subscriberId)
193 }
194 }
195 console.log(
196 '[HandlerExec] Components to refresh:',
197 Array.from(subscribersToRefresh),
198 )
199​
200 // Re-fetch current report state after UI updates
201 const currentState = getReportState(reportId)
202 if (currentState) {
203 for (const subscriberId of subscribersToRefresh) {
204 console.log('[HandlerExec] Refreshing component:', subscriberId)
205 const refreshResult = await refreshComponent(
206 currentState,
207 subscriberId,
208 )
209 console.log('[HandlerExec] Refresh result:', refreshResult)
210 refreshResults.push(refreshResult)
211 }
212 }
213 } else {
214 console.log(
215 '[HandlerExec] No signals to invalidate or no signal registry',
216 )
217 }
218 console.log(
219 '[HandlerExec] Total refresh results:',
220 refreshResults.length,
221 )
222​
223 // Evaluate watchers for invalidated signals
224 if (invalidatedSignals.size > 0) {
225 const currentState = getReportState(reportId)
226 if (currentState) {
227 const watcherResults = await evaluateWatchersForSignals(
228 currentState,
229 invalidatedSignals,
230 )
231 // Add watcher-triggered effects to the response
232 for (const effect of watcherResults.effects) {
233 effects.push(effect as UIEffect)
234 }
235 }
236 }
237​
238 // Include refresh results in the response
239 result.refreshResults = refreshResults
240​
241 return new Response(JSON.stringify(result), {
242 headers: { 'Content-Type': 'application/json' },
243 })
244 },
245 },
246 },
247})