Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
krismuniz committed Jan 12, 2020
0 parents commit 95e1681
Show file tree
Hide file tree
Showing 10 changed files with 4,259 additions and 0 deletions.
20 changes: 20 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module.exports = {
env: {
commonjs: true,
es6: true,
node: true,
mocha: true
},
extends: [
'standard'
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly'
},
parserOptions: {
ecmaVersion: 2018
},
rules: {
}
}
31 changes: 31 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: build

on: [push]

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node: [12, 13]
steps:
- name: Clone Repo
uses: actions/checkout@v1

- name: Setup Node.js ${{ matrix.node }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node }}

- name: List Versions
run: |
node --version
npm --version
- name: Install Dependencies
run: npm ci

- name: Run Tests & Lint
run: |
npm run test
npm run lint
107 changes: 107 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Kristian Muñiz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
124 changes: 124 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# JS to JSON Logic

[![npm](https://img.shields.io/npm/v/js-to-json-logic.svg?style=flat-square)](https://npm.im/js-to-json-logic) [![License:MIT](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](http://opensource.org/licenses/MIT) [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/krismuniz/js-to-json-logic/build?logo=github&logoColor=white&style=flat-square)](https://github.com/krismuniz/js-to-json-logic/actions?query=workflow%3Abuild) ![Type Declarations](https://img.shields.io/npm/types/js-to-json-logic.svg?style=flat-square)

Transform JavaScript expressions into [JSON Logic](http://jsonlogic.com) objects. For Node.js.

> NOTICE: This module is still in beta!
### Installing

```shell
npm install --save js-to-json-logic
```

### Usage

```js
const transformJS = require("js-to-json-logic");

transformJS('temp < 110 && pie.filling === "apple"');
```

The `transformJS` function returns a JavaScript object, which can be stringified as a JSON and look like this:

```json
{
"and": [
{
"<": [
{
"var": "temp"
},
110
]
},
{
"===": [
{
"var": "pie.filling"
},
"apple"
]
}
]
}
```

### How it Works

To parse input code, this module uses `@babel/parser` and `@babel/traverse` to parse JavaScript code into an [Abstract Syntax Tree (AST)](https://en.wikipedia.org/wiki/Abstract_syntax_tree). The tree is then transformed into a JSON Logic object.

Said object is can then be used with the [`json-logic-js`](https://npmjs.com/package/json-logic-js) module to apply the interpreted rules to any type of data. [Learn More](http://jsonlogic.com)

### Supported JavaScript Syntax

| expression | support | examples |
| ------------------------------ | ------- | -------------------------------------------------------- |
| Boolean Literals | full | `true`, `false` |
| String Literals | full | `"banana"`, `"hello world"` |
| Template Literals | full | <code>\`hello, \${first_name}\`</code> |
| Numeric Literals | full | `1`, `2.04`, `-10292.64`, `0b01011010`, `0xFF00FF`, etc. |
| Object Expressions / Literals | full | `{ a: [1, false, 'string'], b: false, d: 'hello' }` |
| Array Expressions | full | `[1, 2, 3]` |
| Spread Operator in Arrays | full | `[1, 2, ...myArr]` |
| Null Literals | full | `null` |
| Identifiers (variables) | full | `myVar`, `deep.property` |
| Comparison Expressions | full | `a > b`, `a < b`, `a <= b`, `a === b`, `a !== b`, etc. |
| Arithmetic Operators | full | `a + b`, `a * b`, `a - b`, `a / b`, `a % b` |
| Call Expressions | full | `myFunction(a, b, c)` |
| Unary Expressions | full | `!cond`, `!!cond`, `-var`, `+var` |
| Conditional (Ternary) Operator | full | `condition ? a : b` |
| Regex Literal | limited | `/[^@]+@[^\.]+\..+/gi` |
| If Statements | limited | `if (condA) { a } else if (condB) { b } else { c }` |
| Call Expressions with Callback | limited | `map(arr, x => x + 1)` |
| Arrow Functions | limited | `x => x + 1`, `(a, b) => a + b` |

Notes:

- Regex Literals: are not supported by the JSON spec. To account for this, they are converted into an array of strings. The first element of the array is the pattern, the second one contains the flags. Example: `[ "\d\d\d\d", "gi" ]`

- If Statements: Multi-line consequentials (block statements in if statements) are not supported. Also, implicit return will always apply.

- Call Expressions with Callback: Only arrow functions are allowed as callbacks in call expressions.

- Arrow Functions: arrow functions can only be single-line expressions or have a one-line block statement

- If a specific syntactic JS feature is not specified in the table above, it's likely that it isn't supported. If you have an idea on how to support said feature, feel free to file a GitHub Issue.

### Unsupported Syntax

The following syntactic features are not supported by this module.

- Class Declarations
- Update Expressions (`i++`, `i--`, etc.)
- Assignment Expressions
- Tagged Template Expressions
- Function Declaration
- While Loops
- For Loops
- Multi-Line Block Statements
- `new` operator
- Destructuring assignment
- Rest operator
- Spread operator (although it works within array expressions)

### Contributing

#### Bug Reports & Feature Requests

Something does not work as expected or perhaps you think this project _needs_ a feature? Please open an issue using GitHub [issue tracker](https://github.com/krismuniz/js-to-json-logic/issues/new).

Make sure that an issue pointing out your specific problem does not exist already. Please be as specific and straightforward as possible.

#### Pull Requests

Pull Requests (PRs) are welcome! You should follow the [same basic stylistic conventions](http://standardjs.com/rules.html) as the original code.

Make sure that a pull request solving your specific problem does not exist already. Your changes must be concise and focus on solving a discrete problem.

### License

[The MIT License (MIT)](/LICENSE)

Copyright (c) 2020 [Kristian Muñiz](https://www.krismuniz.com)
1 change: 1 addition & 0 deletions js-to-json-logic.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default function transformJS (code: string): any
Loading

0 comments on commit 95e1681

Please sign in to comment.