|
1 | 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. |
2 | 2 |
|
3 | 3 | import util from 'node:util'; |
| 4 | + |
| 5 | +import ts from 'typescript'; |
| 6 | + |
4 | 7 | import { WorkerInput, WorkerSuccess, WorkerError } from './code-tool-types'; |
5 | 8 | import { CasParser } from 'cas-parser-node'; |
6 | 9 |
|
| 10 | +function getRunFunctionNode( |
| 11 | + code: string, |
| 12 | +): ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction | null { |
| 13 | + const sourceFile = ts.createSourceFile('code.ts', code, ts.ScriptTarget.Latest, true); |
| 14 | + |
| 15 | + for (const statement of sourceFile.statements) { |
| 16 | + // Check for top-level function declarations |
| 17 | + if (ts.isFunctionDeclaration(statement)) { |
| 18 | + if (statement.name?.text === 'run') { |
| 19 | + return statement; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + // Check for variable declarations: const run = () => {} or const run = function() {} |
| 24 | + if (ts.isVariableStatement(statement)) { |
| 25 | + for (const declaration of statement.declarationList.declarations) { |
| 26 | + if (ts.isIdentifier(declaration.name) && declaration.name.text === 'run') { |
| 27 | + // Check if it's initialized with a function |
| 28 | + if ( |
| 29 | + declaration.initializer && |
| 30 | + (ts.isFunctionExpression(declaration.initializer) || ts.isArrowFunction(declaration.initializer)) |
| 31 | + ) { |
| 32 | + return declaration.initializer; |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return null; |
| 40 | +} |
| 41 | + |
7 | 42 | const fetch = async (req: Request): Promise<Response> => { |
8 | 43 | const { opts, code } = (await req.json()) as WorkerInput; |
| 44 | + |
| 45 | + const runFunctionNode = getRunFunctionNode(code); |
| 46 | + if (!runFunctionNode) { |
| 47 | + return Response.json( |
| 48 | + { |
| 49 | + message: |
| 50 | + 'The code is missing a top-level `run` function. Write code within this template:\n\n```\nasync function run(client) {\n // Fill this out\n}\n```', |
| 51 | + } satisfies WorkerError, |
| 52 | + { status: 400, statusText: 'Code execution error' }, |
| 53 | + ); |
| 54 | + } |
| 55 | + |
9 | 56 | const client = new CasParser({ |
10 | 57 | ...opts, |
11 | 58 | }); |
|
0 commit comments