Skip to content

Commit 08267f0

Browse files
committed
refactor(execution): parse user code with Babel, not the TypeScript 6 compiler
TypeScript 7 ships no compiler API, so the server kept @typescript/typescript6 only to parse and transpile code users write. Three of its four runtime uses move to libraries built for the job: - MCP code mode strips types with sucrase after Babel checks the syntax, so a program that does not parse still reports every error with its own line. - The Function block's import scan and the document file-reference scanner parse with Babel through one shared parser for user JavaScript. A Function body that does not parse now runs where its syntax error is reported, instead of first starting a remote sandbox for the imports found in it.
1 parent 4c0ac32 commit 08267f0

9 files changed

Lines changed: 304 additions & 156 deletions

File tree

‎apps/sim/lib/api/mcp/code-mode.ts‎

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import {
1919
} from '@/lib/api/mcp/dispatch'
2020
import { createConcurrencyLimit } from '@/lib/core/utils/concurrency'
2121
import { runSandboxTask, SandboxUserCodeError } from '@/lib/execution/sandbox/run-task'
22-
import { loadTypeScript } from '@/lib/execution/typescript'
22+
import { stripTypes } from '@/lib/execution/typescript'
2323
import { structuredToolResult, toolError } from '@/lib/mcp/tool-result'
2424
import { SIM_API_CODE_MAX_TIMEOUT_MS } from '@/sandboxes/sim-api-code'
2525

@@ -128,24 +128,16 @@ function envelopeFailure(status: number, text: string): SimApiAnswer {
128128
* value or error, is recorded for `finalize` rather than lost to the worker.
129129
* Syntax errors come back with lines numbered as the caller wrote them.
130130
*/
131-
async function compileProgram(code: string): Promise<{ script: string } | { error: string }> {
132-
const ts = await loadTypeScript()
133-
const { outputText, diagnostics } = ts.transpileModule(
134-
`const __simProgram = async () => {\n${code}\n};`,
135-
{
136-
reportDiagnostics: true,
137-
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
138-
}
139-
)
140-
const problems = (diagnostics ?? []).flatMap((diagnostic) => {
141-
if (!diagnostic.file || diagnostic.start === undefined) return []
142-
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')
143-
const { line } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start)
144-
return [`Line ${Math.max(1, line)}: ${message}`]
145-
})
146-
if (problems.length > 0) return { error: `The program does not parse.\n${problems.join('\n')}` }
131+
function compileProgram(code: string): { script: string } | { error: string } {
132+
const stripped = stripTypes(`const __simProgram = async () => {\n${code}\n};`)
133+
if ('errors' in stripped) {
134+
const problems = stripped.errors.map(
135+
({ line, message }) => `Line ${Math.max(1, line - 1)}: ${message}`
136+
)
137+
return { error: `The program does not parse.\n${problems.join('\n')}` }
138+
}
147139
return {
148-
script: `${outputText}\ntry { __simCodeSettle(true, await __simProgram()); } catch (error) { __simCodeSettle(false, error); }`,
140+
script: `${stripped.code}\ntry { __simCodeSettle(true, await __simProgram()); } catch (error) { __simCodeSettle(false, error); }`,
149141
}
150142
}
151143

@@ -192,7 +184,7 @@ export async function runCodeMode(
192184
codeSha256: sha256Hex(input.code),
193185
})
194186

