Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

angular-expressions

peerigon215.4kUnlicense1.4.3TypeScript support: included

Angular expressions as standalone module

angular, expression, parser, lexer, parse, eval, source

readme

angular-expressions

angular's nicest part extracted as a standalone module for the browser and node.

build status

angular-expressions exposes a .compile()-method which can be used to compile evaluable expressions:

var expressions = require("angular-expressions");

evaluate = expressions.compile("1 + 1");
evaluate(); // returns 2

You can also set and get values on a given scope:

evaluate = expressions.compile("name");
scope = { name: "Jenny" };
evaluate(scope); // returns 'Jenny'

evaluate = expressions.compile("ship.pirate.name = 'Störtebeker'");
evaluate(scope); // won't throw an error because angular's expressions are forgiving
console.log(scope.ship.pirate.name); // prints 'Störtebeker'

For assigning values, you can also use .assign():

evaluate = expressions.compile("ship.pirate.name");
evaluate.assign(scope, "Störtebeker");
console.log(scope.ship.pirate.name); // prints 'Störtebeker'

Check out their readme for further information.


Setup

npm status


Filters

Angular provides a mechanism to define filters on expressions:

expressions.filters.uppercase = (input) => input.toUpperCase();

expr = expressions.compile("'arr' | uppercase");
expr(); // returns 'ARR'

Arguments are evaluated against the scope:

expressions.filters.currency = (input, currency, digits) => {
  input = input.toFixed(digits);

  if (currency === "EUR") {
    return input + "€";
  } else {
    return input + "$";
  }
};

expr = expressions.compile("1.2345 | currency:selectedCurrency:2");
expr({
  selectedCurrency: "EUR",
}); // returns '1.23€'

If you need an isolated filters object, this can be achieved by setting the filters attribute in the options argument. Global cache is disabled if using options.filters. To setup an isolated cache, you can also set the cache attribute in the options argument:

var isolatedFilters = {
  transform: (input) => input.toLowerCase(),
};
var isolatedCache = {};

var resultOne = expressions.compile("'Foo Bar' | transform", {
  filters: isolatedFilters,
  cache: isolatedCache,
});

console.log(resultOne()); // prints 'foo bar'
console.log(isolatedCache); // prints '{"'Foo Bar' | transform": [Function fn] }'

API

exports

.compile(src): Function

Compiles src and returns a function evaluate(). The compiled function is cached under compile.cache[src] to speed up further calls.

Compiles also export the AST.

Example output of: compile("tmp + 1").ast

{ type: 'Program',
  body:
   [ { type: 'ExpressionStatement',
       expression:
        { type: 'Identifier',
          name: 'tmp',
          constant: false,
          toWatch: [ [Circular] ] } } ],
  constant: false }

NOTE angular $parse do not export ast variable it's done by this library.

.compile.cache = Object.create(null)

A cache containing all compiled functions. The src is used as key. Set this on false to disable the cache.

.filters = {}

An empty object where you may define your custom filters.

.Lexer

The internal Lexer.

.Parser

The internal Parser.


evaluate(scope?): *

Evaluates the compiled src and returns the result of the expression. Property look-ups or assignments are executed on a given scope.

evaluate.assign(scope, value): *

Tries to assign the given value to the result of the compiled expression on the given scope and returns the result of the assignment.


In the browser

There is no dist build because it's not 2005 anymore. Use a module bundler like webpack or browserify. They're both capable of CommonJS and AMD.


Security

The code of angular was not secured from reading prototype, and since version 1.0.1 of angular-expressions, the module disallows reading properties that are not ownProperties. See this blog post for more details about the sandbox that got removed completely in angular 1.6.

Comment from angular.js/src/ng/parse.js:


Angular expressions are generally considered safe because these expressions only have direct access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by obtaining a reference to native JS functions such as the Function constructor.

As an example, consider the following Angular expression:

{}.toString.constructor(alert("evil JS code"))

We want to prevent this type of access. For the sake of performance, during the lexing phase we disallow any "dotted" access to any member named "constructor".

