Coder Social home page Coder Social logo

carsonf / whence Goto Github PK

View Code? Open in Web Editor NEW

This project forked from jonschlinkert/whence

0.0 2.0 0.0 54 KB

Add context awareness to your apps and frameworks by safely evaluating user-defined conditional expressions. Useful for evaluating expressions in config files, prompts, key bindings, completions, templates, and many other user cases.

License: MIT License

JavaScript 100.00%

whence's Introduction

whence NPM version NPM monthly downloads NPM total downloads Tests

Add context awareness to your apps and frameworks by safely evaluating user-defined conditional expressions. Useful for evaluating expressions in config files, prompts, key bindings, completions, templates, and many other user cases.

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your ❤️ and support.

Install

Install with npm (requires Node.js >=14):

$ npm install --save whence

What is whence?

This libarary doest returneth true if thine 'when' clause doest matcheth the granted context object.

Seriously though, what does this library do?

Whence uses eval-estree-expression to safely evaluate user-defined conditional expressions, sometimes referred to as "when" clauses.

Why do I need this?

Add context awareness to your apps and frameworks.

Conditional expressions are useful in config files, creating prompts, determining key bindings, filtering suggestions and completions, variables in templates and snippets, and many other user cases.

It's even more useful when those conditional expressions can be evaluated safely.

Example: configuration files

For example, when authoring configuration files for workflows, pipelines, builds, and so on, it's common for developers to define expressions with conditionals to determine if or when a job, task, or step should run based on environment variables, etc. These configurations are typically defined using YAML, JSON or a similar data format, which means that conditional expressions must be written as strings, booleans, or numbers. Whence makes it safe and easy to evalue these expressions.

Other use cases

  • Templates and snippets - Use whence to conditionally render files, sections, or variables
  • Completions and suggestions - Use whence to filter completions and suggestions in your text editor or prompt system
  • Key bindings - VS Code and other text editors use when clauses or something similar to determine the keybindings to use when a key is pressed.
How safe is it?

No assignment operators, functions, or function calls are allowed by default to make it as safe as possible to evaluate user-defined expressions. To accomplish this, whence uses the eval-estree-expression library, which takes an estree expression from [@babel/parser][], esprima, acorn, or any similar library that parses and returns a valid estree expression.

Why another "eval" library?

What we found

Every other eval library I found had one of the following shortcomings:

  • Uses eval or Node's vm or something similar to evaluate code. This is to risky, or too heavy for our use cases.
  • Functions are either the primary use case or are supported by default. We don't want users to be able to define functions in their config files.
  • Naive attempts to sanitize code before evaluating it
  • Brittle, incomplete, hand-rolled parsers

What whence does differently

  • Whence takes a valid [estree][] expression AST
  • Functions are not supported by default, although you can enable function support (See the eval-estree-expression docs for more details)
  • Special care was taken in eval-estree-expression to disallow assignment operators, functions, or other potentially malicious code, like setting __proto__, constructor, prototype, or undefined as a property name on nested properties.

Usage

const whence = require('whence');

// async usage
console.log(await whence('amount > 100', { amount: 101 }));
console.log(await whence('a < b && c > d', { a: 0, b: 1, c: 3, d: 2 }));
console.log(await whence('platform === "darwin"', { platform: process.platform }));

// sync usage
console.log(whence.sync('amount > 100', { amount: 101 }));
console.log(whence.sync('a < b && c > d', { a: 0, b: 1, c: 3, d: 2 }));
console.log(whence.sync('platform === "darwin"', { platform: process.platform }));

See eval-estree-expression and the eval-estree-expression unit tests for many more examples of the types of expressions that are supported.

API

Returns true if the given value is truthy, or the left value is contained within the right value.

Params

  • left {any}: The value to test.
  • right {Object}: The value to compare against.
  • parent {type}
  • returns {Boolean}: Returns true or false.

Parses the given expression string with [@babel/parser][] and returns and AST. You may also an [estree][]-compatible expression AST.

Params

  • source {String}: Expression string or an [estree][]-compatible expression AST.
  • options {Object}
  • returns {Object}

Example

const { parse } = require('whence');

console.log(parse('platform === "darwin"'));
// Resuls in something like this:
// Node {
//   type: 'BinaryExpression',
//   left: Node { type: 'Identifier', name: 'platform' },
//   operator: '===',
//   right: Node {
//     type: 'StringLiteral',
//     extra: { rawValue: 'darwin', raw: '"darwin"' },
//     value: 'darwin'
//   }
// }

Asynchronously evaluates the given expression and returns a boolean.

Params

  • source {String|Object}: Expression string or an [estree][]-compatible expression AST.
  • context {Object}
  • options {Object}
  • returns {Boolean}

Example

const whence = require('whence');

console.log(await whence('10 < 20')); //=> true
console.log(whence.sync('10 < 20')); //=> true

Synchronous version of whence. Aliased as whence.sync().

Params

  • source {String|Object}: Expression string or an [estree][]-compatible expression AST.
  • context {Object}
  • options {Object}
  • returns {Boolean}

Example

const { whenceSync } = require('whence');

console.log(whenceSync('10 < 20')); //=> true

Compiles the given expression and returns an async function.

Params

  • source {String|Object}: Expression string or an [estree][]-compatible expression AST.
  • options {Object}
  • returns {Function}: Returns a function that takes a context object.

Example

const { compile } = require('whence');
const fn = compile('type === "foo"');

console.log(await fn({ type: 'foo' })); //=> true
console.log(await fn({ type: 'bar' })); //=> false

Synchronous version of compile. This method is also alias as .compile.sync().

Params

  • source {String|Object}: Expression string or an [estree][]-compatible expression AST.
  • options {Object}
  • returns {Function}: Returns a function that takes a context object.

Example

const { compile } = require('whence');
const fn = compile.sync('type === "foo"');

console.log(fn({ type: 'foo' })); //=> true
console.log(fn({ type: 'bar' })); //=> false

Options

Supports all options from eval-estree-expression along with the following whence options.

Examples

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Author

Jon Schlinkert

License

Copyright © 2021, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.8.0, on September 07, 2021.

whence's People

Contributors

jonschlinkert avatar

Watchers

James Cloos avatar  avatar

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.