Code Monkey home page Code Monkey logo

eval2's Introduction

eval2.js

Sometimes you need to use generated code in your app. But sometimes that generated code has syntax errors in it, which causes an error to be thrown:

code =
  'function add ( a, b ) {\n' +
  '  return a _ b;\n' +  // oops! fat finger. we meant `+`, not `_`
  '}';

add = eval( '(' + code + ')' ); // 'SyntaxError: Unexpected identifier'

But where is the syntax error? In this case it's obvious, but imagine the code has dozens of lines. Maybe it won't be so obvious then. The stack trace will include the call to eval, but not the line of code that contained the error.

The same is true of new Function():

var add = new Function( 'a', 'b', 'return a _ b' );

eval2.js fixes this problem. In modern browsers, the code is converted to a data URI and inserted via a <script> tag. In node.js, a temporary module is created. In both cases, any syntax errors that are thrown will include the offending code in the stack trace.

Installation

Install with npm...

$ npm i eval2

...or bower...

bower i eval2

...or grab a copy of eval2.js and include it in your app (works as AMD or node.js module, or as browser global).

Usage

var eval2 = require( 'eval2' );

var code =
  'function add ( a, b ) {\n' +
  '  return a _ b;\n' +
  '}';

eval2( '(' + code + ')' );

// You can optionally pass in a sourceURL which will be used
// for debugging where possible...
eval2( '(' + code + ')', {
  sourceURL: 'add.js'
});

// ...or, if you're really fancy, a dynamic source map
// (see http://kybernetikos.github.io/jsSandbox/srcmaps/dynamic.html)
eval2( '(' + code + ')', {
  sourceMap: { version: 3, ... }
});

In browsers, you'll get an Uncaught SyntaxError message printed to the console, with a link pointing to the offending line of code. Note that you can't capture this stack trace programmatically - the error will be thrown asynchronously (because code added via a dynamic <script> element always executes asynchronously), so you must inspect the code via the console.

In node.js, the code itself will be printed to the console, along with the error.

You can also create functions using eval2.Function - this behaves similarly to new Function():

// If the function body contains a syntax error, eval2 will
// reveal it:
var add = new eval2.Function( 'a', 'b', 'return a + b' );

You can pass an options object as the final argument:

var add = new eval2.Function( 'a', 'b', 'return a + b', { sourceMap: { version: 3, ... } });

Notes

The line numbers in node.js error reports will be 1 greater than the actual line number; this is because the code is wrapped in an anonymous function.

Unlike the standard eval, code executed with eval2 will always be executed in the global scope:

(function () {
  // this works...
  var answer = 42;
  eval( 'alert(answer)' );

  // ...but this won't, because `answer` doesn't exist
  // in the global scope
  eval2( 'alert(answer)' );
}());

Similar projects

node-syntax-error by substack finds syntax errors in node programs by attempting to parse them with esprima.

Credits and feedback

Issues, pull requests and feedback welcome. I'm @Rich_Harris on Twitter.

@martypdx figured out how to dynamically generate modules in node.js.

License

MIT.

eval2's People

Contributors

rich-harris avatar

Stargazers

Dylan Piercey avatar Paulo Coghi avatar Michael Anthony avatar Sebastian Werner avatar James Zetlen avatar

Watchers

James Cloos avatar  avatar Michael Anthony avatar  avatar

Forkers

martypdx

eval2's Issues

Doesn't work as expected with compiling TypeScript

var ts = require("typescript");
var content = "let a = 0;\n\n\nb = b * a";
var eval2 = require('eval2');
var compilerOptions = { module: ts.ModuleKind.CommonJS, inlineSourceMap: true };

var res1 = ts.transpileModule(content, {
  compilerOptions: compilerOptions,
  moduleName: "myModule2"
});
console.log(res1);
console.log('-------')
console.log(content)
console.log('-------')
console.log(res1.outputText)
console.log('-------')
var script = res1.outputText;
eval2( script );

It says that error is in line 3 (but should be 4). Here is an output I see after running on node

{ outputText:
   'var a = 0;\nb = b * a;\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kdWxlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsibW9kdWxlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLElBQUksQ0FBQyxHQUFHLENBQUMsQ0FBQztBQUdWLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxDQUFBIn0=',
  diagnostics: [],
  sourceMapText: undefined }
-------
let a = 0;


b = b * a
-------
var a = 0;
b = b * a;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kdWxlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsibW9kdWxlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLElBQUksQ0FBQyxHQUFHLENBQUMsQ0FBQztBQUdWLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxDQUFBIn0=
-------
:3
b = b * a;
^

ReferenceError: b is not defined
    at Module.module.exports (<anonymous>:3:1)
    at locateErrorUsingModule (/root/ts-eval/node_modules/eval2/dist/eval2.js:129:5)
    at eval2 (/root/ts-eval/node_modules/eval2/dist/eval2.js:57:5)
    at Object.<anonymous> (/root/ts-eval/exal.js:17:1)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)

btoa fails with non-Latin1 characters

Repro:

eval2( '1 + 2', {
    sourceMap: {
    version: 3,
    file: 'foo.js',
    sources: [ 'foo.xyz' ],
    sourcesContent: [ 'РЖД' ],
    mappings: 'AACA'
  }
});

Only fails in browser ('Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range').

require("module") breaks bundling

Hi, I'm using jspm and wanted to write a plugin using rcu and rcu-builders for importing Ractive components, but when trying to jspm bundle, it says:

err  Error: Module module not declared as a dependency of /.../myproject/jspm_packages/npm/[email protected]/dist/rcu.umd.js

When forcing JSPM to treat the package as amd:

err  TypeError: Cannot read property 'nodeRequire' of undefined

Both times, the error is in this line. (Not quite, as this dependency is actually bundled into rcu, but it traces back here)

Note 1: I don't know whether to report that in ractivejs/rcu or in here, hope I did it correctly.
Note 2: Do you by chance know of any loader plugin that does this automatically? Or of any way to use rollup-plugin-ractive with JSPM?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.