UNPKG

@comake/skl-js-engine

Version:

Standard Knowledge Language Javascript Engine

80 lines (69 loc) 2.65 kB
/* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/no-empty-function */ /* eslint-disable prefer-arrow-callback */ /* eslint-disable @typescript-eslint/ban-ts-comment */ // @ts-nocheck import { ChildStdioTransport } from '../../transport/stdio/ChildStdioTransport.ts'; interface ExecuteCodeMessage { code: string; args: Record<string, any>; functionName?: string; } // Create a single transport that handles both server and client functionality const transport = new ChildStdioTransport(); transport.setName('jsExecutor-example-process'); // Register methods that the parent can call (server functionality) transport.registerMethod( 'executeCode', async(message: ExecuteCodeMessage): Promise<{ result: string }> => { const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor; const executeCode = new AsyncFunction( 'args', 'console', 'request', 'SKL', ` ${message.code} try { if (typeof ${message.functionName} === 'function') { return await ${message.functionName}(args); } throw new Error('Function name is not defined'); } catch (error) { throw error; } ` ); // Const sklEngine = new SKLEngine({ // skdsEndpointUrl: 'http://localhost:3000' // }); // Create SKL proxy that converts method calls to request calls const SKL = new Proxy({}, { get(target, prop) { if (typeof prop === 'string') { return async(...args: any[]) => { // Convert method call to request call // SKL.getTime() becomes request('getTime', {}, options) const [ params = {}, options = {} ] = args; return await transport.request(prop, params, options); }; } } }); const result = await executeCode(message.args, console, transport.request.bind(transport), SKL); return { result }; } ); transport.registerMethod('ping', async(): Promise<string> => 'pong'); // Register a method that demonstrates calling back to the parent (client functionality) // transport.registerMethod('callParent', async(): Promise<{ result: string }> => { // try { // // Call the parent's getTime method // const result = await transport.request('getTime'); // return { result: `Parent getTime returned: ${JSON.stringify(result)}` }; // } catch (error: unknown) { // return { result: `Error calling parent: ${(error as Error).message}` }; // } // }); // Initialize the transport (this sets up stdio communication) await transport.initialize();