195-
const compiled = await compileProgram(input.code)
187+
const compiled = compileProgram(input.code)
196188
if ('error' in compiled) {
197189
summary('syntax_error')
198190
return toolError(compiled.error)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { type ParseResult, parse } from '@babel/parser'
2+
import type { File } from '@babel/types'
3+
4+
interface UserJavaScriptParseOptions {
5+
/** Keep parsing past errors that leave the tree intact, listing them on `errors`. */
6+
errorRecovery?: boolean
7+
/** Include every token, comments among them, on `tokens`. */
8+
tokens?: boolean
9+
}
10+
11+
/**
12+
* Parses JavaScript a user wrote, which runs as the body of an async function: top-level
13+
* `return` and `await` are allowed, static imports may sit anywhere, and the source is
14+
* sloppy-mode script, as the sandboxes evaluate it. Throws a `SyntaxError` carrying `loc`
15+
* when the source does not parse.
16+
*/
17+
export function parseUserJavaScript(
18+
code: string,
19+
{ errorRecovery = false, tokens = false }: UserJavaScriptParseOptions = {}
20+
): ParseResult<File> {
21+
return parse(code, {
22+
sourceType: 'script',
23+
allowImportExportEverywhere: true,
24+
allowReturnOutsideFunction: true,
25+
allowAwaitOutsideFunction: true,
26+
errorRecovery,
27+
tokens,
28+
plugins: ['jsx'],
29+
})
30+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* @vitest-environment node
3+
*/
4+
import { runInNewContext } from 'node:vm'
5+
import { describe, expect, it } from 'vitest'
6+
import { stripTypes } from '@/lib/execution/typescript'
7+
8+
function run(source: string): unknown {
9+
const stripped = stripTypes(`(() => {\n${source}\n})()`)
10+
if ('errors' in stripped) throw new Error(JSON.stringify(stripped.errors))
11+
return runInNewContext(stripped.code)
12+
}
13+
14+
describe('stripTypes', () => {
15+
it('removes annotations, interfaces and assertions but keeps the values they wrap', () => {
16+
expect(
17+
run(`interface Row { id: string }
18+
const rows = [{ id: 'a' }] as const satisfies readonly Row[]
19+
const first: Row | undefined = rows[0]!
20+
return rows.map((row): string => row.id).concat(first ? [first.id] : [])`)
21+
).toEqual(['a', 'a'])
22+
})
23+
24+
it('compiles the TypeScript constructs that have a runtime value', () => {
25+
expect(run('enum Color { Red, Blue }\nreturn [Color.Blue, Color[0]]')).toEqual([1, 'Red'])
26+
})
27+
28+
it('keeps every line where it was written, so runtime positions match the source', () => {
29+
const stripped = stripTypes('type A = {\n a: number\n}\nconst value: A = { a: 1 }\nvalue.b()')
30+
expect('code' in stripped && stripped.code.split('\n')[4]).toBe('value.b()')
31+
})
32+
33+
it('reports a program that does not parse with the line of each error', () => {
34+
expect(stripTypes('const a = 1\nconst b: = 2')).toEqual({
35+
errors: [{ line: 2, message: expect.stringContaining('Unexpected token') }],
36+
})
37+
expect(stripTypes('let a = 1\nlet a = 2\nlet b = 1\nlet b = 2')).toEqual({
38+
errors: [
39+
{ line: 2, message: "Identifier 'a' has already been declared." },
40+
{ line: 4, message: "Identifier 'b' has already been declared." },
41+
],
42+
})
43+
})
44+
})
Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,48 @@
1-
type TypeScriptModule = typeof import('@typescript/typescript6')
1+
import { parse } from '@babel/parser'
2+
import { transform } from 'sucrase'
23

3-
let typescriptModule: Promise<TypeScriptModule> | null = null
4+
interface TypeScriptSyntaxError {
5+
/** 1-based, in the source as given. */
6+
line: number
7+
message: string
8+
}
9+
10+
type StripTypesResult = { code: string } | { errors: TypeScriptSyntaxError[] }
11+
12+
interface LocatedError {
13+
message: string
14+
loc: { line: number }
15+
}
16+
17+
function isLocatedError(value: unknown): value is LocatedError {
18+
if (!(value instanceof Error)) return false
19+
const loc: unknown = Reflect.get(value, 'loc')
20+
return typeof loc === 'object' && loc !== null && typeof Reflect.get(loc, 'line') === 'number'
21+
}
22+
23+
function toSyntaxError(error: LocatedError): TypeScriptSyntaxError {
24+
return { line: error.loc.line, message: error.message.replace(/ \(\d+:\d+\)$/, '') }
25+
}
426

527
/**
6-
* The TypeScript compiler, imported on first use: it is large, and most
7-
* requests never parse or transpile user code. A failed import is dropped so
8-
* the next call retries it.
28+
* TypeScript as JavaScript a sandbox can run: types are removed and nothing else is
29+
* transformed, so every line keeps its number. The source is checked first, so a program
30+
* that does not parse comes back as its errors and their lines instead of failing later at
31+
* run time with positions that no longer match what was written.
932
*/
10-
export function loadTypeScript(): Promise<TypeScriptModule> {
11-
typescriptModule ??= import('@typescript/typescript6').then(
12-
(mod) => (mod?.default ?? mod) as TypeScriptModule,
13-
(error) => {
14-
typescriptModule = null
15-
throw error
16-
}
17-
)
18-
return typescriptModule
33+
export function stripTypes(source: string): StripTypesResult {
34+
let errors: TypeScriptSyntaxError[]
35+
try {
36+
const ast = parse(source, {
37+
sourceType: 'module',
38+
errorRecovery: true,
39+
plugins: ['typescript'],
40+
})
41+
errors = (ast.errors ?? []).filter(isLocatedError).map(toSyntaxError)
42+
} catch (error) {
43+
if (!isLocatedError(error)) throw error
44+
errors = [toSyntaxError(error)]
45+
}
46+
if (errors.length > 0) return { errors }
47+
return { code: transform(source, { transforms: ['typescript'], disableESTransforms: true }).code }
1948
}

‎apps/sim/lib/function-execution/execute-request.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -823,6 +823,38 @@ describe('Function execution request', () => {
823823
})
824824

825825
describe('Basic Function Execution', () => {
826+
it('hoists every static import, with the comment above it, and keeps the body on its lines', async () => {
827+
envFlagsMock.isRemoteSandboxEnabled = true
828+
829+
const response = await POST(
830+
createMockRequest('POST', {
831+
code: [
832+
'const label = "sep"',
833+
'// joins paths',
834+
'import path from "node:path"',
835+
'return label + path.sep',
836+
].join('\n'),
837+
language: 'javascript',
838+
})
839+
)
840+
841+
expect(response.status).toBe(200)
842+
const code: string = mockExecuteInSandbox.mock.calls.at(-1)?.[0].code
843+
expect(code).toContain('// joins paths\nimport path from "node:path"\n')
844+
expect(code).toContain('const label = "sep"\n \n \n return label + path.sep')
845+
})
846+
847+
it.each([
848+
['a require call', 'const path = require("node:path")\nreturn path.sep', 1],
849+
['code that does not parse', 'import path from "node:path"\nreturn (', 0],
850+
])('sends %s to the remote sandbox only when it loads modules', async (_, code, calls) => {
851+
envFlagsMock.isRemoteSandboxEnabled = true
852+
853+
await POST(createMockRequest('POST', { code, language: 'javascript' }))
854+
855+
expect(mockExecuteInSandbox).toHaveBeenCalledTimes(calls)
856+
})
857+
826858
it('compacts large array result fields to manifests when execution context is durable', async () => {
827859
// Compaction cost scales with element count, so a few wide rows cross the threshold cheaply.
828860
const rowCount = 64

0 commit comments

Comments
 (0)