-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathresolver.ts
More file actions
404 lines (358 loc) · 12.2 KB
/
resolver.ts
File metadata and controls
404 lines (358 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import { createLogger } from '@sim/logger'
import { BlockType } from '@/executor/constants'
import type { ExecutionState, LoopScope } from '@/executor/execution/state'
import type { ExecutionContext } from '@/executor/types'
import { createEnvVarPattern, replaceValidReferences } from '@/executor/utils/reference-validation'
import { BlockResolver } from '@/executor/variables/resolvers/block'
import { EnvResolver } from '@/executor/variables/resolvers/env'
import { LoopResolver } from '@/executor/variables/resolvers/loop'
import { ParallelResolver } from '@/executor/variables/resolvers/parallel'
import {
RESOLVED_EMPTY,
type ResolutionContext,
type Resolver,
} from '@/executor/variables/resolvers/reference'
import { WorkflowResolver } from '@/executor/variables/resolvers/workflow'
import type { SerializedBlock, SerializedWorkflow } from '@/serializer/types'
/** Key used to carry pre-resolved context variables through the inputs map. */
export const FUNCTION_BLOCK_CONTEXT_VARS_KEY = '_runtimeContextVars'
const logger = createLogger('VariableResolver')
export class VariableResolver {
private resolvers: Resolver[]
private blockResolver: BlockResolver
constructor(
workflow: SerializedWorkflow,
workflowVariables: Record<string, any>,
private state: ExecutionState
) {
this.blockResolver = new BlockResolver(workflow)
this.resolvers = [
new LoopResolver(workflow),
new ParallelResolver(workflow),
new WorkflowResolver(workflowVariables),
new EnvResolver(),
this.blockResolver,
]
}
/**
* Resolves inputs for function blocks. Block output references in the `code` field
* are stored as named context variables instead of being embedded as JavaScript
* literals, preventing large values from bloating the code string.
*
* Returns the resolved inputs and a `contextVariables` map. Callers should inject
* contextVariables into the function execution request body so the isolated VM can
* access them as global variables.
*/
resolveInputsForFunctionBlock(
ctx: ExecutionContext,
currentNodeId: string,
params: Record<string, any>,
block: SerializedBlock
): { resolvedInputs: Record<string, any>; contextVariables: Record<string, unknown> } {
const contextVariables: Record<string, unknown> = {}
const resolved: Record<string, any> = {}
for (const [key, value] of Object.entries(params)) {
if (key === 'code') {
if (typeof value === 'string') {
resolved[key] = this.resolveCodeWithContextVars(
ctx,
currentNodeId,
value,
undefined,
block,
contextVariables
)
} else if (Array.isArray(value)) {
resolved[key] = value.map((item: any) => {
if (item && typeof item === 'object' && typeof item.content === 'string') {
return {
...item,
content: this.resolveCodeWithContextVars(
ctx,
currentNodeId,
item.content,
undefined,
block,
contextVariables
),
}
}
return item
})
} else {
resolved[key] = this.resolveValue(ctx, currentNodeId, value, undefined, block)
}
} else {
resolved[key] = this.resolveValue(ctx, currentNodeId, value, undefined, block)
}
}
return { resolvedInputs: resolved, contextVariables }
}
resolveInputs(
ctx: ExecutionContext,
currentNodeId: string,
params: Record<string, any>,
block?: SerializedBlock
): Record<string, any> {
if (!params) {
return {}
}
const resolved: Record<string, any> = {}
const isConditionBlock = block?.metadata?.id === BlockType.CONDITION
if (isConditionBlock && typeof params.conditions === 'string') {
try {
const parsed = JSON.parse(params.conditions)
if (Array.isArray(parsed)) {
resolved.conditions = parsed.map((cond: any) => ({
...cond,
value:
typeof cond.value === 'string'
? this.resolveTemplateWithoutConditionFormatting(ctx, currentNodeId, cond.value)
: cond.value,
}))
} else {
resolved.conditions = this.resolveValue(
ctx,
currentNodeId,
params.conditions,
undefined,
block
)
}
} catch (parseError) {
logger.warn('Failed to parse conditions JSON, falling back to normal resolution', {
error: parseError,
conditions: params.conditions,
})
resolved.conditions = this.resolveValue(
ctx,
currentNodeId,
params.conditions,
undefined,
block
)
}
}
for (const [key, value] of Object.entries(params)) {
if (isConditionBlock && key === 'conditions') {
continue
}
resolved[key] = this.resolveValue(ctx, currentNodeId, value, undefined, block)
}
return resolved
}
resolveSingleReference(
ctx: ExecutionContext,
currentNodeId: string,
reference: string,
loopScope?: LoopScope
): any {
if (typeof reference === 'string') {
const trimmed = reference.trim()
if (/^<[^<>]+>$/.test(trimmed)) {
const resolutionContext: ResolutionContext = {
executionContext: ctx,
executionState: this.state,
currentNodeId,
loopScope,
}
const result = this.resolveReference(trimmed, resolutionContext)
if (result === RESOLVED_EMPTY) {
return null
}
return result
}
}
return this.resolveValue(ctx, currentNodeId, reference, loopScope)
}
private resolveValue(
ctx: ExecutionContext,
currentNodeId: string,
value: any,
loopScope?: LoopScope,
block?: SerializedBlock
): any {
if (value === null || value === undefined) {
return value
}
if (Array.isArray(value)) {
return value.map((v) => this.resolveValue(ctx, currentNodeId, v, loopScope, block))
}
if (typeof value === 'object') {
return Object.entries(value).reduce(
(acc, [key, val]) => ({
...acc,
[key]: this.resolveValue(ctx, currentNodeId, val, loopScope, block),
}),
{}
)
}
if (typeof value === 'string') {
return this.resolveTemplate(ctx, currentNodeId, value, loopScope, block)
}
return value
}
/**
* Resolves a code template for a function block. Block output references are stored
* in `contextVarAccumulator` as named variables (e.g. `__blockRef_0`) and replaced
* with those variable names in the returned code string. Non-block references (loop
* items, workflow variables, env vars) are still inlined as literals so they remain
* available without any extra passing mechanism.
*/
private resolveCodeWithContextVars(
ctx: ExecutionContext,
currentNodeId: string,
template: string,
loopScope: LoopScope | undefined,
block: SerializedBlock,
contextVarAccumulator: Record<string, unknown>
): string {
const resolutionContext: ResolutionContext = {
executionContext: ctx,
executionState: this.state,
currentNodeId,
loopScope,
}
const language = (block.config?.params as Record<string, unknown> | undefined)?.language as
| string
| undefined
let replacementError: Error | null = null
let result = replaceValidReferences(template, (match) => {
if (replacementError) return match
try {
const resolved = this.resolveReference(match, resolutionContext)
if (resolved === undefined) return match
const effectiveValue = resolved === RESOLVED_EMPTY ? null : resolved
if (this.blockResolver.canResolve(match)) {
// Block output: store in contextVarAccumulator, replace with variable name
const varName = `__blockRef_${Object.keys(contextVarAccumulator).length}`
contextVarAccumulator[varName] = effectiveValue
return varName
}
// Non-block reference (loop, parallel, workflow, env): embed as literal
return this.blockResolver.formatValueForBlock(effectiveValue, BlockType.FUNCTION, language)
} catch (error) {
replacementError = error instanceof Error ? error : new Error(String(error))
return match
}
})
if (replacementError !== null) {
throw replacementError
}
result = result.replace(createEnvVarPattern(), (match) => {
const resolved = this.resolveReference(match, resolutionContext)
return typeof resolved === 'string' ? resolved : match
})
return result
}
private resolveTemplate(
ctx: ExecutionContext,
currentNodeId: string,
template: string,
loopScope?: LoopScope,
block?: SerializedBlock
): string {
const resolutionContext: ResolutionContext = {
executionContext: ctx,
executionState: this.state,
currentNodeId,
loopScope,
}
let replacementError: Error | null = null
const blockType = block?.metadata?.id
const language =
blockType === BlockType.FUNCTION
? ((block?.config?.params as Record<string, unknown> | undefined)?.language as
| string
| undefined)
: undefined
let result = replaceValidReferences(template, (match) => {
if (replacementError) return match
try {
const resolved = this.resolveReference(match, resolutionContext)
if (resolved === undefined) {
return match
}
if (resolved === RESOLVED_EMPTY) {
if (blockType === BlockType.FUNCTION) {
return this.blockResolver.formatValueForBlock(null, blockType, language)
}
return ''
}
return this.blockResolver.formatValueForBlock(resolved, blockType, language)
} catch (error) {
replacementError = error instanceof Error ? error : new Error(String(error))
return match
}
})
if (replacementError !== null) {
throw replacementError
}
result = result.replace(createEnvVarPattern(), (match) => {
const resolved = this.resolveReference(match, resolutionContext)
return typeof resolved === 'string' ? resolved : match
})
return result
}
private resolveTemplateWithoutConditionFormatting(
ctx: ExecutionContext,
currentNodeId: string,
template: string,
loopScope?: LoopScope
): string {
const resolutionContext: ResolutionContext = {
executionContext: ctx,
executionState: this.state,
currentNodeId,
loopScope,
}
let replacementError: Error | null = null
let result = replaceValidReferences(template, (match) => {
if (replacementError) return match
try {
const resolved = this.resolveReference(match, resolutionContext)
if (resolved === undefined) {
return match
}
if (resolved === RESOLVED_EMPTY) {
return 'null'
}
if (typeof resolved === 'string') {
const escaped = resolved
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
return `'${escaped}'`
}
if (typeof resolved === 'object' && resolved !== null) {
return JSON.stringify(resolved)
}
return String(resolved)
} catch (error) {
replacementError = error instanceof Error ? error : new Error(String(error))
return match
}
})
if (replacementError !== null) {
throw replacementError
}
result = result.replace(createEnvVarPattern(), (match) => {
const resolved = this.resolveReference(match, resolutionContext)
return typeof resolved === 'string' ? resolved : match
})
return result
}
private resolveReference(reference: string, context: ResolutionContext): any {
for (const resolver of this.resolvers) {
if (resolver.canResolve(reference)) {
const result = resolver.resolve(reference, context)
return result
}
}
logger.warn('No resolver found for reference', { reference })
return undefined
}
}