Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(sandbox): retry sucrase transpile with a leading empty statement when it crashes (#16376)

Chaker Atallahcbcb98faaac9
diff --git a/bun.lock b/bun.lock
index 193726e3c6b..a95ff519e5e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1,6 +1,5 @@
{
"lockfileVersion": 1,
- "configVersion": 0,
"workspaces": {
"": {
"name": "activepieces",
@@ -11040,6 +11039,7 @@
"devDependencies": {
"@types/node": "24.11.0",
"@types/write-file-atomic": "4.0.3",
+ "deno": "2.9.3",
"socket.io-client": "4.8.1",
"sucrase": "3.35.1",
"vitest": "3.2.6",
diff --git a/packages/server/sandbox/package.json b/packages/server/sandbox/package.json
index b8155bfddde..926af903e5a 100644
--- a/packages/server/sandbox/package.json
+++ b/packages/server/sandbox/package.json
@@ -21,6 +21,7 @@
"write-file-atomic": "5.0.1"
},
"devDependencies": {
+ "deno": "2.9.3",
"sucrase": "3.35.1",
"@types/write-file-atomic": "4.0.3",
"@types/node": "24.11.0",
diff --git a/packages/server/sandbox/src/lib/cache/flow/code/code-builder.ts b/packages/server/sandbox/src/lib/cache/flow/code/code-builder.ts
index bc9f82ba900..b873d1d4ca5 100644
--- a/packages/server/sandbox/src/lib/cache/flow/code/code-builder.ts
+++ b/packages/server/sandbox/src/lib/cache/flow/code/code-builder.ts
@@ -1,7 +1,7 @@
import { existsSync } from 'node:fs'
import fs, { rm } from 'node:fs/promises'
import path from 'node:path'
-import { tryCatch, tryCatchSync } from '@activepieces/core-utils'
+import { isNil, tryCatch, tryCatchSync } from '@activepieces/core-utils'
import { type ApLogger, cryptoUtils, fileSystemUtils, wideEvent } from '@activepieces/server-utils'
import { ExecutionMode } from '@activepieces/shared'
import { CodeArtifact, SandboxSettings } from '../../../types'
@@ -125,8 +125,9 @@ export const codeBuilder = (log: ApLogger, getSettings: () => SandboxSettings) =
await fs.writeFile(entryPath, sourceCode.code, 'utf8')
const { data: transpiled, error } = await tryCatch(() => denoStepTranspiler.toCommonJs({ source: sourceCode.code }))
if (error !== null || transpiled.fallbackToEsm === true) {
- if (error !== null) {
- log.info({ codePath, error }, 'Deno step transpile failed, falling back to raw source')
+ const fallbackError = error ?? transpiled?.error
+ if (!isNil(fallbackError)) {
+ log.info({ codePath, error: fallbackError }, 'Deno step transpile failed, falling back to raw source')
}
return
}
diff --git a/packages/server/sandbox/src/lib/cache/flow/code/deno-step-transpiler.ts b/packages/server/sandbox/src/lib/cache/flow/code/deno-step-transpiler.ts
index d2d48c5d98b..5b91ed95086 100644
--- a/packages/server/sandbox/src/lib/cache/flow/code/deno-step-transpiler.ts
+++ b/packages/server/sandbox/src/lib/cache/flow/code/deno-step-transpiler.ts
@@ -9,18 +9,34 @@ export const denoStepTranspiler = {
const result = await deno.run({
body: `
${SUCRASE_SOURCE}
- const transformed = globalThis.__apSucrase.transform(${JSON.stringify(source)}, {
+ const transpile = (src) => globalThis.__apSucrase.transform(src, {
transforms: ['typescript', 'imports'],
disableESTransforms: true,
production: true,
}).code.replace(/^"use strict";/, '');
+ let transformed = null;
+ let transformError = null;
+ try {
+ transformed = transpile(${JSON.stringify(source)});
+ }
+ catch {
+ try {
+ transformed = transpile(';' + ${JSON.stringify(source)});
+ }
+ catch (retryError) {
+ transformError = retryError;
+ }
+ }
let result;
try {
+ if (transformed === null) {
+ throw transformError;
+ }
new Function(transformed);
result = { code: transformed };
}
- catch {
- result = { fallbackToEsm: true };
+ catch (error) {
+ result = { fallbackToEsm: true, error: String(error && error.message ? error.message : error) };
}
`,
permissions: [],
@@ -51,7 +67,9 @@ type ToCommonJsParams = {
export type TranspileResult = {
code: string
fallbackToEsm?: undefined
+ error?: undefined
} | {
code?: undefined
fallbackToEsm: true
+ error?: string
}
diff --git a/packages/server/sandbox/test/lib/cache/flow/code/deno-step-transpiler.test.ts b/packages/server/sandbox/test/lib/cache/flow/code/deno-step-transpiler.test.ts
new file mode 100644
index 00000000000..80f25575b73
--- /dev/null
+++ b/packages/server/sandbox/test/lib/cache/flow/code/deno-step-transpiler.test.ts
@@ -0,0 +1,77 @@
+import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+
+process.env.AP_DENO_PATH = path.join(path.dirname(require.resolve('deno/bin.cjs')), 'deno')
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+let denoStepTranspiler: any
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+let deno: any
+let stepDir: string
+
+beforeAll(async () => {
+ const transpilerModule = await import('../../../../../src/lib/cache/flow/code/deno-step-transpiler')
+ denoStepTranspiler = transpilerModule.denoStepTranspiler
+ const coreUtils = await import('@activepieces/core-utils')
+ deno = coreUtils.deno
+ stepDir = await realpath(await mkdtemp(path.join(tmpdir(), 'ap-transpiler-test-')))
+})
+
+afterAll(async () => {
+ await rm(stepDir, { recursive: true, force: true })
+})
+
+async function runTranspiledAsCommonJs(code: string): Promise<unknown> {
+ const cjsPath = path.join(stepDir, 'index.cjs')
+ await writeFile(cjsPath, code)
+ return deno.run({
+ body: `
+ const { createRequire } = await import('node:module');
+ const mod = createRequire(${JSON.stringify(cjsPath)})(${JSON.stringify(cjsPath)});
+ const result = await mod.code();
+`,
+ permissions: [],
+ cwd: stepDir,
+ allowReadPaths: [stepDir],
+ })
+}
+
+describe('denoStepTranspiler', () => {
+ it('transpiles an ESM step to CommonJS', async () => {
+ const result = await denoStepTranspiler.toCommonJs({
+ source: 'export const code = async (inputs: { a: number }) => inputs.a + 1',
+ })
+ expect(result.fallbackToEsm).toBeUndefined()
+ expect(result.code).toContain('exports.')
+ expect(result.code).not.toMatch(/^"use strict";/)
+ })
+
+ it('transpiles a source whose first statement is an undeclared assignment alongside an export, and the output runs', async () => {
+ const result = await denoStepTranspiler.toCommonJs({
+ source: 'cv = (x) => x;\nexport const code = async () => cv(1);',
+ })
+ expect(result.fallbackToEsm).toBeUndefined()
+ await expect(runTranspiledAsCommonJs(result.code)).resolves.toBe(1)
+ })
+
+ it('falls back to ESM for top-level await, reporting why', async () => {
+ const result = await denoStepTranspiler.toCommonJs({
+ source: 'const value = await Promise.resolve(1);\nexport const code = async () => value;',
+ })
+ expect(result.fallbackToEsm).toBe(true)
+ expect(result.code).toBeUndefined()
+ expect(result.error).toMatch(/await/)
+ })
+
+ it('falls back to ESM when the source cannot be transpiled at all, reporting the transform error', async () => {
+ const result = await denoStepTranspiler.toCommonJs({
+ source: 'export const code = async () => { const htmlInput = <center>broken</div>; }',
+ })
+ expect(result.fallbackToEsm).toBe(true)
+ expect(result.code).toBeUndefined()
+ expect(typeof result.error).toBe('string')
+ expect(result.error.length).toBeGreaterThan(0)
+ })
+})