For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor while evaluating the expression, which is a stronger but more expensive test. Since reflective calls are expensive anyway, this is not such a big deal compared to static dereferencing. This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits against the expression language, but not to prevent exploits that were enabled by exposing sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good practice and therefore we are not even trying to protect against interaction with an object explicitly exposed in this way.

A developer could foil the name check by aliasing the Function constructor under a different name on the scope.

In general, it is not possible to access a Window object from an angular expression unless a window or some DOM object that has a reference to window is published onto a Scope.



Authorship

Kudos go entirely to the great angular.js team, it's their implementation!


Contributing

Suggestions and bug-fixes are always appreciated. Don't hesitate to create an issue or pull-request. All contributed code should pass

  1. the tests in node.js by running npm test
  2. the tests in all major browsers by running npm run test-browser and then visiting http://localhost:8080/bundle

License

Unlicense

Sponsors

changelog

1.4.3

Disallow access to prototype chain (CVE-2024-54152) when using compile with locals (two arguments in the called function) :

compile("__proto__")({}, {});

=> This now returns undefined, previously it would give you the __proto__ instance which would allow Remote Code Execution.

Thanks to @JorianWoltjer who found the vulnerability and reported it.

1.4.2

Make handleThis the default if you use the Lexer and Parser directly, and you don't use .compile.

This is a way less common use case but it makes sense to have handleThis be the same default for both cases.

(This also makes the library behave in the same way between 1.3.0 and 1.4.1 when using Parser or Lexer). There was a backwards incompatible change brought by 1.4.0 for users of Parser.

1.4.1

Don't use this version, it is missing a commit for the 1.4.2 fix

1.4.0

Add support for handleThis: false to disable handling of this.

(By default handleThis is true).

This way, if you write : {this | filter}, the this will be used as a key from the scope, eg scope["this"].

1.3.0

Add support for template literals.

It is now possible to write :

compile("`Hello ${user}`")({ user: "John" });
// Returns "Hello John"

1.2.1

Bugfix compile(tag, { csp: true }) should now work correctly.

1.2.0

Add four options to the second arg of the compile method :

  • compile(tag, {filters: { upper: (input) => input.toUpperCase()}}) which adds filters to a specific instance (those filters are not shared between instances).

  • compile(tag, {cache: {}}) to set a "non global" cache.

  • compile(tag, { csp: true }) to use the interpreter (avoid use of "new Function()" which is for example not allowed in Vercel).

  • compile(tag, {literals: { true: true, false: false, null: null, undefined: undefined } }) which allows to customize literals (such as null, true, false, undefined)

1.1.10

Update typescript typings for "Parser"

1.1.9

Update typescript typings (add .assign method)

1.1.8

Update typescript typings (add filters).

1.1.7

Add typescript typings (for compile, Parser and Lexer).

1.1.6

Published by mistake (same as 1.1.7), but without dependency changes

1.1.5

Add specific error when a filter is not defined.

1.1.4

Bugfix : When using an assignment expression, such as b = a, the value will always be set in the scope, not in the locals.

With this code :

const scope = { a: 10 };
const locals = { b: 5 };
compile("b=a")(scope, locals);

The scope value will be { a: 10, b: 10 } after the evaluation.

In previous versions, the value would be assigned to the locals, meaning locals would be { b: 10 }

1.1.3

Bugfix : Make module ES5 compatible (to work in IE10 for example), by using var instead of const

1.1.2

  • Disallow access to prototype chain (CVE-2021-21277)

1.1.1

Previous version was published with ES6 feature, now the published JS uses ES5 only

1.1.0

  • Add support for special characters by using the following :
function validChars(ch) {
  return (
    (ch >= "a" && ch <= "z") ||
    (ch >= "A" && ch <= "Z") ||
    ch === "_" ||
    ch === "$" ||
    "ÀÈÌÒÙàèìòùÁÉÍÓÚáéíóúÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜŸäëïöüÿß".indexOf(ch) !== -1
  );
}
evaluate = compile("être_embarassé", {
  isIdentifierStart: validChars,
  isIdentifierContinue: validChars,
});

evaluate({ être_embarassé: "Ping" });

1.0.1

  • Disallow access to prototype chain (CVE-2020-5219)

1.0.0

  • Add support for this keyword to write :
evaluate = compile("this + 2")(2); // which gives 4