npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@nasa-jpl/aerie-ts-user-code-runner

v0.7.0

Published

A simple way to safely run user code written in Typescript.

Downloads

452

Readme

Typescript User Code Runner

A simple way to safely run user code written in Typescript.

  • Speed - NodeJS/V8 makes JavaScript fast enough that if you have performance issues, you really should probably rethink your architecture and move more processing out of user code.
  • Isolation - NodeJS exposes the internal VM of V8, which allows us to create new V8 isolates for each user code run. This means that bad user code will not crash your system and won't have access to anything you don't explicitly expose.
  • Execution Limits - V8 isolates enable setting a timeout on the executing code, so users can't hang your system.
  • Simple User API - User code just needs to export a default function that takes any arguments you want to give it, and returns anything you want back from it.
  • No Throw - executeUserCode never throws. The return uses a Result monad to ensure confidence in dealing with user code errors

Requirements

NodeJS >= 13.0.0

Because we are transpiling and running the typescript code as modules in a vm, we need to flag on the vm modules flag at runtime with node --experimental-vm-modules

Example

import { UserCodeRunner } from './UserCodeRunner';

const userCode = `
  export default function MyDSLFunction(thing: string): string {
    return thing + ' world';
  }
`;

const codeRunner = new UserCodeRunner();

const result = await codeRunner.executeUserCode(
        userCode, // Actual user code
        ['hello'], // Input arguments
        'string', // Return type
        ['string'], // Argument types
);

expect(result.isOk()).toBeTruthy();
expect(result.unwrap()).toBe('hello world');

Error Messages

Error messaging is even more important when dealing with user code as you really need to guide the user to resolve any errors.

Type Error Examples

TypeError: TS2322 Incorrect return type. Expected: 'number', Actual: 'string'.
  at MyDSLFunction(0:54)
TypeError: TS2554 Incorrect argument type. Expected: '[string]', Actual: '[string, number]'.
  at MyDSLFunction(0:38)
TypeError: TS2322 Type 'string' is not assignable to type 'number'.

Runtime Error Examples

Error: This is a test error
      at subroutine(7:8)
      at MyDSLFunction(2:2)

Usage Examples

Simple Example

const userCode = `
  export default function MyDSLFunction(thing: string): string {
    return thing + ' world';
  }
  `.trimTemplate();

const codeRunner = new UserCodeRunner();

const result = await codeRunner.executeUserCode(
  userCode,
  ['hello'],
  'string',
  ['string'],
);

expect(result.isOk()).toBeTruthy();
expect(result.unwrap()).toBe('hello world');

Including other files for import, declaring some globals, and specified context

const userCode = `
  import { importedFunction } from 'other-importable';
  export default function myDSLFunction(thing: string): string {
    return someGlobalFunction(thing) + otherFunction(' world');
  }
  `.trimTemplate();

const codeRunner = new UserCodeRunner();

const result = await codeRunner.executeUserCode(
  userCode,
  ['hello'],
  'string',
  ['string'],
  1000,
  [
    ts.createSourceFile('globals.d.ts', `
    declare global {
      function someGlobalFunction(thing: string): string;
    }
    export {};
    `.trimTemplate(), ts.ScriptTarget.ESNext, true),
    ts.createSourceFile('other-importable.ts', `
    export function importedFunction(thing: string): string {
      return thing + ' other';
    }
    `.trimTemplate(), ts.ScriptTarget.ESNext, true)
  ],
  vm.createContext({
    someGlobalFunction: (thing: string) => 'hello ' + thing, // Implementation injected to global namespace here
  }),
);

// expect(result.isOk()).toBeTruthy();
expect(result.unwrap()).toBe('hello hello world other');