initial commit
commit
89583e5419
|
@ -0,0 +1,27 @@
|
|||
const https = require('https');
|
||||
const turndown = require('turndown');
|
||||
const { Readability } = require('@mozilla/readability');
|
||||
const JSDOM = require('jsdom').JSDOM;
|
||||
|
||||
service = new turndown();
|
||||
|
||||
const express = require('express')
|
||||
const app = express()
|
||||
const port = 4040
|
||||
|
||||
app.get('/', (req, res) => {
|
||||
url = req.query.url;
|
||||
read_url(url, res);
|
||||
});
|
||||
|
||||
app.listen(port, () => {
|
||||
})
|
||||
|
||||
function read_url(url, res) {
|
||||
JSDOM.fromURL(url).then((document)=>{
|
||||
let reader = new Readability(document.window.document);
|
||||
let article = reader.parse();
|
||||
let result = service.turndown(article.content);
|
||||
res.send(result);
|
||||
});
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
../acorn/bin/acorn
|
|
@ -0,0 +1 @@
|
|||
../escodegen/bin/escodegen.js
|
|
@ -0,0 +1 @@
|
|||
../escodegen/bin/esgenerate.js
|
|
@ -0,0 +1 @@
|
|||
../esprima/bin/esparse.js
|
|
@ -0,0 +1 @@
|
|||
../esprima/bin/esvalidate.js
|
|
@ -0,0 +1 @@
|
|||
../mime/cli.js
|
|
@ -0,0 +1 @@
|
|||
../sshpk/bin/sshpk-conv
|
|
@ -0,0 +1 @@
|
|||
../sshpk/bin/sshpk-sign
|
|
@ -0,0 +1 @@
|
|||
../sshpk/bin/sshpk-verify
|
|
@ -0,0 +1 @@
|
|||
../uuid/bin/uuid
|
|
@ -0,0 +1,208 @@
|
|||
"use strict";
|
||||
|
||||
module.exports = {
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 6
|
||||
},
|
||||
"rules": {
|
||||
// Braces only needed for multi-line arrow function blocks
|
||||
// "arrow-body-style": [2, "as-needed"],
|
||||
|
||||
// Require spacing around =>
|
||||
// "arrow-spacing": 2,
|
||||
|
||||
// Always require spacing around a single line block
|
||||
// "block-spacing": 1,
|
||||
|
||||
// No newline before open brace for a block
|
||||
"brace-style": 2,
|
||||
|
||||
// No space before always a space after a comma
|
||||
"comma-spacing": [2, {"before": false, "after": true}],
|
||||
|
||||
// Commas at the end of the line not the start
|
||||
// "comma-style": 2,
|
||||
|
||||
// Don't require spaces around computed properties
|
||||
// "computed-property-spacing": [2, "never"],
|
||||
|
||||
// Functions must always return something or nothing
|
||||
"consistent-return": 2,
|
||||
|
||||
// Require braces around blocks that start a new line
|
||||
// Note that this rule is likely to be overridden on a per-directory basis
|
||||
// very frequently.
|
||||
// "curly": [2, "multi-line"],
|
||||
|
||||
// Always require a trailing EOL
|
||||
"eol-last": 2,
|
||||
|
||||
// Require function* name()
|
||||
// "generator-star-spacing": [2, {"before": false, "after": true}],
|
||||
|
||||
// Two space indent
|
||||
"indent": [2, 2, { "SwitchCase": 1 }],
|
||||
|
||||
// Space after colon not before in property declarations
|
||||
"key-spacing": [2, { "beforeColon": false, "afterColon": true, "mode": "minimum" }],
|
||||
|
||||
// Unix linebreaks
|
||||
"linebreak-style": [2, "unix"],
|
||||
|
||||
// Always require parenthesis for new calls
|
||||
"new-parens": 2,
|
||||
|
||||
// Use [] instead of Array()
|
||||
// "no-array-constructor": 2,
|
||||
|
||||
// No duplicate arguments in function declarations
|
||||
"no-dupe-args": 2,
|
||||
|
||||
// No duplicate keys in object declarations
|
||||
"no-dupe-keys": 2,
|
||||
|
||||
// No duplicate cases in switch statements
|
||||
"no-duplicate-case": 2,
|
||||
|
||||
// No labels
|
||||
"no-labels": 2,
|
||||
|
||||
// If an if block ends with a return no need for an else block
|
||||
"no-else-return": 2,
|
||||
|
||||
// No empty statements
|
||||
"no-empty": 2,
|
||||
|
||||
// No empty character classes in regex
|
||||
"no-empty-character-class": 2,
|
||||
|
||||
// Disallow empty destructuring
|
||||
"no-empty-pattern": 2,
|
||||
|
||||
// No assiging to exception variable
|
||||
// "no-ex-assign": 2,
|
||||
|
||||
// No using !! where casting to boolean is already happening
|
||||
// "no-extra-boolean-cast": 2,
|
||||
|
||||
// No double semicolon
|
||||
"no-extra-semi": 2,
|
||||
|
||||
// No overwriting defined functions
|
||||
"no-func-assign": 2,
|
||||
|
||||
// Declarations in Program or Function Body
|
||||
"no-inner-declarations": 2,
|
||||
|
||||
// No invalid regular expresions
|
||||
"no-invalid-regexp": 2,
|
||||
|
||||
// No odd whitespace characters
|
||||
"no-irregular-whitespace": 2,
|
||||
|
||||
// No single if block inside an else block
|
||||
"no-lonely-if": 2,
|
||||
|
||||
// No mixing spaces and tabs in indent
|
||||
"no-mixed-spaces-and-tabs": [2, "smart-tabs"],
|
||||
|
||||
// No unnecessary spacing
|
||||
"no-multi-spaces": [2, { exceptions: { "AssignmentExpression": true, "VariableDeclarator": true, "ArrayExpression": true, "ObjectExpression": true } }],
|
||||
|
||||
// No reassigning native JS objects
|
||||
"no-native-reassign": 2,
|
||||
|
||||
// No (!foo in bar)
|
||||
"no-negated-in-lhs": 2,
|
||||
|
||||
// Nested ternary statements are confusing
|
||||
"no-nested-ternary": 2,
|
||||
|
||||
// Use {} instead of new Object()
|
||||
// "no-new-object": 2,
|
||||
|
||||
// No Math() or JSON()
|
||||
"no-obj-calls": 2,
|
||||
|
||||
// No octal literals
|
||||
"no-octal": 2,
|
||||
|
||||
// No redeclaring variables
|
||||
"no-redeclare": 2,
|
||||
|
||||
// No unnecessary comparisons
|
||||
"no-self-compare": 2,
|
||||
|
||||
// No declaring variables from an outer scope
|
||||
"no-shadow": 2,
|
||||
|
||||
// No declaring variables that hide things like arguments
|
||||
"no-shadow-restricted-names": 2,
|
||||
|
||||
// No spaces between function name and parentheses
|
||||
"no-spaced-func": 2,
|
||||
|
||||
// No trailing whitespace
|
||||
"no-trailing-spaces": 2,
|
||||
|
||||
// No using undeclared variables
|
||||
// "no-undef": 2,
|
||||
|
||||
// Error on newline where a semicolon is needed
|
||||
"no-unexpected-multiline": 2,
|
||||
|
||||
// No unreachable statements
|
||||
"no-unreachable": 2,
|
||||
|
||||
// No expressions where a statement is expected
|
||||
// "no-unused-expressions": 2,
|
||||
|
||||
// No declaring variables that are never used
|
||||
"no-unused-vars": [2, {"vars": "all", "args": "none"}],
|
||||
|
||||
// No using variables before defined
|
||||
// "no-use-before-define": [2, "nofunc"],
|
||||
|
||||
// No using with
|
||||
"no-with": 2,
|
||||
|
||||
// No if/while/for blocks on the same line as the if/while/for statement:
|
||||
"nonblock-statement-body-position": [2, "below"],
|
||||
|
||||
// Always require semicolon at end of statement
|
||||
"semi": [2, "always"],
|
||||
|
||||
// Require space after keywords
|
||||
"keyword-spacing": 2,
|
||||
|
||||
// Always use double quotes
|
||||
"quotes": [2, "double", {"avoidEscape": true}],
|
||||
|
||||
// Require space before blocks
|
||||
"space-before-blocks": 2,
|
||||
|
||||
// Never use spaces before function parentheses
|
||||
// "space-before-function-paren": [2, { "anonymous": "always", "named": "never" }],
|
||||
|
||||
// Require spaces before finally, catch, etc.
|
||||
// "space-before-keywords": [2, "always"],
|
||||
|
||||
// No space padding in parentheses
|
||||
// "space-in-parens": [2, "never"],
|
||||
|
||||
// Require spaces around operators
|
||||
// "space-infix-ops": 2,
|
||||
|
||||
// Require spaces after return, throw and case
|
||||
// "space-return-throw-case": 2,
|
||||
|
||||
// ++ and -- should not need spacing
|
||||
// "space-unary-ops": [2, { "words": true, "nonwords": false }],
|
||||
|
||||
// No comparisons to NaN
|
||||
"use-isnan": 2,
|
||||
|
||||
// Only check typeof against valid results
|
||||
"valid-typeof": 2,
|
||||
},
|
||||
};
|
|
@ -0,0 +1,15 @@
|
|||
# Community Participation Guidelines
|
||||
|
||||
This repository is governed by Mozilla's code of conduct and etiquette guidelines.
|
||||
For more details, please read the
|
||||
[Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/).
|
||||
|
||||
## How to Report
|
||||
For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page.
|
||||
|
||||
<!--
|
||||
## Project Specific Etiquette
|
||||
|
||||
In some cases, there will be additional project etiquette i.e.: (https://bugzilla.mozilla.org/page.cgi?id=etiquette.html).
|
||||
Please update for your project.
|
||||
-->
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,139 @@
|
|||
# Readability.js
|
||||
|
||||
A standalone version of the readability library used for Firefox Reader View.
|
||||
|
||||
## Usage on the web
|
||||
|
||||
To parse a document, you must create a new `Readability` object from a DOM document object, and then call `parse()`. Here's an example:
|
||||
|
||||
```javascript
|
||||
var article = new Readability(document).parse();
|
||||
```
|
||||
|
||||
This `article` object will contain the following properties:
|
||||
|
||||
* `title`: article title
|
||||
* `content`: HTML string of processed article content
|
||||
* `length`: length of an article, in characters
|
||||
* `excerpt`: article description, or short excerpt from the content
|
||||
* `byline`: author metadata
|
||||
* `dir`: content direction
|
||||
|
||||
If you're using Readability on the web, you will likely be able to use a `document` reference
|
||||
from elsewhere (e.g. fetched via XMLHttpRequest, in a same-origin `<iframe>` you have access to, etc.).
|
||||
|
||||
### Optional
|
||||
|
||||
Readability's `parse()` works by modifying the DOM. This removes some elements in the web page.
|
||||
You could avoid this by passing the clone of the `document` object while creating a `Readability` object.
|
||||
|
||||
```
|
||||
var documentClone = document.cloneNode(true);
|
||||
var article = new Readability(documentClone).parse();
|
||||
```
|
||||
|
||||
## Usage from Node.js
|
||||
|
||||
Readability is available on npm:
|
||||
|
||||
```bash
|
||||
npm install @mozilla/readability
|
||||
```
|
||||
|
||||
In Node.js, you won't generally have a DOM document object. To obtain one, you can use external
|
||||
libraries like [jsdom](https://github.com/jsdom/jsdom). While this repository contains a parser of
|
||||
its own (`JSDOMParser`), that is restricted to reading XML-compatible markup and therefore we do
|
||||
not recommend it for general use.
|
||||
|
||||
If you're using `jsdom` to create a DOM object, you should ensure that the page doesn't run (page)
|
||||
scripts (avoid fetching remote resources etc.) as well as passing it the page's URI as the `url`
|
||||
property of the `options` object you pass the `JSDOM` constructor.
|
||||
|
||||
### Example:
|
||||
|
||||
```js
|
||||
var { Readability } = require('@mozilla/readability');
|
||||
var JSDOM = require('jsdom').JSDOM;
|
||||
var doc = new JSDOM("<body>Here's a bunch of text</body>", {
|
||||
url: "https://www.example.com/the-page-i-got-the-source-from"
|
||||
});
|
||||
let reader = new Readability(doc.window.document);
|
||||
let article = reader.parse();
|
||||
```
|
||||
|
||||
## What's Readability-readerable?
|
||||
|
||||
It's a quick-and-dirty way of figuring out if it's plausible that the contents of a given
|
||||
document are suitable for processing with Readability. It is likely to produce both false
|
||||
positives and false negatives. The reason it exists is to avoid bogging down a time-sensitive
|
||||
process (like loading and showing the user a webpage) with the complex logic in the core of
|
||||
Readability. Improvements to its logic (while not deteriorating its performance) are very
|
||||
welcome.
|
||||
|
||||
## Security
|
||||
|
||||
If you're going to use Readability with untrusted input (whether in HTML or DOM form), we
|
||||
**strongly** recommend you use a sanitizer library like
|
||||
[DOMPurify](https://github.com/cure53/DOMPurify) to avoid script injection when you use
|
||||
the output of Readability. We would also recommend using
|
||||
[CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) to add further defense-in-depth
|
||||
restrictions to what you allow the resulting content to do. The Firefox integration of
|
||||
reader mode uses both of these techniques itself. Sanitizing unsafe content out of the input
|
||||
is explicitly not something we aim to do as part of Readability itself - there are other
|
||||
good sanitizer libraries out there, use them!
|
||||
|
||||
## Contributing
|
||||
|
||||
[![Build Status](https://travis-ci.org/mozilla/readability.svg?branch=master)](https://travis-ci.org/mozilla/readability)
|
||||
|
||||
For outstanding issues, see the issue list in this repo, as well as this [bug list](https://bugzilla.mozilla.org/buglist.cgi?component=Reader%20Mode&product=Toolkit&bug_status=__open__&limit=0).
|
||||
|
||||
Any changes to Readability.js itself should be reviewed by an [appropriate Firefox/toolkit peer](https://wiki.mozilla.org/Modules/Firefox), such as [@gijsk](https://github.com/gijsk), since these changes will be merged to mozilla-central and shipped in Firefox.
|
||||
|
||||
To test local changes to Readability.js, you can use the [automated tests](#tests). There's a [node script](https://github.com/mozilla/readability/blob/master/test/generate-testcase.js) to help you create new ones.
|
||||
|
||||
## Tests
|
||||
|
||||
Please run [eslint](http://eslint.org/) as a first check that your changes are valid JS and adhere to our style guidelines.
|
||||
|
||||
To run the test suite:
|
||||
|
||||
$ mocha test/test-*.js
|
||||
|
||||
To run a specific test page by its name:
|
||||
|
||||
$ mocha test/test-*.js -g 001
|
||||
|
||||
To run the test suite in TDD mode:
|
||||
|
||||
$ mocha test/test-*.js -w
|
||||
|
||||
Combo time:
|
||||
|
||||
$ mocha test/test-*.js -w -g 001
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Benchmarks for all test pages:
|
||||
|
||||
$ npm run perf
|
||||
|
||||
Reference benchmark:
|
||||
|
||||
$ npm run perf-reference
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2010 Arc90 Inc
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,99 @@
|
|||
/* eslint-env es6:false */
|
||||
/*
|
||||
* Copyright (c) 2010 Arc90 Inc
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This code is heavily based on Arc90's readability.js (1.7.1) script
|
||||
* available at: http://code.google.com/p/arc90labs-readability
|
||||
*/
|
||||
|
||||
var REGEXPS = {
|
||||
// NOTE: These two regular expressions are duplicated in
|
||||
// Readability.js. Please keep both copies in sync.
|
||||
unlikelyCandidates: /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i,
|
||||
okMaybeItsACandidate: /and|article|body|column|content|main|shadow/i,
|
||||
};
|
||||
|
||||
function isNodeVisible(node) {
|
||||
// Have to null-check node.style and node.className.indexOf to deal with SVG and MathML nodes.
|
||||
return (!node.style || node.style.display != "none")
|
||||
&& !node.hasAttribute("hidden")
|
||||
//check for "fallback-image" so that wikimedia math images are displayed
|
||||
&& (!node.hasAttribute("aria-hidden") || node.getAttribute("aria-hidden") != "true" || (node.className && node.className.indexOf && node.className.indexOf("fallback-image") !== -1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides whether or not the document is reader-able without parsing the whole thing.
|
||||
*
|
||||
* @return boolean Whether or not we suspect Readability.parse() will suceeed at returning an article object.
|
||||
*/
|
||||
function isProbablyReaderable(doc, isVisible) {
|
||||
if (!isVisible) {
|
||||
isVisible = isNodeVisible;
|
||||
}
|
||||
|
||||
var nodes = doc.querySelectorAll("p, pre");
|
||||
|
||||
// Get <div> nodes which have <br> node(s) and append them into the `nodes` variable.
|
||||
// Some articles' DOM structures might look like
|
||||
// <div>
|
||||
// Sentences<br>
|
||||
// <br>
|
||||
// Sentences<br>
|
||||
// </div>
|
||||
var brNodes = doc.querySelectorAll("div > br");
|
||||
if (brNodes.length) {
|
||||
var set = new Set(nodes);
|
||||
[].forEach.call(brNodes, function(node) {
|
||||
set.add(node.parentNode);
|
||||
});
|
||||
nodes = Array.from(set);
|
||||
}
|
||||
|
||||
var score = 0;
|
||||
// This is a little cheeky, we use the accumulator 'score' to decide what to return from
|
||||
// this callback:
|
||||
return [].some.call(nodes, function(node) {
|
||||
if (!isVisible(node))
|
||||
return false;
|
||||
|
||||
var matchString = node.className + " " + node.id;
|
||||
if (REGEXPS.unlikelyCandidates.test(matchString) &&
|
||||
!REGEXPS.okMaybeItsACandidate.test(matchString)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (node.matches("li p")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var textContentLength = node.textContent.trim().length;
|
||||
if (textContentLength < 140) {
|
||||
return false;
|
||||
}
|
||||
|
||||
score += Math.sqrt(textContentLength - 140);
|
||||
|
||||
if (score > 20) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof module === "object") {
|
||||
module.exports = isProbablyReaderable;
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,7 @@
|
|||
var Readability = require("./Readability");
|
||||
var isProbablyReaderable = require("./Readability-readerable");
|
||||
|
||||
module.exports = {
|
||||
Readability: Readability,
|
||||
isProbablyReaderable: isProbablyReaderable
|
||||
};
|
|
@ -0,0 +1,63 @@
|
|||
{
|
||||
"_from": "@mozilla/readability",
|
||||
"_id": "@mozilla/readability@0.3.0",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-q8f1CAZsRKK1j+O0BmikGIlKSK03RpT4woT0PCQwhw0nH0z4+rG026AkxoPcjT7Dsgh1ifGscW8tOpvjoyOjvw==",
|
||||
"_location": "/@mozilla/readability",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "tag",
|
||||
"registry": true,
|
||||
"raw": "@mozilla/readability",
|
||||
"name": "@mozilla/readability",
|
||||
"escapedName": "@mozilla%2freadability",
|
||||
"scope": "@mozilla",
|
||||
"rawSpec": "",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "latest"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"#USER",
|
||||
"/"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.3.0.tgz",
|
||||
"_shasum": "a473790e8b42ea39f9f03703fa1f17fec7984b60",
|
||||
"_spec": "@mozilla/readability",
|
||||
"_where": "/home/centos/markdown",
|
||||
"author": "",
|
||||
"bugs": {
|
||||
"url": "https://github.com/mozilla/readability/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"deprecated": false,
|
||||
"description": "A standalone version of the readability library used for Firefox Reader View.",
|
||||
"devDependencies": {
|
||||
"chai": "^2.1.*",
|
||||
"eslint": ">=4.2",
|
||||
"htmltidy2": "^0.3.0",
|
||||
"js-beautify": "^1.5.5",
|
||||
"jsdom": "^13.1",
|
||||
"matcha": "^0.6.0",
|
||||
"mocha": "^2.2.*",
|
||||
"sinon": "^7.3.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"homepage": "https://github.com/mozilla/readability",
|
||||
"license": "Apache-2.0",
|
||||
"main": "index.js",
|
||||
"name": "@mozilla/readability",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/mozilla/readability.git"
|
||||
},
|
||||
"scripts": {
|
||||
"generate-testcase": "node test/generate-testcase.js",
|
||||
"lint": "eslint .",
|
||||
"perf": "matcha benchmarks/benchmarks.js",
|
||||
"perf-reference": "READABILITY_PERF_REFERENCE=1 matcha --reporter ./benchmarks/benchmark-reporter.js benchmarks/benchmarks.js",
|
||||
"test": "mocha test/test-*.js"
|
||||
},
|
||||
"version": "0.3.0"
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
## 2.0.5
|
||||
|
||||
- Use a lookup string in atobLookup and btoaLookup (@GiovanniFrigo in #38)
|
||||
- Dependency updates
|
||||
|
||||
## 2.0.4
|
||||
|
||||
- Dependency updates
|
||||
|
||||
## 2.0.3
|
||||
|
||||
- Use standard wording for BSD-3-Clause license (@PhilippWendler)
|
||||
|
||||
## 2.0.2
|
||||
|
||||
- Correct license in `package.json` (@Haegin)
|
||||
|
||||
## 2.0.1
|
||||
|
||||
- Add TypeScript type definitions, thanks to @LinusU
|
||||
|
||||
## 2.0.0
|
||||
|
||||
Modernization updates thanks to @TimothyGu:
|
||||
|
||||
- Use jsdom's eslint config, remove jscs
|
||||
- Move syntax to ES6
|
||||
- Remove Babel
|
||||
- Via: https://github.com/jsdom/abab/pull/26
|
||||
|
||||
## 1.0.4
|
||||
|
||||
- Added license file
|
||||
|
||||
## 1.0.3
|
||||
|
||||
- Replaced `let` with `var` in `lib/btoa.js`
|
||||
- Follow up from `1.0.2`
|
||||
- Resolves https://github.com/jsdom/abab/issues/18
|
||||
|
||||
## 1.0.2
|
||||
|
||||
- Replaced `const` with `var` in `index.js`
|
||||
- Allows use of `abab` in the browser without a transpilation step
|
||||
- Resolves https://github.com/jsdom/abab/issues/15
|
|
@ -0,0 +1,13 @@
|
|||
Copyright © 2019 W3C and Jeff Carpenter \<jeffcarp@chromium.org\>
|
||||
|
||||
Both the original source code and new contributions in this repository are released under the [3-Clause BSD license](https://opensource.org/licenses/BSD-3-Clause).
|
||||
|
||||
# The 3-Clause BSD License
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@ -0,0 +1,51 @@
|
|||
# abab [![npm version](https://badge.fury.io/js/abab.svg)](https://www.npmjs.com/package/abab) [![Build Status](https://travis-ci.org/jsdom/abab.svg?branch=master)](https://travis-ci.org/jsdom/abab)
|
||||
|
||||
A JavaScript module that implements `window.atob` and `window.btoa` according the forgiving-base64 algorithm in the [Infra Standard](https://infra.spec.whatwg.org/#forgiving-base64). The original code was forked from [w3c/web-platform-tests](https://github.com/w3c/web-platform-tests/blob/master/html/webappapis/atob/base64.html).
|
||||
|
||||
Compatibility: Node.js version 3+ and all major browsers.
|
||||
|
||||
Install with `npm`:
|
||||
|
||||
```sh
|
||||
npm install abab
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### `btoa` (base64 encode)
|
||||
|
||||
```js
|
||||
const { btoa } = require('abab');
|
||||
btoa('Hello, world!'); // 'SGVsbG8sIHdvcmxkIQ=='
|
||||
```
|
||||
|
||||
### `atob` (base64 decode)
|
||||
|
||||
```js
|
||||
const { atob } = require('abab');
|
||||
atob('SGVsbG8sIHdvcmxkIQ=='); // 'Hello, world!'
|
||||
```
|
||||
|
||||
#### Valid characters
|
||||
|
||||
[Per the spec](https://html.spec.whatwg.org/multipage/webappapis.html#atob:dom-windowbase64-btoa-3), `btoa` will accept strings "containing only characters in the range `U+0000` to `U+00FF`." If passed a string with characters above `U+00FF`, `btoa` will return `null`. If `atob` is passed a string that is not base64-valid, it will also return `null`. In both cases when `null` is returned, the spec calls for throwing a `DOMException` of type `InvalidCharacterError`.
|
||||
|
||||
## Browsers
|
||||
|
||||
If you want to include just one of the methods to save bytes in your client-side code, you can `require` the desired module directly.
|
||||
|
||||
```js
|
||||
const atob = require('abab/lib/atob');
|
||||
const btoa = require('abab/lib/btoa');
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
If you're **submitting a PR** or **deploying to npm**, please use the [checklists in CONTRIBUTING.md](CONTRIBUTING.md#checklists).
|
||||
|
||||
## Remembering what `atob` and `btoa` stand for
|
||||
|
||||
Base64 comes from IETF [RFC 4648](https://tools.ietf.org/html/rfc4648#section-4) (2006).
|
||||
|
||||
- **`btoa`**, the encoder function, stands for **binary** to **ASCII**, meaning it converts any binary input into a subset of **ASCII** (Base64).
|
||||
- **`atob`**, the decoder function, converts **ASCII** (or Base64) to its original **binary** format.
|
|
@ -0,0 +1,2 @@
|
|||
export function atob(encodedData: string): string | null
|
||||
export function btoa(stringToEncode: string): string | null
|
|
@ -0,0 +1,9 @@
|
|||
"use strict";
|
||||
|
||||
const atob = require("./lib/atob");
|
||||
const btoa = require("./lib/btoa");
|
||||
|
||||
module.exports = {
|
||||
atob,
|
||||
btoa
|
||||
};
|
|
@ -0,0 +1,97 @@
|
|||
"use strict";
|
||||
|
||||
/**
|
||||
* Implementation of atob() according to the HTML and Infra specs, except that
|
||||
* instead of throwing INVALID_CHARACTER_ERR we return null.
|
||||
*/
|
||||
function atob(data) {
|
||||
// Web IDL requires DOMStrings to just be converted using ECMAScript
|
||||
// ToString, which in our case amounts to using a template literal.
|
||||
data = `${data}`;
|
||||
// "Remove all ASCII whitespace from data."
|
||||
data = data.replace(/[ \t\n\f\r]/g, "");
|
||||
// "If data's length divides by 4 leaving no remainder, then: if data ends
|
||||
// with one or two U+003D (=) code points, then remove them from data."
|
||||
if (data.length % 4 === 0) {
|
||||
data = data.replace(/==?$/, "");
|
||||
}
|
||||
// "If data's length divides by 4 leaving a remainder of 1, then return
|
||||
// failure."
|
||||
//
|
||||
// "If data contains a code point that is not one of
|
||||
//
|
||||
// U+002B (+)
|
||||
// U+002F (/)
|
||||
// ASCII alphanumeric
|
||||
//
|
||||
// then return failure."
|
||||
if (data.length % 4 === 1 || /[^+/0-9A-Za-z]/.test(data)) {
|
||||
return null;
|
||||
}
|
||||
// "Let output be an empty byte sequence."
|
||||
let output = "";
|
||||
// "Let buffer be an empty buffer that can have bits appended to it."
|
||||
//
|
||||
// We append bits via left-shift and or. accumulatedBits is used to track
|
||||
// when we've gotten to 24 bits.
|
||||
let buffer = 0;
|
||||
let accumulatedBits = 0;
|
||||
// "Let position be a position variable for data, initially pointing at the
|
||||
// start of data."
|
||||
//
|
||||
// "While position does not point past the end of data:"
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
// "Find the code point pointed to by position in the second column of
|
||||
// Table 1: The Base 64 Alphabet of RFC 4648. Let n be the number given in
|
||||
// the first cell of the same row.
|
||||
//
|
||||
// "Append to buffer the six bits corresponding to n, most significant bit
|
||||
// first."
|
||||
//
|
||||
// atobLookup() implements the table from RFC 4648.
|
||||
buffer <<= 6;
|
||||
buffer |= atobLookup(data[i]);
|
||||
accumulatedBits += 6;
|
||||
// "If buffer has accumulated 24 bits, interpret them as three 8-bit
|
||||
// big-endian numbers. Append three bytes with values equal to those
|
||||
// numbers to output, in the same order, and then empty buffer."
|
||||
if (accumulatedBits === 24) {
|
||||
output += String.fromCharCode((buffer & 0xff0000) >> 16);
|
||||
output += String.fromCharCode((buffer & 0xff00) >> 8);
|
||||
output += String.fromCharCode(buffer & 0xff);
|
||||
buffer = accumulatedBits = 0;
|
||||
}
|
||||
// "Advance position by 1."
|
||||
}
|
||||
// "If buffer is not empty, it contains either 12 or 18 bits. If it contains
|
||||
// 12 bits, then discard the last four and interpret the remaining eight as
|
||||
// an 8-bit big-endian number. If it contains 18 bits, then discard the last
|
||||
// two and interpret the remaining 16 as two 8-bit big-endian numbers. Append
|
||||
// the one or two bytes with values equal to those one or two numbers to
|
||||
// output, in the same order."
|
||||
if (accumulatedBits === 12) {
|
||||
buffer >>= 4;
|
||||
output += String.fromCharCode(buffer);
|
||||
} else if (accumulatedBits === 18) {
|
||||
buffer >>= 2;
|
||||
output += String.fromCharCode((buffer & 0xff00) >> 8);
|
||||
output += String.fromCharCode(buffer & 0xff);
|
||||
}
|
||||
// "Return output."
|
||||
return output;
|
||||
}
|
||||
/**
|
||||
* A lookup table for atob(), which converts an ASCII character to the
|
||||
* corresponding six-bit number.
|
||||
*/
|
||||
|
||||
const keystr =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
function atobLookup(chr) {
|
||||
const index = keystr.indexOf(chr);
|
||||
// Throw exception if character is not in the lookup string; should not be hit in tests
|
||||
return index < 0 ? undefined : index;
|
||||
}
|
||||
|
||||
module.exports = atob;
|
|
@ -0,0 +1,58 @@
|
|||
"use strict";
|
||||
|
||||
/**
|
||||
* btoa() as defined by the HTML and Infra specs, which mostly just references
|
||||
* RFC 4648.
|
||||
*/
|
||||
function btoa(s) {
|
||||
let i;
|
||||
// String conversion as required by Web IDL.
|
||||
s = `${s}`;
|
||||
// "The btoa() method must throw an "InvalidCharacterError" DOMException if
|
||||
// data contains any character whose code point is greater than U+00FF."
|
||||
for (i = 0; i < s.length; i++) {
|
||||
if (s.charCodeAt(i) > 255) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
let out = "";
|
||||
for (i = 0; i < s.length; i += 3) {
|
||||
const groupsOfSix = [undefined, undefined, undefined, undefined];
|
||||
groupsOfSix[0] = s.charCodeAt(i) >> 2;
|
||||
groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4;
|
||||
if (s.length > i + 1) {
|
||||
groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4;
|
||||
groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2;
|
||||
}
|
||||
if (s.length > i + 2) {
|
||||
groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6;
|
||||
groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f;
|
||||
}
|
||||
for (let j = 0; j < groupsOfSix.length; j++) {
|
||||
if (typeof groupsOfSix[j] === "undefined") {
|
||||
out += "=";
|
||||
} else {
|
||||
out += btoaLookup(groupsOfSix[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lookup table for btoa(), which converts a six-bit number into the
|
||||
* corresponding ASCII character.
|
||||
*/
|
||||
const keystr =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
function btoaLookup(index) {
|
||||
if (index >= 0 && index < 64) {
|
||||
return keystr[index];
|
||||
}
|
||||
|
||||
// Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests.
|
||||
return undefined;
|
||||
}
|
||||
|
||||
module.exports = btoa;
|
|
@ -0,0 +1,71 @@
|
|||
{
|
||||
"_from": "abab@^2.0.3",
|
||||
"_id": "abab@2.0.5",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q==",
|
||||
"_location": "/abab",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "abab@^2.0.3",
|
||||
"name": "abab",
|
||||
"escapedName": "abab",
|
||||
"rawSpec": "^2.0.3",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^2.0.3"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/data-urls",
|
||||
"/jsdom"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/abab/-/abab-2.0.5.tgz",
|
||||
"_shasum": "c0b678fb32d60fc1219c784d6a826fe385aeb79a",
|
||||
"_spec": "abab@^2.0.3",
|
||||
"_where": "/home/centos/markdown/node_modules/jsdom",
|
||||
"author": {
|
||||
"name": "Jeff Carpenter",
|
||||
"email": "gcarpenterv@gmail.com"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/jsdom/abab/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"deprecated": false,
|
||||
"description": "WHATWG spec-compliant implementations of window.atob and window.btoa.",
|
||||
"devDependencies": {
|
||||
"eslint": "^4.19.1",
|
||||
"karma": "^2.0.0",
|
||||
"karma-cli": "^1.0.1",
|
||||
"karma-firefox-launcher": "^1.1.0",
|
||||
"karma-mocha": "^1.3.0",
|
||||
"karma-webpack": "^3.0.0",
|
||||
"mocha": "^5.1.0",
|
||||
"webpack": "^4.5.0"
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"index.js",
|
||||
"lib/"
|
||||
],
|
||||
"homepage": "https://github.com/jsdom/abab#readme",
|
||||
"keywords": [
|
||||
"atob",
|
||||
"btoa",
|
||||
"browser"
|
||||
],
|
||||
"license": "BSD-3-Clause",
|
||||
"main": "index.js",
|
||||
"name": "abab",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/jsdom/abab.git"
|
||||
},
|
||||
"scripts": {
|
||||
"karma": "karma start",
|
||||
"lint": "eslint .",
|
||||
"mocha": "mocha test/node",
|
||||
"test": "npm run lint && npm run mocha && npm run karma"
|
||||
},
|
||||
"version": "2.0.5"
|
||||
}
|
|
@ -0,0 +1,236 @@
|
|||
1.3.7 / 2019-04-29
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.6.2
|
||||
- Fix sorting charset, encoding, and language with extra parameters
|
||||
|
||||
1.3.6 / 2019-04-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.24
|
||||
- deps: mime-db@~1.40.0
|
||||
|
||||
1.3.5 / 2018-02-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.18
|
||||
- deps: mime-db@~1.33.0
|
||||
|
||||
1.3.4 / 2017-08-22
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.16
|
||||
- deps: mime-db@~1.29.0
|
||||
|
||||
1.3.3 / 2016-05-02
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.11
|
||||
- deps: mime-db@~1.23.0
|
||||
* deps: negotiator@0.6.1
|
||||
- perf: improve `Accept` parsing speed
|
||||
- perf: improve `Accept-Charset` parsing speed
|
||||
- perf: improve `Accept-Encoding` parsing speed
|
||||
- perf: improve `Accept-Language` parsing speed
|
||||
|
||||
1.3.2 / 2016-03-08
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.10
|
||||
- Fix extension of `application/dash+xml`
|
||||
- Update primary extension for `audio/mp4`
|
||||
- deps: mime-db@~1.22.0
|
||||
|
||||
1.3.1 / 2016-01-19
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.9
|
||||
- deps: mime-db@~1.21.0
|
||||
|
||||
1.3.0 / 2015-09-29
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.7
|
||||
- deps: mime-db@~1.19.0
|
||||
* deps: negotiator@0.6.0
|
||||
- Fix including type extensions in parameters in `Accept` parsing
|
||||
- Fix parsing `Accept` parameters with quoted equals
|
||||
- Fix parsing `Accept` parameters with quoted semicolons
|
||||
- Lazy-load modules from main entry point
|
||||
- perf: delay type concatenation until needed
|
||||
- perf: enable strict mode
|
||||
- perf: hoist regular expressions
|
||||
- perf: remove closures getting spec properties
|
||||
- perf: remove a closure from media type parsing
|
||||
- perf: remove property delete from media type parsing
|
||||
|
||||
1.2.13 / 2015-09-06
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.6
|
||||
- deps: mime-db@~1.18.0
|
||||
|
||||
1.2.12 / 2015-07-30
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.4
|
||||
- deps: mime-db@~1.16.0
|
||||
|
||||
1.2.11 / 2015-07-16
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.3
|
||||
- deps: mime-db@~1.15.0
|
||||
|
||||
1.2.10 / 2015-07-01
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.2
|
||||
- deps: mime-db@~1.14.0
|
||||
|
||||
1.2.9 / 2015-06-08
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.1
|
||||
- perf: fix deopt during mapping
|
||||
|
||||
1.2.8 / 2015-06-07
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.0
|
||||
- deps: mime-db@~1.13.0
|
||||
* perf: avoid argument reassignment & argument slice
|
||||
* perf: avoid negotiator recursive construction
|
||||
* perf: enable strict mode
|
||||
* perf: remove unnecessary bitwise operator
|
||||
|
||||
1.2.7 / 2015-05-10
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.5.3
|
||||
- Fix media type parameter matching to be case-insensitive
|
||||
|
||||
1.2.6 / 2015-05-07
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.11
|
||||
- deps: mime-db@~1.9.1
|
||||
* deps: negotiator@0.5.2
|
||||
- Fix comparing media types with quoted values
|
||||
- Fix splitting media types with quoted commas
|
||||
|
||||
1.2.5 / 2015-03-13
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.10
|
||||
- deps: mime-db@~1.8.0
|
||||
|
||||
1.2.4 / 2015-02-14
|
||||
==================
|
||||
|
||||
* Support Node.js 0.6
|
||||
* deps: mime-types@~2.0.9
|
||||
- deps: mime-db@~1.7.0
|
||||
* deps: negotiator@0.5.1
|
||||
- Fix preference sorting to be stable for long acceptable lists
|
||||
|
||||
1.2.3 / 2015-01-31
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.8
|
||||
- deps: mime-db@~1.6.0
|
||||
|
||||
1.2.2 / 2014-12-30
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.7
|
||||
- deps: mime-db@~1.5.0
|
||||
|
||||
1.2.1 / 2014-12-30
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.5
|
||||
- deps: mime-db@~1.3.1
|
||||
|
||||
1.2.0 / 2014-12-19
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.5.0
|
||||
- Fix list return order when large accepted list
|
||||
- Fix missing identity encoding when q=0 exists
|
||||
- Remove dynamic building of Negotiator class
|
||||
|
||||
1.1.4 / 2014-12-10
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.4
|
||||
- deps: mime-db@~1.3.0
|
||||
|
||||
1.1.3 / 2014-11-09
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.3
|
||||
- deps: mime-db@~1.2.0
|
||||
|
||||
1.1.2 / 2014-10-14
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.9
|
||||
- Fix error when media type has invalid parameter
|
||||
|
||||
1.1.1 / 2014-09-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.2
|
||||
- deps: mime-db@~1.1.0
|
||||
* deps: negotiator@0.4.8
|
||||
- Fix all negotiations to be case-insensitive
|
||||
- Stable sort preferences of same quality according to client order
|
||||
|
||||
1.1.0 / 2014-09-02
|
||||
==================
|
||||
|
||||
* update `mime-types`
|
||||
|
||||
1.0.7 / 2014-07-04
|
||||
==================
|
||||
|
||||
* Fix wrong type returned from `type` when match after unknown extension
|
||||
|
||||
1.0.6 / 2014-06-24
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.7
|
||||
|
||||
1.0.5 / 2014-06-20
|
||||
==================
|
||||
|
||||
* fix crash when unknown extension given
|
||||
|
||||
1.0.4 / 2014-06-19
|
||||
==================
|
||||
|
||||
* use `mime-types`
|
||||
|
||||
1.0.3 / 2014-06-11
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.6
|
||||
- Order by specificity when quality is the same
|
||||
|
||||
1.0.2 / 2014-05-29
|
||||
==================
|
||||
|
||||
* Fix interpretation when header not in request
|
||||
* deps: pin negotiator@0.4.5
|
||||
|
||||
1.0.1 / 2014-01-18
|
||||
==================
|
||||
|
||||
* Identity encoding isn't always acceptable
|
||||
* deps: negotiator@~0.4.0
|
||||
|
||||
1.0.0 / 2013-12-27
|
||||
==================
|
||||
|
||||
* Genesis
|
|
@ -0,0 +1,23 @@
|
|||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
|
||||
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
|
||||
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.
|
|
@ -0,0 +1,142 @@
|
|||
# accepts
|
||||
|
||||
[![NPM Version][npm-version-image]][npm-url]
|
||||
[![NPM Downloads][npm-downloads-image]][npm-url]
|
||||
[![Node.js Version][node-version-image]][node-version-url]
|
||||
[![Build Status][travis-image]][travis-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator).
|
||||
Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
|
||||
|
||||
In addition to negotiator, it allows:
|
||||
|
||||
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])`
|
||||
as well as `('text/html', 'application/json')`.
|
||||
- Allows type shorthands such as `json`.
|
||||
- Returns `false` when no types match
|
||||
- Treats non-existent headers as `*`
|
||||
|
||||
## Installation
|
||||
|
||||
This is a [Node.js](https://nodejs.org/en/) module available through the
|
||||
[npm registry](https://www.npmjs.com/). Installation is done using the
|
||||
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
|
||||
|
||||
```sh
|
||||
$ npm install accepts
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
<!-- eslint-disable no-unused-vars -->
|
||||
|
||||
```js
|
||||
var accepts = require('accepts')
|
||||
```
|
||||
|
||||
### accepts(req)
|
||||
|
||||
Create a new `Accepts` object for the given `req`.
|
||||
|
||||
#### .charset(charsets)
|
||||
|
||||
Return the first accepted charset. If nothing in `charsets` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .charsets()
|
||||
|
||||
Return the charsets that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .encoding(encodings)
|
||||
|
||||
Return the first accepted encoding. If nothing in `encodings` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .encodings()
|
||||
|
||||
Return the encodings that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .language(languages)
|
||||
|
||||
Return the first accepted language. If nothing in `languages` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .languages()
|
||||
|
||||
Return the languages that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .type(types)
|
||||
|
||||
Return the first accepted type (and it is returned as the same text as what
|
||||
appears in the `types` array). If nothing in `types` is accepted, then `false`
|
||||
is returned.
|
||||
|
||||
The `types` array can contain full MIME types or file extensions. Any value
|
||||
that is not a full MIME types is passed to `require('mime-types').lookup`.
|
||||
|
||||
#### .types()
|
||||
|
||||
Return the types that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
## Examples
|
||||
|
||||
### Simple type negotiation
|
||||
|
||||
This simple example shows how to use `accepts` to return a different typed
|
||||
respond body based on what the client wants to accept. The server lists it's
|
||||
preferences in order and will get back the best match between the client and
|
||||
server.
|
||||
|
||||
```js
|
||||
var accepts = require('accepts')
|
||||
var http = require('http')
|
||||
|
||||
function app (req, res) {
|
||||
var accept = accepts(req)
|
||||
|
||||
// the order of this list is significant; should be server preferred order
|
||||
switch (accept.type(['json', 'html'])) {
|
||||
case 'json':
|
||||
res.setHeader('Content-Type', 'application/json')
|
||||
res.write('{"hello":"world!"}')
|
||||
break
|
||||
case 'html':
|
||||
res.setHeader('Content-Type', 'text/html')
|
||||
res.write('<b>hello, world!</b>')
|
||||
break
|
||||
default:
|
||||
// the fallback is text/plain, so no need to specify it above
|
||||
res.setHeader('Content-Type', 'text/plain')
|
||||
res.write('hello, world!')
|
||||
break
|
||||
}
|
||||
|
||||
res.end()
|
||||
}
|
||||
|
||||
http.createServer(app).listen(3000)
|
||||
```
|
||||
|
||||
You can test this out with the cURL program:
|
||||
```sh
|
||||
curl -I -H'Accept: text/html' http://localhost:3000/
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master
|
||||
[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master
|
||||
[node-version-image]: https://badgen.net/npm/node/accepts
|
||||
[node-version-url]: https://nodejs.org/en/download
|
||||
[npm-downloads-image]: https://badgen.net/npm/dm/accepts
|
||||
[npm-url]: https://npmjs.org/package/accepts
|
||||
[npm-version-image]: https://badgen.net/npm/v/accepts
|
||||
[travis-image]: https://badgen.net/travis/jshttp/accepts/master
|
||||
[travis-url]: https://travis-ci.org/jshttp/accepts
|
|
@ -0,0 +1,238 @@
|
|||
/*!
|
||||
* accepts
|
||||
* Copyright(c) 2014 Jonathan Ong
|
||||
* Copyright(c) 2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var Negotiator = require('negotiator')
|
||||
var mime = require('mime-types')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @public
|
||||
*/
|
||||
|
||||
module.exports = Accepts
|
||||
|
||||
/**
|
||||
* Create a new Accepts object for the given req.
|
||||
*
|
||||
* @param {object} req
|
||||
* @public
|
||||
*/
|
||||
|
||||
function Accepts (req) {
|
||||
if (!(this instanceof Accepts)) {
|
||||
return new Accepts(req)
|
||||
}
|
||||
|
||||
this.headers = req.headers
|
||||
this.negotiator = new Negotiator(req)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given `type(s)` is acceptable, returning
|
||||
* the best match when true, otherwise `undefined`, in which
|
||||
* case you should respond with 406 "Not Acceptable".
|
||||
*
|
||||
* The `type` value may be a single mime type string
|
||||
* such as "application/json", the extension name
|
||||
* such as "json" or an array `["json", "html", "text/plain"]`. When a list
|
||||
* or array is given the _best_ match, if any is returned.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* // Accept: text/html
|
||||
* this.types('html');
|
||||
* // => "html"
|
||||
*
|
||||
* // Accept: text/*, application/json
|
||||
* this.types('html');
|
||||
* // => "html"
|
||||
* this.types('text/html');
|
||||
* // => "text/html"
|
||||
* this.types('json', 'text');
|
||||
* // => "json"
|
||||
* this.types('application/json');
|
||||
* // => "application/json"
|
||||
*
|
||||
* // Accept: text/*, application/json
|
||||
* this.types('image/png');
|
||||
* this.types('png');
|
||||
* // => undefined
|
||||
*
|
||||
* // Accept: text/*;q=.5, application/json
|
||||
* this.types(['html', 'json']);
|
||||
* this.types('html', 'json');
|
||||
* // => "json"
|
||||
*
|
||||
* @param {String|Array} types...
|
||||
* @return {String|Array|Boolean}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.type =
|
||||
Accepts.prototype.types = function (types_) {
|
||||
var types = types_
|
||||
|
||||
// support flattened arguments
|
||||
if (types && !Array.isArray(types)) {
|
||||
types = new Array(arguments.length)
|
||||
for (var i = 0; i < types.length; i++) {
|
||||
types[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no types, return all requested types
|
||||
if (!types || types.length === 0) {
|
||||
return this.negotiator.mediaTypes()
|
||||
}
|
||||
|
||||
// no accept header, return first given type
|
||||
if (!this.headers.accept) {
|
||||
return types[0]
|
||||
}
|
||||
|
||||
var mimes = types.map(extToMime)
|
||||
var accepts = this.negotiator.mediaTypes(mimes.filter(validMime))
|
||||
var first = accepts[0]
|
||||
|
||||
return first
|
||||
? types[mimes.indexOf(first)]
|
||||
: false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted encodings or best fit based on `encodings`.
|
||||
*
|
||||
* Given `Accept-Encoding: gzip, deflate`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['gzip', 'deflate']
|
||||
*
|
||||
* @param {String|Array} encodings...
|
||||
* @return {String|Array}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.encoding =
|
||||
Accepts.prototype.encodings = function (encodings_) {
|
||||
var encodings = encodings_
|
||||
|
||||
// support flattened arguments
|
||||
if (encodings && !Array.isArray(encodings)) {
|
||||
encodings = new Array(arguments.length)
|
||||
for (var i = 0; i < encodings.length; i++) {
|
||||
encodings[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no encodings, return all requested encodings
|
||||
if (!encodings || encodings.length === 0) {
|
||||
return this.negotiator.encodings()
|
||||
}
|
||||
|
||||
return this.negotiator.encodings(encodings)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted charsets or best fit based on `charsets`.
|
||||
*
|
||||
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['utf-8', 'utf-7', 'iso-8859-1']
|
||||
*
|
||||
* @param {String|Array} charsets...
|
||||
* @return {String|Array}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.charset =
|
||||
Accepts.prototype.charsets = function (charsets_) {
|
||||
var charsets = charsets_
|
||||
|
||||
// support flattened arguments
|
||||
if (charsets && !Array.isArray(charsets)) {
|
||||
charsets = new Array(arguments.length)
|
||||
for (var i = 0; i < charsets.length; i++) {
|
||||
charsets[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no charsets, return all requested charsets
|
||||
if (!charsets || charsets.length === 0) {
|
||||
return this.negotiator.charsets()
|
||||
}
|
||||
|
||||
return this.negotiator.charsets(charsets)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted languages or best fit based on `langs`.
|
||||
*
|
||||
* Given `Accept-Language: en;q=0.8, es, pt`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['es', 'pt', 'en']
|
||||
*
|
||||
* @param {String|Array} langs...
|
||||
* @return {Array|String}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.lang =
|
||||
Accepts.prototype.langs =
|
||||
Accepts.prototype.language =
|
||||
Accepts.prototype.languages = function (languages_) {
|
||||
var languages = languages_
|
||||
|
||||
// support flattened arguments
|
||||
if (languages && !Array.isArray(languages)) {
|
||||
languages = new Array(arguments.length)
|
||||
for (var i = 0; i < languages.length; i++) {
|
||||
languages[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no languages, return all requested languages
|
||||
if (!languages || languages.length === 0) {
|
||||
return this.negotiator.languages()
|
||||
}
|
||||
|
||||
return this.negotiator.languages(languages)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert extnames to mime.
|
||||
*
|
||||
* @param {String} type
|
||||
* @return {String}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function extToMime (type) {
|
||||
return type.indexOf('/') === -1
|
||||
? mime.lookup(type)
|
||||
: type
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if mime is valid.
|
||||
*
|
||||
* @param {String} type
|
||||
* @return {String}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function validMime (type) {
|
||||
return typeof type === 'string'
|
||||
}
|
|
@ -0,0 +1,86 @@
|
|||
{
|
||||
"_from": "accepts@~1.3.7",
|
||||
"_id": "accepts@1.3.7",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==",
|
||||
"_location": "/accepts",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "accepts@~1.3.7",
|
||||
"name": "accepts",
|
||||
"escapedName": "accepts",
|
||||
"rawSpec": "~1.3.7",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "~1.3.7"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/express"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz",
|
||||
"_shasum": "531bc726517a3b2b41f850021c6cc15eaab507cd",
|
||||
"_spec": "accepts@~1.3.7",
|
||||
"_where": "/home/centos/markdown/node_modules/express",
|
||||
"bugs": {
|
||||
"url": "https://github.com/jshttp/accepts/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Douglas Christopher Wilson",
|
||||
"email": "doug@somethingdoug.com"
|
||||
},
|
||||
{
|
||||
"name": "Jonathan Ong",
|
||||
"email": "me@jongleberry.com",
|
||||
"url": "http://jongleberry.com"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"mime-types": "~2.1.24",
|
||||
"negotiator": "0.6.2"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Higher-level content negotiation",
|
||||
"devDependencies": {
|
||||
"deep-equal": "1.0.1",
|
||||
"eslint": "5.16.0",
|
||||
"eslint-config-standard": "12.0.0",
|
||||
"eslint-plugin-import": "2.17.2",
|
||||
"eslint-plugin-markdown": "1.0.0",
|
||||
"eslint-plugin-node": "8.0.1",
|
||||
"eslint-plugin-promise": "4.1.1",
|
||||
"eslint-plugin-standard": "4.0.0",
|
||||
"mocha": "6.1.4",
|
||||
"nyc": "14.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"HISTORY.md",
|
||||
"index.js"
|
||||
],
|
||||
"homepage": "https://github.com/jshttp/accepts#readme",
|
||||
"keywords": [
|
||||
"content",
|
||||
"negotiation",
|
||||
"accept",
|
||||
"accepts"
|
||||
],
|
||||
"license": "MIT",
|
||||
"name": "accepts",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/jshttp/accepts.git"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint --plugin markdown --ext js,md .",
|
||||
"test": "mocha --reporter spec --check-leaks --bail test/",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test",
|
||||
"test-travis": "nyc --reporter=text npm test"
|
||||
},
|
||||
"version": "1.3.7"
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
Copyright (c) 2014 Forbes Lindesay
|
||||
|
||||
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.
|
|
@ -0,0 +1,81 @@
|
|||
# acorn-globals
|
||||
|
||||
Detect global variables in JavaScript using acorn
|
||||
|
||||
[Get supported acorn-globals with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-acorn_globals?utm_source=npm-acorn-globals&utm_medium=referral&utm_campaign=readme)
|
||||
|
||||
[![Build Status](https://img.shields.io/travis/ForbesLindesay/acorn-globals/master.svg)](https://travis-ci.org/ForbesLindesay/acorn-globals)
|
||||
[![Dependency Status](https://img.shields.io/david/ForbesLindesay/acorn-globals.svg)](https://david-dm.org/ForbesLindesay/acorn-globals)
|
||||
[![NPM version](https://img.shields.io/npm/v/acorn-globals.svg)](https://www.npmjs.org/package/acorn-globals)
|
||||
|
||||
## Installation
|
||||
|
||||
npm install acorn-globals
|
||||
|
||||
## Usage
|
||||
|
||||
detect.js
|
||||
|
||||
```js
|
||||
var fs = require('fs');
|
||||
var detect = require('acorn-globals');
|
||||
|
||||
var src = fs.readFileSync(__dirname + '/input.js', 'utf8');
|
||||
|
||||
var scope = detect(src);
|
||||
console.dir(scope);
|
||||
```
|
||||
|
||||
input.js
|
||||
|
||||
```js
|
||||
var x = 5;
|
||||
var y = 3, z = 2;
|
||||
|
||||
w.foo();
|
||||
w = 2;
|
||||
|
||||
RAWR=444;
|
||||
RAWR.foo();
|
||||
|
||||
BLARG=3;
|
||||
|
||||
foo(function () {
|
||||
var BAR = 3;
|
||||
process.nextTick(function (ZZZZZZZZZZZZ) {
|
||||
console.log('beep boop');
|
||||
var xyz = 4;
|
||||
x += 10;
|
||||
x.zzzzzz;
|
||||
ZZZ=6;
|
||||
});
|
||||
function doom () {
|
||||
}
|
||||
ZZZ.foo();
|
||||
|
||||
});
|
||||
|
||||
console.log(xyz);
|
||||
```
|
||||
|
||||
output:
|
||||
|
||||
```
|
||||
$ node example/detect.js
|
||||
[ { name: 'BLARG', nodes: [ [Object] ] },
|
||||
{ name: 'RAWR', nodes: [ [Object], [Object] ] },
|
||||
{ name: 'ZZZ', nodes: [ [Object], [Object] ] },
|
||||
{ name: 'console', nodes: [ [Object], [Object] ] },
|
||||
{ name: 'foo', nodes: [ [Object] ] },
|
||||
{ name: 'process', nodes: [ [Object] ] },
|
||||
{ name: 'w', nodes: [ [Object], [Object] ] },
|
||||
{ name: 'xyz', nodes: [ [Object] ] } ]
|
||||
```
|
||||
|
||||
## Security contact information
|
||||
|
||||
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
|
@ -0,0 +1,179 @@
|
|||
'use strict';
|
||||
|
||||
var acorn = require('acorn');
|
||||
var walk = require('acorn-walk');
|
||||
|
||||
function isScope(node) {
|
||||
return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration' || node.type === 'ArrowFunctionExpression' || node.type === 'Program';
|
||||
}
|
||||
function isBlockScope(node) {
|
||||
return node.type === 'BlockStatement' || isScope(node);
|
||||
}
|
||||
|
||||
function declaresArguments(node) {
|
||||
return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration';
|
||||
}
|
||||
|
||||
function declaresThis(node) {
|
||||
return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration';
|
||||
}
|
||||
|
||||
function reallyParse(source, options) {
|
||||
var parseOptions = Object.assign({}, options,
|
||||
{
|
||||
allowReturnOutsideFunction: true,
|
||||
allowImportExportEverywhere: true,
|
||||
allowHashBang: true
|
||||
}
|
||||
);
|
||||
return acorn.parse(source, parseOptions);
|
||||
}
|
||||
module.exports = findGlobals;
|
||||
module.exports.parse = reallyParse;
|
||||
function findGlobals(source, options) {
|
||||
options = options || {};
|
||||
var globals = [];
|
||||
var ast;
|
||||
// istanbul ignore else
|
||||
if (typeof source === 'string') {
|
||||
ast = reallyParse(source, options);
|
||||
} else {
|
||||
ast = source;
|
||||
}
|
||||
// istanbul ignore if
|
||||
if (!(ast && typeof ast === 'object' && ast.type === 'Program')) {
|
||||
throw new TypeError('Source must be either a string of JavaScript or an acorn AST');
|
||||
}
|
||||
var declareFunction = function (node) {
|
||||
var fn = node;
|
||||
fn.locals = fn.locals || Object.create(null);
|
||||
node.params.forEach(function (node) {
|
||||
declarePattern(node, fn);
|
||||
});
|
||||
if (node.id) {
|
||||
fn.locals[node.id.name] = true;
|
||||
}
|
||||
};
|
||||
var declareClass = function (node) {
|
||||
node.locals = node.locals || Object.create(null);
|
||||
if (node.id) {
|
||||
node.locals[node.id.name] = true;
|
||||
}
|
||||
};
|
||||
var declarePattern = function (node, parent) {
|
||||
switch (node.type) {
|
||||
case 'Identifier':
|
||||
parent.locals[node.name] = true;
|
||||
break;
|
||||
case 'ObjectPattern':
|
||||
node.properties.forEach(function (node) {
|
||||
declarePattern(node.value || node.argument, parent);
|
||||
});
|
||||
break;
|
||||
case 'ArrayPattern':
|
||||
node.elements.forEach(function (node) {
|
||||
if (node) declarePattern(node, parent);
|
||||
});
|
||||
break;
|
||||
case 'RestElement':
|
||||
declarePattern(node.argument, parent);
|
||||
break;
|
||||
case 'AssignmentPattern':
|
||||
declarePattern(node.left, parent);
|
||||
break;
|
||||
// istanbul ignore next
|
||||
default:
|
||||
throw new Error('Unrecognized pattern type: ' + node.type);
|
||||
}
|
||||
};
|
||||
var declareModuleSpecifier = function (node, parents) {
|
||||
ast.locals = ast.locals || Object.create(null);
|
||||
ast.locals[node.local.name] = true;
|
||||
};
|
||||
walk.ancestor(ast, {
|
||||
'VariableDeclaration': function (node, parents) {
|
||||
var parent = null;
|
||||
for (var i = parents.length - 1; i >= 0 && parent === null; i--) {
|
||||
if (node.kind === 'var' ? isScope(parents[i]) : isBlockScope(parents[i])) {
|
||||
parent = parents[i];
|
||||
}
|
||||
}
|
||||
parent.locals = parent.locals || Object.create(null);
|
||||
node.declarations.forEach(function (declaration) {
|
||||
declarePattern(declaration.id, parent);
|
||||
});
|
||||
},
|
||||
'FunctionDeclaration': function (node, parents) {
|
||||
var parent = null;
|
||||
for (var i = parents.length - 2; i >= 0 && parent === null; i--) {
|
||||
if (isScope(parents[i])) {
|
||||
parent = parents[i];
|
||||
}
|
||||
}
|
||||
parent.locals = parent.locals || Object.create(null);
|
||||
if (node.id) {
|
||||
parent.locals[node.id.name] = true;
|
||||
}
|
||||
declareFunction(node);
|
||||
},
|
||||
'Function': declareFunction,
|
||||
'ClassDeclaration': function (node, parents) {
|
||||
var parent = null;
|
||||
for (var i = parents.length - 2; i >= 0 && parent === null; i--) {
|
||||
if (isBlockScope(parents[i])) {
|
||||
parent = parents[i];
|
||||
}
|
||||
}
|
||||
parent.locals = parent.locals || Object.create(null);
|
||||
if (node.id) {
|
||||
parent.locals[node.id.name] = true;
|
||||
}
|
||||
declareClass(node);
|
||||
},
|
||||
'Class': declareClass,
|
||||
'TryStatement': function (node) {
|
||||
if (node.handler === null) return;
|
||||
node.handler.locals = node.handler.locals || Object.create(null);
|
||||
declarePattern(node.handler.param, node.handler);
|
||||
},
|
||||
'ImportDefaultSpecifier': declareModuleSpecifier,
|
||||
'ImportSpecifier': declareModuleSpecifier,
|
||||
'ImportNamespaceSpecifier': declareModuleSpecifier
|
||||
});
|
||||
function identifier(node, parents) {
|
||||
var name = node.name;
|
||||
if (name === 'undefined') return;
|
||||
for (var i = 0; i < parents.length; i++) {
|
||||
if (name === 'arguments' && declaresArguments(parents[i])) {
|
||||
return;
|
||||
}
|
||||
if (parents[i].locals && name in parents[i].locals) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
node.parents = parents.slice();
|
||||
globals.push(node);
|
||||
}
|
||||
walk.ancestor(ast, {
|
||||
'VariablePattern': identifier,
|
||||
'Identifier': identifier,
|
||||
'ThisExpression': function (node, parents) {
|
||||
for (var i = 0; i < parents.length; i++) {
|
||||
if (declaresThis(parents[i])) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
node.parents = parents.slice();
|
||||
globals.push(node);
|
||||
}
|
||||
});
|
||||
var groupedGlobals = Object.create(null);
|
||||
globals.forEach(function (node) {
|
||||
var name = node.type === 'ThisExpression' ? 'this' : node.name;
|
||||
groupedGlobals[name] = (groupedGlobals[name] || []);
|
||||
groupedGlobals[name].push(node);
|
||||
});
|
||||
return Object.keys(groupedGlobals).sort().map(function (name) {
|
||||
return {name: name, nodes: groupedGlobals[name]};
|
||||
});
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
{
|
||||
"_from": "acorn-globals@^6.0.0",
|
||||
"_id": "acorn-globals@6.0.0",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-ZQl7LOWaF5ePqqcX4hLuv/bLXYQNfNWw2c0/yX/TsPRKamzHcTGQnlCjHT3TsmkOUVEPS3crCxiPfdzE/Trlhg==",
|
||||
"_location": "/acorn-globals",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "acorn-globals@^6.0.0",
|
||||
"name": "acorn-globals",
|
||||
"escapedName": "acorn-globals",
|
||||
"rawSpec": "^6.0.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^6.0.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/jsdom"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-6.0.0.tgz",
|
||||
"_shasum": "46cdd39f0f8ff08a876619b55f5ac8a6dc770b45",
|
||||
"_spec": "acorn-globals@^6.0.0",
|
||||
"_where": "/home/centos/markdown/node_modules/jsdom",
|
||||
"author": {
|
||||
"name": "ForbesLindesay"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/ForbesLindesay/acorn-globals/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"acorn": "^7.1.1",
|
||||
"acorn-walk": "^7.1.1"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Detect global variables in JavaScript using acorn",
|
||||
"devDependencies": {
|
||||
"testit": "^3.1.0"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"LICENSE"
|
||||
],
|
||||
"homepage": "https://github.com/ForbesLindesay/acorn-globals#readme",
|
||||
"keywords": [
|
||||
"ast",
|
||||
"variable",
|
||||
"name",
|
||||
"lexical",
|
||||
"scope",
|
||||
"local",
|
||||
"global",
|
||||
"implicit"
|
||||
],
|
||||
"license": "MIT",
|
||||
"name": "acorn-globals",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/ForbesLindesay/acorn-globals.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node test"
|
||||
},
|
||||
"version": "6.0.0"
|
||||
}
|
|
@ -0,0 +1,131 @@
|
|||
## 7.2.0 (2020-06-17)
|
||||
|
||||
### New features
|
||||
|
||||
Support optional chaining and nullish coalescing.
|
||||
|
||||
Support `import.meta`.
|
||||
|
||||
Add support for `export * as ns from "source"`.
|
||||
|
||||
## 7.1.1 (2020-02-13)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Clean up the type definitions to actually work well with the main parser.
|
||||
|
||||
## 7.1.0 (2020-02-11)
|
||||
|
||||
### New features
|
||||
|
||||
Add a TypeScript definition file for the library.
|
||||
|
||||
## 7.0.0 (2017-08-12)
|
||||
|
||||
### New features
|
||||
|
||||
Support walking `ImportExpression` nodes.
|
||||
|
||||
## 6.2.0 (2017-07-04)
|
||||
|
||||
### New features
|
||||
|
||||
Add support for `Import` nodes.
|
||||
|
||||
## 6.1.0 (2018-09-28)
|
||||
|
||||
### New features
|
||||
|
||||
The walker now walks `TemplateElement` nodes.
|
||||
|
||||
## 6.0.1 (2018-09-14)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix bad "main" field in package.json.
|
||||
|
||||
## 6.0.0 (2018-09-14)
|
||||
|
||||
### Breaking changes
|
||||
|
||||
This is now a separate package, `acorn-walk`, rather than part of the main `acorn` package.
|
||||
|
||||
The `ScopeBody` and `ScopeExpression` meta-node-types are no longer supported.
|
||||
|
||||
## 5.7.1 (2018-06-15)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Make sure the walker and bin files are rebuilt on release (the previous release didn't get the up-to-date versions).
|
||||
|
||||
## 5.7.0 (2018-06-15)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix crash in walker when walking a binding-less catch node.
|
||||
|
||||
## 5.6.2 (2018-06-05)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
In the walker, go back to allowing the `baseVisitor` argument to be null to default to the default base everywhere.
|
||||
|
||||
## 5.6.1 (2018-06-01)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix regression when passing `null` as fourth argument to `walk.recursive`.
|
||||
|
||||
## 5.6.0 (2018-05-31)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix a bug in the walker that caused a crash when walking an object pattern spread.
|
||||
|
||||
## 5.5.1 (2018-03-06)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix regression in walker causing property values in object patterns to be walked as expressions.
|
||||
|
||||
## 5.5.0 (2018-02-27)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Support object spread in the AST walker.
|
||||
|
||||
## 5.4.1 (2018-02-02)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
5.4.0 somehow accidentally included an old version of walk.js.
|
||||
|
||||
## 5.2.0 (2017-10-30)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
The `full` and `fullAncestor` walkers no longer visit nodes multiple times.
|
||||
|
||||
## 5.1.0 (2017-07-05)
|
||||
|
||||
### New features
|
||||
|
||||
New walker functions `full` and `fullAncestor`.
|
||||
|
||||
## 3.2.0 (2016-06-07)
|
||||
|
||||
### New features
|
||||
|
||||
Make it possible to use `visit.ancestor` with a walk state.
|
||||
|
||||
## 3.1.0 (2016-04-18)
|
||||
|
||||
### New features
|
||||
|
||||
The walker now allows defining handlers for `CatchClause` nodes.
|
||||
|
||||
## 2.5.2 (2015-10-27)
|
||||
|
||||
### Fixes
|
||||
|
||||
Fix bug where the walker walked an exported `let` statement as an expression.
|
|
@ -0,0 +1,19 @@
|
|||
Copyright (C) 2012-2018 by various contributors (see AUTHORS)
|
||||
|
||||
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.
|
|
@ -0,0 +1,126 @@
|
|||
# Acorn AST walker
|
||||
|
||||
An abstract syntax tree walker for the
|
||||
[ESTree](https://github.com/estree/estree) format.
|
||||
|
||||
## Community
|
||||
|
||||
Acorn is open source software released under an
|
||||
[MIT license](https://github.com/acornjs/acorn/blob/master/acorn-walk/LICENSE).
|
||||
|
||||
You are welcome to
|
||||
[report bugs](https://github.com/acornjs/acorn/issues) or create pull
|
||||
requests on [github](https://github.com/acornjs/acorn). For questions
|
||||
and discussion, please use the
|
||||
[Tern discussion forum](https://discuss.ternjs.net).
|
||||
|
||||
## Installation
|
||||
|
||||
The easiest way to install acorn is from [`npm`](https://www.npmjs.com/):
|
||||
|
||||
```sh
|
||||
npm install acorn-walk
|
||||
```
|
||||
|
||||
Alternately, you can download the source and build acorn yourself:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/acornjs/acorn.git
|
||||
cd acorn
|
||||
npm install
|
||||
```
|
||||
|
||||
## Interface
|
||||
|
||||
An algorithm for recursing through a syntax tree is stored as an
|
||||
object, with a property for each tree node type holding a function
|
||||
that will recurse through such a node. There are several ways to run
|
||||
such a walker.
|
||||
|
||||
**simple**`(node, visitors, base, state)` does a 'simple' walk over a
|
||||
tree. `node` should be the AST node to walk, and `visitors` an object
|
||||
with properties whose names correspond to node types in the [ESTree
|
||||
spec](https://github.com/estree/estree). The properties should contain
|
||||
functions that will be called with the node object and, if applicable
|
||||
the state at that point. The last two arguments are optional. `base`
|
||||
is a walker algorithm, and `state` is a start state. The default
|
||||
walker will simply visit all statements and expressions and not
|
||||
produce a meaningful state. (An example of a use of state is to track
|
||||
scope at each point in the tree.)
|
||||
|
||||
```js
|
||||
const acorn = require("acorn")
|
||||
const walk = require("acorn-walk")
|
||||
|
||||
walk.simple(acorn.parse("let x = 10"), {
|
||||
Literal(node) {
|
||||
console.log(`Found a literal: ${node.value}`)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**ancestor**`(node, visitors, base, state)` does a 'simple' walk over
|
||||
a tree, building up an array of ancestor nodes (including the current node)
|
||||
and passing the array to the callbacks as a third parameter.
|
||||
|
||||
```js
|
||||
const acorn = require("acorn")
|
||||
const walk = require("acorn-walk")
|
||||
|
||||
walk.ancestor(acorn.parse("foo('hi')"), {
|
||||
Literal(_, ancestors) {
|
||||
console.log("This literal's ancestors are:", ancestors.map(n => n.type))
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**recursive**`(node, state, functions, base)` does a 'recursive'
|
||||
walk, where the walker functions are responsible for continuing the
|
||||
walk on the child nodes of their target node. `state` is the start
|
||||
state, and `functions` should contain an object that maps node types
|
||||
to walker functions. Such functions are called with `(node, state, c)`
|
||||
arguments, and can cause the walk to continue on a sub-node by calling
|
||||
the `c` argument on it with `(node, state)` arguments. The optional
|
||||
`base` argument provides the fallback walker functions for node types
|
||||
that aren't handled in the `functions` object. If not given, the
|
||||
default walkers will be used.
|
||||
|
||||
**make**`(functions, base)` builds a new walker object by using the
|
||||
walker functions in `functions` and filling in the missing ones by
|
||||
taking defaults from `base`.
|
||||
|
||||
**full**`(node, callback, base, state)` does a 'full' walk over a
|
||||
tree, calling the callback with the arguments (node, state, type) for
|
||||
each node
|
||||
|
||||
**fullAncestor**`(node, callback, base, state)` does a 'full' walk
|
||||
over a tree, building up an array of ancestor nodes (including the
|
||||
current node) and passing the array to the callbacks as a third
|
||||
parameter.
|
||||
|
||||
```js
|
||||
const acorn = require("acorn")
|
||||
const walk = require("acorn-walk")
|
||||
|
||||
walk.full(acorn.parse("1 + 1"), node => {
|
||||
console.log(`There's a ${node.type} node at ${node.ch}`)
|
||||
})
|
||||
```
|
||||
|
||||
**findNodeAt**`(node, start, end, test, base, state)` tries to locate
|
||||
a node in a tree at the given start and/or end offsets, which
|
||||
satisfies the predicate `test`. `start` and `end` can be either `null`
|
||||
(as wildcard) or a number. `test` may be a string (indicating a node
|
||||
type) or a function that takes `(nodeType, node)` arguments and
|
||||
returns a boolean indicating whether this node is interesting. `base`
|
||||
and `state` are optional, and can be used to specify a custom walker.
|
||||
Nodes are tested from inner to outer, so if two nodes match the
|
||||
boundaries, the inner one will be preferred.
|
||||
|
||||
**findNodeAround**`(node, pos, test, base, state)` is a lot like
|
||||
`findNodeAt`, but will match any node that exists 'around' (spanning)
|
||||
the given position.
|
||||
|
||||
**findNodeAfter**`(node, pos, test, base, state)` is similar to
|
||||
`findNodeAround`, but will match all nodes *after* the given position
|
||||
(testing outer nodes before inner nodes).
|
|
@ -0,0 +1,112 @@
|
|||
import {Node} from 'acorn';
|
||||
|
||||
declare module "acorn-walk" {
|
||||
type FullWalkerCallback<TState> = (
|
||||
node: Node,
|
||||
state: TState,
|
||||
type: string
|
||||
) => void;
|
||||
|
||||
type FullAncestorWalkerCallback<TState> = (
|
||||
node: Node,
|
||||
state: TState | Node[],
|
||||
ancestors: Node[],
|
||||
type: string
|
||||
) => void;
|
||||
type WalkerCallback<TState> = (node: Node, state: TState) => void;
|
||||
|
||||
type SimpleWalkerFn<TState> = (
|
||||
node: Node,
|
||||
state: TState
|
||||
) => void;
|
||||
|
||||
type AncestorWalkerFn<TState> = (
|
||||
node: Node,
|
||||
state: TState| Node[],
|
||||
ancestors: Node[]
|
||||
) => void;
|
||||
|
||||
type RecursiveWalkerFn<TState> = (
|
||||
node: Node,
|
||||
state: TState,
|
||||
callback: WalkerCallback<TState>
|
||||
) => void;
|
||||
|
||||
type SimpleVisitors<TState> = {
|
||||
[type: string]: SimpleWalkerFn<TState>
|
||||
};
|
||||
|
||||
type AncestorVisitors<TState> = {
|
||||
[type: string]: AncestorWalkerFn<TState>
|
||||
};
|
||||
|
||||
type RecursiveVisitors<TState> = {
|
||||
[type: string]: RecursiveWalkerFn<TState>
|
||||
};
|
||||
|
||||
type FindPredicate = (type: string, node: Node) => boolean;
|
||||
|
||||
interface Found<TState> {
|
||||
node: Node,
|
||||
state: TState
|
||||
}
|
||||
|
||||
export function simple<TState>(
|
||||
node: Node,
|
||||
visitors: SimpleVisitors<TState>,
|
||||
base?: RecursiveVisitors<TState>,
|
||||
state?: TState
|
||||
): void;
|
||||
|
||||
export function ancestor<TState>(
|
||||
node: Node,
|
||||
visitors: AncestorVisitors<TState>,
|
||||
base?: RecursiveVisitors<TState>,
|
||||
state?: TState
|
||||
): void;
|
||||
|
||||
export function recursive<TState>(
|
||||
node: Node,
|
||||
state: TState,
|
||||
functions: RecursiveVisitors<TState>,
|
||||
base?: RecursiveVisitors<TState>
|
||||
): void;
|
||||
|
||||
export function full<TState>(
|
||||
node: Node,
|
||||
callback: FullWalkerCallback<TState>,
|
||||
base?: RecursiveVisitors<TState>,
|
||||
state?: TState
|
||||
): void;
|
||||
|
||||
export function fullAncestor<TState>(
|
||||
node: Node,
|
||||
callback: FullAncestorWalkerCallback<TState>,
|
||||
base?: RecursiveVisitors<TState>,
|
||||
state?: TState
|
||||
): void;
|
||||
|
||||
export function make<TState>(
|
||||
functions: RecursiveVisitors<TState>,
|
||||
base?: RecursiveVisitors<TState>
|
||||
): RecursiveVisitors<TState>;
|
||||
|
||||
export function findNodeAt<TState>(
|
||||
node: Node,
|
||||
start: number | undefined,
|
||||
end?: number | undefined,
|
||||
type?: FindPredicate | string,
|
||||
base?: RecursiveVisitors<TState>,
|
||||
state?: TState
|
||||
): Found<TState> | undefined;
|
||||
|
||||
export function findNodeAround<TState>(
|
||||
node: Node,
|
||||
start: number | undefined,
|
||||
type?: FindPredicate | string,
|
||||
base?: RecursiveVisitors<TState>,
|
||||
state?: TState
|
||||
): Found<TState> | undefined;
|
||||
|
||||
export const findNodeAfter: typeof findNodeAround;
|
||||
}
|
|
@ -0,0 +1,463 @@
|
|||
(function (global, factory) {
|
||||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
||||
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
||||
(global = global || self, factory((global.acorn = global.acorn || {}, global.acorn.walk = {})));
|
||||
}(this, (function (exports) { 'use strict';
|
||||
|
||||
// AST walker module for Mozilla Parser API compatible trees
|
||||
|
||||
// A simple walk is one where you simply specify callbacks to be
|
||||
// called on specific nodes. The last two arguments are optional. A
|
||||
// simple use would be
|
||||
//
|
||||
// walk.simple(myTree, {
|
||||
// Expression: function(node) { ... }
|
||||
// });
|
||||
//
|
||||
// to do something with all expressions. All Parser API node types
|
||||
// can be used to identify node types, as well as Expression and
|
||||
// Statement, which denote categories of nodes.
|
||||
//
|
||||
// The base argument can be used to pass a custom (recursive)
|
||||
// walker, and state can be used to give this walked an initial
|
||||
// state.
|
||||
|
||||
function simple(node, visitors, baseVisitor, state, override) {
|
||||
if (!baseVisitor) { baseVisitor = base
|
||||
; }(function c(node, st, override) {
|
||||
var type = override || node.type, found = visitors[type];
|
||||
baseVisitor[type](node, st, c);
|
||||
if (found) { found(node, st); }
|
||||
})(node, state, override);
|
||||
}
|
||||
|
||||
// An ancestor walk keeps an array of ancestor nodes (including the
|
||||
// current node) and passes them to the callback as third parameter
|
||||
// (and also as state parameter when no other state is present).
|
||||
function ancestor(node, visitors, baseVisitor, state, override) {
|
||||
var ancestors = [];
|
||||
if (!baseVisitor) { baseVisitor = base
|
||||
; }(function c(node, st, override) {
|
||||
var type = override || node.type, found = visitors[type];
|
||||
var isNew = node !== ancestors[ancestors.length - 1];
|
||||
if (isNew) { ancestors.push(node); }
|
||||
baseVisitor[type](node, st, c);
|
||||
if (found) { found(node, st || ancestors, ancestors); }
|
||||
if (isNew) { ancestors.pop(); }
|
||||
})(node, state, override);
|
||||
}
|
||||
|
||||
// A recursive walk is one where your functions override the default
|
||||
// walkers. They can modify and replace the state parameter that's
|
||||
// threaded through the walk, and can opt how and whether to walk
|
||||
// their child nodes (by calling their third argument on these
|
||||
// nodes).
|
||||
function recursive(node, state, funcs, baseVisitor, override) {
|
||||
var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor
|
||||
;(function c(node, st, override) {
|
||||
visitor[override || node.type](node, st, c);
|
||||
})(node, state, override);
|
||||
}
|
||||
|
||||
function makeTest(test) {
|
||||
if (typeof test === "string")
|
||||
{ return function (type) { return type === test; } }
|
||||
else if (!test)
|
||||
{ return function () { return true; } }
|
||||
else
|
||||
{ return test }
|
||||
}
|
||||
|
||||
var Found = function Found(node, state) { this.node = node; this.state = state; };
|
||||
|
||||
// A full walk triggers the callback on each node
|
||||
function full(node, callback, baseVisitor, state, override) {
|
||||
if (!baseVisitor) { baseVisitor = base
|
||||
; }(function c(node, st, override) {
|
||||
var type = override || node.type;
|
||||
baseVisitor[type](node, st, c);
|
||||
if (!override) { callback(node, st, type); }
|
||||
})(node, state, override);
|
||||
}
|
||||
|
||||
// An fullAncestor walk is like an ancestor walk, but triggers
|
||||
// the callback on each node
|
||||
function fullAncestor(node, callback, baseVisitor, state) {
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
var ancestors = []
|
||||
;(function c(node, st, override) {
|
||||
var type = override || node.type;
|
||||
var isNew = node !== ancestors[ancestors.length - 1];
|
||||
if (isNew) { ancestors.push(node); }
|
||||
baseVisitor[type](node, st, c);
|
||||
if (!override) { callback(node, st || ancestors, ancestors, type); }
|
||||
if (isNew) { ancestors.pop(); }
|
||||
})(node, state);
|
||||
}
|
||||
|
||||
// Find a node with a given start, end, and type (all are optional,
|
||||
// null can be used as wildcard). Returns a {node, state} object, or
|
||||
// undefined when it doesn't find a matching node.
|
||||
function findNodeAt(node, start, end, test, baseVisitor, state) {
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
test = makeTest(test);
|
||||
try {
|
||||
(function c(node, st, override) {
|
||||
var type = override || node.type;
|
||||
if ((start == null || node.start <= start) &&
|
||||
(end == null || node.end >= end))
|
||||
{ baseVisitor[type](node, st, c); }
|
||||
if ((start == null || node.start === start) &&
|
||||
(end == null || node.end === end) &&
|
||||
test(type, node))
|
||||
{ throw new Found(node, st) }
|
||||
})(node, state);
|
||||
} catch (e) {
|
||||
if (e instanceof Found) { return e }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// Find the innermost node of a given type that contains the given
|
||||
// position. Interface similar to findNodeAt.
|
||||
function findNodeAround(node, pos, test, baseVisitor, state) {
|
||||
test = makeTest(test);
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
try {
|
||||
(function c(node, st, override) {
|
||||
var type = override || node.type;
|
||||
if (node.start > pos || node.end < pos) { return }
|
||||
baseVisitor[type](node, st, c);
|
||||
if (test(type, node)) { throw new Found(node, st) }
|
||||
})(node, state);
|
||||
} catch (e) {
|
||||
if (e instanceof Found) { return e }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// Find the outermost matching node after a given position.
|
||||
function findNodeAfter(node, pos, test, baseVisitor, state) {
|
||||
test = makeTest(test);
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
try {
|
||||
(function c(node, st, override) {
|
||||
if (node.end < pos) { return }
|
||||
var type = override || node.type;
|
||||
if (node.start >= pos && test(type, node)) { throw new Found(node, st) }
|
||||
baseVisitor[type](node, st, c);
|
||||
})(node, state);
|
||||
} catch (e) {
|
||||
if (e instanceof Found) { return e }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// Find the outermost matching node before a given position.
|
||||
function findNodeBefore(node, pos, test, baseVisitor, state) {
|
||||
test = makeTest(test);
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
var max
|
||||
;(function c(node, st, override) {
|
||||
if (node.start > pos) { return }
|
||||
var type = override || node.type;
|
||||
if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))
|
||||
{ max = new Found(node, st); }
|
||||
baseVisitor[type](node, st, c);
|
||||
})(node, state);
|
||||
return max
|
||||
}
|
||||
|
||||
// Fallback to an Object.create polyfill for older environments.
|
||||
var create = Object.create || function(proto) {
|
||||
function Ctor() {}
|
||||
Ctor.prototype = proto;
|
||||
return new Ctor
|
||||
};
|
||||
|
||||
// Used to create a custom walker. Will fill in all missing node
|
||||
// type properties with the defaults.
|
||||
function make(funcs, baseVisitor) {
|
||||
var visitor = create(baseVisitor || base);
|
||||
for (var type in funcs) { visitor[type] = funcs[type]; }
|
||||
return visitor
|
||||
}
|
||||
|
||||
function skipThrough(node, st, c) { c(node, st); }
|
||||
function ignore(_node, _st, _c) {}
|
||||
|
||||
// Node walkers.
|
||||
|
||||
var base = {};
|
||||
|
||||
base.Program = base.BlockStatement = function (node, st, c) {
|
||||
for (var i = 0, list = node.body; i < list.length; i += 1)
|
||||
{
|
||||
var stmt = list[i];
|
||||
|
||||
c(stmt, st, "Statement");
|
||||
}
|
||||
};
|
||||
base.Statement = skipThrough;
|
||||
base.EmptyStatement = ignore;
|
||||
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
|
||||
function (node, st, c) { return c(node.expression, st, "Expression"); };
|
||||
base.IfStatement = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.consequent, st, "Statement");
|
||||
if (node.alternate) { c(node.alternate, st, "Statement"); }
|
||||
};
|
||||
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
|
||||
base.BreakStatement = base.ContinueStatement = ignore;
|
||||
base.WithStatement = function (node, st, c) {
|
||||
c(node.object, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.SwitchStatement = function (node, st, c) {
|
||||
c(node.discriminant, st, "Expression");
|
||||
for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
|
||||
var cs = list$1[i$1];
|
||||
|
||||
if (cs.test) { c(cs.test, st, "Expression"); }
|
||||
for (var i = 0, list = cs.consequent; i < list.length; i += 1)
|
||||
{
|
||||
var cons = list[i];
|
||||
|
||||
c(cons, st, "Statement");
|
||||
}
|
||||
}
|
||||
};
|
||||
base.SwitchCase = function (node, st, c) {
|
||||
if (node.test) { c(node.test, st, "Expression"); }
|
||||
for (var i = 0, list = node.consequent; i < list.length; i += 1)
|
||||
{
|
||||
var cons = list[i];
|
||||
|
||||
c(cons, st, "Statement");
|
||||
}
|
||||
};
|
||||
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
|
||||
if (node.argument) { c(node.argument, st, "Expression"); }
|
||||
};
|
||||
base.ThrowStatement = base.SpreadElement =
|
||||
function (node, st, c) { return c(node.argument, st, "Expression"); };
|
||||
base.TryStatement = function (node, st, c) {
|
||||
c(node.block, st, "Statement");
|
||||
if (node.handler) { c(node.handler, st); }
|
||||
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
|
||||
};
|
||||
base.CatchClause = function (node, st, c) {
|
||||
if (node.param) { c(node.param, st, "Pattern"); }
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForStatement = function (node, st, c) {
|
||||
if (node.init) { c(node.init, st, "ForInit"); }
|
||||
if (node.test) { c(node.test, st, "Expression"); }
|
||||
if (node.update) { c(node.update, st, "Expression"); }
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
|
||||
c(node.left, st, "ForInit");
|
||||
c(node.right, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForInit = function (node, st, c) {
|
||||
if (node.type === "VariableDeclaration") { c(node, st); }
|
||||
else { c(node, st, "Expression"); }
|
||||
};
|
||||
base.DebuggerStatement = ignore;
|
||||
|
||||
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
|
||||
base.VariableDeclaration = function (node, st, c) {
|
||||
for (var i = 0, list = node.declarations; i < list.length; i += 1)
|
||||
{
|
||||
var decl = list[i];
|
||||
|
||||
c(decl, st);
|
||||
}
|
||||
};
|
||||
base.VariableDeclarator = function (node, st, c) {
|
||||
c(node.id, st, "Pattern");
|
||||
if (node.init) { c(node.init, st, "Expression"); }
|
||||
};
|
||||
|
||||
base.Function = function (node, st, c) {
|
||||
if (node.id) { c(node.id, st, "Pattern"); }
|
||||
for (var i = 0, list = node.params; i < list.length; i += 1)
|
||||
{
|
||||
var param = list[i];
|
||||
|
||||
c(param, st, "Pattern");
|
||||
}
|
||||
c(node.body, st, node.expression ? "Expression" : "Statement");
|
||||
};
|
||||
|
||||
base.Pattern = function (node, st, c) {
|
||||
if (node.type === "Identifier")
|
||||
{ c(node, st, "VariablePattern"); }
|
||||
else if (node.type === "MemberExpression")
|
||||
{ c(node, st, "MemberPattern"); }
|
||||
else
|
||||
{ c(node, st); }
|
||||
};
|
||||
base.VariablePattern = ignore;
|
||||
base.MemberPattern = skipThrough;
|
||||
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
|
||||
base.ArrayPattern = function (node, st, c) {
|
||||
for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
||||
var elt = list[i];
|
||||
|
||||
if (elt) { c(elt, st, "Pattern"); }
|
||||
}
|
||||
};
|
||||
base.ObjectPattern = function (node, st, c) {
|
||||
for (var i = 0, list = node.properties; i < list.length; i += 1) {
|
||||
var prop = list[i];
|
||||
|
||||
if (prop.type === "Property") {
|
||||
if (prop.computed) { c(prop.key, st, "Expression"); }
|
||||
c(prop.value, st, "Pattern");
|
||||
} else if (prop.type === "RestElement") {
|
||||
c(prop.argument, st, "Pattern");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
base.Expression = skipThrough;
|
||||
base.ThisExpression = base.Super = base.MetaProperty = ignore;
|
||||
base.ArrayExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
||||
var elt = list[i];
|
||||
|
||||
if (elt) { c(elt, st, "Expression"); }
|
||||
}
|
||||
};
|
||||
base.ObjectExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.properties; i < list.length; i += 1)
|
||||
{
|
||||
var prop = list[i];
|
||||
|
||||
c(prop, st);
|
||||
}
|
||||
};
|
||||
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
|
||||
base.SequenceExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.expressions; i < list.length; i += 1)
|
||||
{
|
||||
var expr = list[i];
|
||||
|
||||
c(expr, st, "Expression");
|
||||
}
|
||||
};
|
||||
base.TemplateLiteral = function (node, st, c) {
|
||||
for (var i = 0, list = node.quasis; i < list.length; i += 1)
|
||||
{
|
||||
var quasi = list[i];
|
||||
|
||||
c(quasi, st);
|
||||
}
|
||||
|
||||
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
|
||||
{
|
||||
var expr = list$1[i$1];
|
||||
|
||||
c(expr, st, "Expression");
|
||||
}
|
||||
};
|
||||
base.TemplateElement = ignore;
|
||||
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
|
||||
c(node.argument, st, "Expression");
|
||||
};
|
||||
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
|
||||
c(node.left, st, "Expression");
|
||||
c(node.right, st, "Expression");
|
||||
};
|
||||
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
|
||||
c(node.left, st, "Pattern");
|
||||
c(node.right, st, "Expression");
|
||||
};
|
||||
base.ConditionalExpression = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.consequent, st, "Expression");
|
||||
c(node.alternate, st, "Expression");
|
||||
};
|
||||
base.NewExpression = base.CallExpression = function (node, st, c) {
|
||||
c(node.callee, st, "Expression");
|
||||
if (node.arguments)
|
||||
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
|
||||
{
|
||||
var arg = list[i];
|
||||
|
||||
c(arg, st, "Expression");
|
||||
} }
|
||||
};
|
||||
base.MemberExpression = function (node, st, c) {
|
||||
c(node.object, st, "Expression");
|
||||
if (node.computed) { c(node.property, st, "Expression"); }
|
||||
};
|
||||
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
|
||||
if (node.declaration)
|
||||
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
|
||||
if (node.source) { c(node.source, st, "Expression"); }
|
||||
};
|
||||
base.ExportAllDeclaration = function (node, st, c) {
|
||||
if (node.exported)
|
||||
{ c(node.exported, st); }
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportDeclaration = function (node, st, c) {
|
||||
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
|
||||
{
|
||||
var spec = list[i];
|
||||
|
||||
c(spec, st);
|
||||
}
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportExpression = function (node, st, c) {
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore;
|
||||
|
||||
base.TaggedTemplateExpression = function (node, st, c) {
|
||||
c(node.tag, st, "Expression");
|
||||
c(node.quasi, st, "Expression");
|
||||
};
|
||||
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
|
||||
base.Class = function (node, st, c) {
|
||||
if (node.id) { c(node.id, st, "Pattern"); }
|
||||
if (node.superClass) { c(node.superClass, st, "Expression"); }
|
||||
c(node.body, st);
|
||||
};
|
||||
base.ClassBody = function (node, st, c) {
|
||||
for (var i = 0, list = node.body; i < list.length; i += 1)
|
||||
{
|
||||
var elt = list[i];
|
||||
|
||||
c(elt, st);
|
||||
}
|
||||
};
|
||||
base.MethodDefinition = base.Property = function (node, st, c) {
|
||||
if (node.computed) { c(node.key, st, "Expression"); }
|
||||
c(node.value, st, "Expression");
|
||||
};
|
||||
|
||||
exports.ancestor = ancestor;
|
||||
exports.base = base;
|
||||
exports.findNodeAfter = findNodeAfter;
|
||||
exports.findNodeAround = findNodeAround;
|
||||
exports.findNodeAt = findNodeAt;
|
||||
exports.findNodeBefore = findNodeBefore;
|
||||
exports.full = full;
|
||||
exports.fullAncestor = fullAncestor;
|
||||
exports.make = make;
|
||||
exports.recursive = recursive;
|
||||
exports.simple = simple;
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
})));
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,443 @@
|
|||
// AST walker module for Mozilla Parser API compatible trees
|
||||
|
||||
// A simple walk is one where you simply specify callbacks to be
|
||||
// called on specific nodes. The last two arguments are optional. A
|
||||
// simple use would be
|
||||
//
|
||||
// walk.simple(myTree, {
|
||||
// Expression: function(node) { ... }
|
||||
// });
|
||||
//
|
||||
// to do something with all expressions. All Parser API node types
|
||||
// can be used to identify node types, as well as Expression and
|
||||
// Statement, which denote categories of nodes.
|
||||
//
|
||||
// The base argument can be used to pass a custom (recursive)
|
||||
// walker, and state can be used to give this walked an initial
|
||||
// state.
|
||||
|
||||
function simple(node, visitors, baseVisitor, state, override) {
|
||||
if (!baseVisitor) { baseVisitor = base
|
||||
; }(function c(node, st, override) {
|
||||
var type = override || node.type, found = visitors[type];
|
||||
baseVisitor[type](node, st, c);
|
||||
if (found) { found(node, st); }
|
||||
})(node, state, override);
|
||||
}
|
||||
|
||||
// An ancestor walk keeps an array of ancestor nodes (including the
|
||||
// current node) and passes them to the callback as third parameter
|
||||
// (and also as state parameter when no other state is present).
|
||||
function ancestor(node, visitors, baseVisitor, state, override) {
|
||||
var ancestors = [];
|
||||
if (!baseVisitor) { baseVisitor = base
|
||||
; }(function c(node, st, override) {
|
||||
var type = override || node.type, found = visitors[type];
|
||||
var isNew = node !== ancestors[ancestors.length - 1];
|
||||
if (isNew) { ancestors.push(node); }
|
||||
baseVisitor[type](node, st, c);
|
||||
if (found) { found(node, st || ancestors, ancestors); }
|
||||
if (isNew) { ancestors.pop(); }
|
||||
})(node, state, override);
|
||||
}
|
||||
|
||||
// A recursive walk is one where your functions override the default
|
||||
// walkers. They can modify and replace the state parameter that's
|
||||
// threaded through the walk, and can opt how and whether to walk
|
||||
// their child nodes (by calling their third argument on these
|
||||
// nodes).
|
||||
function recursive(node, state, funcs, baseVisitor, override) {
|
||||
var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor
|
||||
;(function c(node, st, override) {
|
||||
visitor[override || node.type](node, st, c);
|
||||
})(node, state, override);
|
||||
}
|
||||
|
||||
function makeTest(test) {
|
||||
if (typeof test === "string")
|
||||
{ return function (type) { return type === test; } }
|
||||
else if (!test)
|
||||
{ return function () { return true; } }
|
||||
else
|
||||
{ return test }
|
||||
}
|
||||
|
||||
var Found = function Found(node, state) { this.node = node; this.state = state; };
|
||||
|
||||
// A full walk triggers the callback on each node
|
||||
function full(node, callback, baseVisitor, state, override) {
|
||||
if (!baseVisitor) { baseVisitor = base
|
||||
; }(function c(node, st, override) {
|
||||
var type = override || node.type;
|
||||
baseVisitor[type](node, st, c);
|
||||
if (!override) { callback(node, st, type); }
|
||||
})(node, state, override);
|
||||
}
|
||||
|
||||
// An fullAncestor walk is like an ancestor walk, but triggers
|
||||
// the callback on each node
|
||||
function fullAncestor(node, callback, baseVisitor, state) {
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
var ancestors = []
|
||||
;(function c(node, st, override) {
|
||||
var type = override || node.type;
|
||||
var isNew = node !== ancestors[ancestors.length - 1];
|
||||
if (isNew) { ancestors.push(node); }
|
||||
baseVisitor[type](node, st, c);
|
||||
if (!override) { callback(node, st || ancestors, ancestors, type); }
|
||||
if (isNew) { ancestors.pop(); }
|
||||
})(node, state);
|
||||
}
|
||||
|
||||
// Find a node with a given start, end, and type (all are optional,
|
||||
// null can be used as wildcard). Returns a {node, state} object, or
|
||||
// undefined when it doesn't find a matching node.
|
||||
function findNodeAt(node, start, end, test, baseVisitor, state) {
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
test = makeTest(test);
|
||||
try {
|
||||
(function c(node, st, override) {
|
||||
var type = override || node.type;
|
||||
if ((start == null || node.start <= start) &&
|
||||
(end == null || node.end >= end))
|
||||
{ baseVisitor[type](node, st, c); }
|
||||
if ((start == null || node.start === start) &&
|
||||
(end == null || node.end === end) &&
|
||||
test(type, node))
|
||||
{ throw new Found(node, st) }
|
||||
})(node, state);
|
||||
} catch (e) {
|
||||
if (e instanceof Found) { return e }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// Find the innermost node of a given type that contains the given
|
||||
// position. Interface similar to findNodeAt.
|
||||
function findNodeAround(node, pos, test, baseVisitor, state) {
|
||||
test = makeTest(test);
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
try {
|
||||
(function c(node, st, override) {
|
||||
var type = override || node.type;
|
||||
if (node.start > pos || node.end < pos) { return }
|
||||
baseVisitor[type](node, st, c);
|
||||
if (test(type, node)) { throw new Found(node, st) }
|
||||
})(node, state);
|
||||
} catch (e) {
|
||||
if (e instanceof Found) { return e }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// Find the outermost matching node after a given position.
|
||||
function findNodeAfter(node, pos, test, baseVisitor, state) {
|
||||
test = makeTest(test);
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
try {
|
||||
(function c(node, st, override) {
|
||||
if (node.end < pos) { return }
|
||||
var type = override || node.type;
|
||||
if (node.start >= pos && test(type, node)) { throw new Found(node, st) }
|
||||
baseVisitor[type](node, st, c);
|
||||
})(node, state);
|
||||
} catch (e) {
|
||||
if (e instanceof Found) { return e }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// Find the outermost matching node before a given position.
|
||||
function findNodeBefore(node, pos, test, baseVisitor, state) {
|
||||
test = makeTest(test);
|
||||
if (!baseVisitor) { baseVisitor = base; }
|
||||
var max
|
||||
;(function c(node, st, override) {
|
||||
if (node.start > pos) { return }
|
||||
var type = override || node.type;
|
||||
if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))
|
||||
{ max = new Found(node, st); }
|
||||
baseVisitor[type](node, st, c);
|
||||
})(node, state);
|
||||
return max
|
||||
}
|
||||
|
||||
// Fallback to an Object.create polyfill for older environments.
|
||||
var create = Object.create || function(proto) {
|
||||
function Ctor() {}
|
||||
Ctor.prototype = proto;
|
||||
return new Ctor
|
||||
};
|
||||
|
||||
// Used to create a custom walker. Will fill in all missing node
|
||||
// type properties with the defaults.
|
||||
function make(funcs, baseVisitor) {
|
||||
var visitor = create(baseVisitor || base);
|
||||
for (var type in funcs) { visitor[type] = funcs[type]; }
|
||||
return visitor
|
||||
}
|
||||
|
||||
function skipThrough(node, st, c) { c(node, st); }
|
||||
function ignore(_node, _st, _c) {}
|
||||
|
||||
// Node walkers.
|
||||
|
||||
var base = {};
|
||||
|
||||
base.Program = base.BlockStatement = function (node, st, c) {
|
||||
for (var i = 0, list = node.body; i < list.length; i += 1)
|
||||
{
|
||||
var stmt = list[i];
|
||||
|
||||
c(stmt, st, "Statement");
|
||||
}
|
||||
};
|
||||
base.Statement = skipThrough;
|
||||
base.EmptyStatement = ignore;
|
||||
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
|
||||
function (node, st, c) { return c(node.expression, st, "Expression"); };
|
||||
base.IfStatement = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.consequent, st, "Statement");
|
||||
if (node.alternate) { c(node.alternate, st, "Statement"); }
|
||||
};
|
||||
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
|
||||
base.BreakStatement = base.ContinueStatement = ignore;
|
||||
base.WithStatement = function (node, st, c) {
|
||||
c(node.object, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.SwitchStatement = function (node, st, c) {
|
||||
c(node.discriminant, st, "Expression");
|
||||
for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
|
||||
var cs = list$1[i$1];
|
||||
|
||||
if (cs.test) { c(cs.test, st, "Expression"); }
|
||||
for (var i = 0, list = cs.consequent; i < list.length; i += 1)
|
||||
{
|
||||
var cons = list[i];
|
||||
|
||||
c(cons, st, "Statement");
|
||||
}
|
||||
}
|
||||
};
|
||||
base.SwitchCase = function (node, st, c) {
|
||||
if (node.test) { c(node.test, st, "Expression"); }
|
||||
for (var i = 0, list = node.consequent; i < list.length; i += 1)
|
||||
{
|
||||
var cons = list[i];
|
||||
|
||||
c(cons, st, "Statement");
|
||||
}
|
||||
};
|
||||
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
|
||||
if (node.argument) { c(node.argument, st, "Expression"); }
|
||||
};
|
||||
base.ThrowStatement = base.SpreadElement =
|
||||
function (node, st, c) { return c(node.argument, st, "Expression"); };
|
||||
base.TryStatement = function (node, st, c) {
|
||||
c(node.block, st, "Statement");
|
||||
if (node.handler) { c(node.handler, st); }
|
||||
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
|
||||
};
|
||||
base.CatchClause = function (node, st, c) {
|
||||
if (node.param) { c(node.param, st, "Pattern"); }
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForStatement = function (node, st, c) {
|
||||
if (node.init) { c(node.init, st, "ForInit"); }
|
||||
if (node.test) { c(node.test, st, "Expression"); }
|
||||
if (node.update) { c(node.update, st, "Expression"); }
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
|
||||
c(node.left, st, "ForInit");
|
||||
c(node.right, st, "Expression");
|
||||
c(node.body, st, "Statement");
|
||||
};
|
||||
base.ForInit = function (node, st, c) {
|
||||
if (node.type === "VariableDeclaration") { c(node, st); }
|
||||
else { c(node, st, "Expression"); }
|
||||
};
|
||||
base.DebuggerStatement = ignore;
|
||||
|
||||
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
|
||||
base.VariableDeclaration = function (node, st, c) {
|
||||
for (var i = 0, list = node.declarations; i < list.length; i += 1)
|
||||
{
|
||||
var decl = list[i];
|
||||
|
||||
c(decl, st);
|
||||
}
|
||||
};
|
||||
base.VariableDeclarator = function (node, st, c) {
|
||||
c(node.id, st, "Pattern");
|
||||
if (node.init) { c(node.init, st, "Expression"); }
|
||||
};
|
||||
|
||||
base.Function = function (node, st, c) {
|
||||
if (node.id) { c(node.id, st, "Pattern"); }
|
||||
for (var i = 0, list = node.params; i < list.length; i += 1)
|
||||
{
|
||||
var param = list[i];
|
||||
|
||||
c(param, st, "Pattern");
|
||||
}
|
||||
c(node.body, st, node.expression ? "Expression" : "Statement");
|
||||
};
|
||||
|
||||
base.Pattern = function (node, st, c) {
|
||||
if (node.type === "Identifier")
|
||||
{ c(node, st, "VariablePattern"); }
|
||||
else if (node.type === "MemberExpression")
|
||||
{ c(node, st, "MemberPattern"); }
|
||||
else
|
||||
{ c(node, st); }
|
||||
};
|
||||
base.VariablePattern = ignore;
|
||||
base.MemberPattern = skipThrough;
|
||||
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
|
||||
base.ArrayPattern = function (node, st, c) {
|
||||
for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
||||
var elt = list[i];
|
||||
|
||||
if (elt) { c(elt, st, "Pattern"); }
|
||||
}
|
||||
};
|
||||
base.ObjectPattern = function (node, st, c) {
|
||||
for (var i = 0, list = node.properties; i < list.length; i += 1) {
|
||||
var prop = list[i];
|
||||
|
||||
if (prop.type === "Property") {
|
||||
if (prop.computed) { c(prop.key, st, "Expression"); }
|
||||
c(prop.value, st, "Pattern");
|
||||
} else if (prop.type === "RestElement") {
|
||||
c(prop.argument, st, "Pattern");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
base.Expression = skipThrough;
|
||||
base.ThisExpression = base.Super = base.MetaProperty = ignore;
|
||||
base.ArrayExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.elements; i < list.length; i += 1) {
|
||||
var elt = list[i];
|
||||
|
||||
if (elt) { c(elt, st, "Expression"); }
|
||||
}
|
||||
};
|
||||
base.ObjectExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.properties; i < list.length; i += 1)
|
||||
{
|
||||
var prop = list[i];
|
||||
|
||||
c(prop, st);
|
||||
}
|
||||
};
|
||||
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
|
||||
base.SequenceExpression = function (node, st, c) {
|
||||
for (var i = 0, list = node.expressions; i < list.length; i += 1)
|
||||
{
|
||||
var expr = list[i];
|
||||
|
||||
c(expr, st, "Expression");
|
||||
}
|
||||
};
|
||||
base.TemplateLiteral = function (node, st, c) {
|
||||
for (var i = 0, list = node.quasis; i < list.length; i += 1)
|
||||
{
|
||||
var quasi = list[i];
|
||||
|
||||
c(quasi, st);
|
||||
}
|
||||
|
||||
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
|
||||
{
|
||||
var expr = list$1[i$1];
|
||||
|
||||
c(expr, st, "Expression");
|
||||
}
|
||||
};
|
||||
base.TemplateElement = ignore;
|
||||
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
|
||||
c(node.argument, st, "Expression");
|
||||
};
|
||||
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
|
||||
c(node.left, st, "Expression");
|
||||
c(node.right, st, "Expression");
|
||||
};
|
||||
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
|
||||
c(node.left, st, "Pattern");
|
||||
c(node.right, st, "Expression");
|
||||
};
|
||||
base.ConditionalExpression = function (node, st, c) {
|
||||
c(node.test, st, "Expression");
|
||||
c(node.consequent, st, "Expression");
|
||||
c(node.alternate, st, "Expression");
|
||||
};
|
||||
base.NewExpression = base.CallExpression = function (node, st, c) {
|
||||
c(node.callee, st, "Expression");
|
||||
if (node.arguments)
|
||||
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
|
||||
{
|
||||
var arg = list[i];
|
||||
|
||||
c(arg, st, "Expression");
|
||||
} }
|
||||
};
|
||||
base.MemberExpression = function (node, st, c) {
|
||||
c(node.object, st, "Expression");
|
||||
if (node.computed) { c(node.property, st, "Expression"); }
|
||||
};
|
||||
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
|
||||
if (node.declaration)
|
||||
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
|
||||
if (node.source) { c(node.source, st, "Expression"); }
|
||||
};
|
||||
base.ExportAllDeclaration = function (node, st, c) {
|
||||
if (node.exported)
|
||||
{ c(node.exported, st); }
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportDeclaration = function (node, st, c) {
|
||||
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
|
||||
{
|
||||
var spec = list[i];
|
||||
|
||||
c(spec, st);
|
||||
}
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportExpression = function (node, st, c) {
|
||||
c(node.source, st, "Expression");
|
||||
};
|
||||
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore;
|
||||
|
||||
base.TaggedTemplateExpression = function (node, st, c) {
|
||||
c(node.tag, st, "Expression");
|
||||
c(node.quasi, st, "Expression");
|
||||
};
|
||||
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
|
||||
base.Class = function (node, st, c) {
|
||||
if (node.id) { c(node.id, st, "Pattern"); }
|
||||
if (node.superClass) { c(node.superClass, st, "Expression"); }
|
||||
c(node.body, st);
|
||||
};
|
||||
base.ClassBody = function (node, st, c) {
|
||||
for (var i = 0, list = node.body; i < list.length; i += 1)
|
||||
{
|
||||
var elt = list[i];
|
||||
|
||||
c(elt, st);
|
||||
}
|
||||
};
|
||||
base.MethodDefinition = base.Property = function (node, st, c) {
|
||||
if (node.computed) { c(node.key, st, "Expression"); }
|
||||
c(node.value, st, "Expression");
|
||||
};
|
||||
|
||||
export { ancestor, base, findNodeAfter, findNodeAround, findNodeAt, findNodeBefore, full, fullAncestor, make, recursive, simple };
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,64 @@
|
|||
{
|
||||
"_from": "acorn-walk@^7.1.1",
|
||||
"_id": "acorn-walk@7.2.0",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==",
|
||||
"_location": "/acorn-walk",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "acorn-walk@^7.1.1",
|
||||
"name": "acorn-walk",
|
||||
"escapedName": "acorn-walk",
|
||||
"rawSpec": "^7.1.1",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^7.1.1"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/acorn-globals"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.2.0.tgz",
|
||||
"_shasum": "0de889a601203909b0fbe07b8938dc21d2e967bc",
|
||||
"_spec": "acorn-walk@^7.1.1",
|
||||
"_where": "/home/centos/markdown/node_modules/acorn-globals",
|
||||
"bugs": {
|
||||
"url": "https://github.com/acornjs/acorn/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"deprecated": false,
|
||||
"description": "ECMAScript (ESTree) AST walker",
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
},
|
||||
"homepage": "https://github.com/acornjs/acorn",
|
||||
"license": "MIT",
|
||||
"main": "dist/walk.js",
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "Marijn Haverbeke",
|
||||
"email": "marijnh@gmail.com",
|
||||
"url": "https://marijnhaverbeke.nl"
|
||||
},
|
||||
{
|
||||
"name": "Ingvar Stepanyan",
|
||||
"email": "me@rreverser.com",
|
||||
"url": "https://rreverser.com/"
|
||||
},
|
||||
{
|
||||
"name": "Adrian Heine",
|
||||
"url": "http://adrianheine.de"
|
||||
}
|
||||
],
|
||||
"module": "dist/walk.mjs",
|
||||
"name": "acorn-walk",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/acornjs/acorn.git"
|
||||
},
|
||||
"scripts": {
|
||||
"prepare": "cd ..; npm run build:walk"
|
||||
},
|
||||
"types": "dist/walk.d.ts",
|
||||
"version": "7.2.0"
|
||||
}
|
|
@ -0,0 +1,620 @@
|
|||
## 7.4.0 (2020-08-03)
|
||||
|
||||
### New features
|
||||
|
||||
Add support for logical assignment operators.
|
||||
|
||||
Add support for numeric separators.
|
||||
|
||||
## 7.3.1 (2020-06-11)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Make the string in the `version` export match the actual library version.
|
||||
|
||||
## 7.3.0 (2020-06-11)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix a bug that caused parsing of object patterns with a property named `set` that had a default value to fail.
|
||||
|
||||
### New features
|
||||
|
||||
Add support for optional chaining (`?.`).
|
||||
|
||||
## 7.2.0 (2020-05-09)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix precedence issue in parsing of async arrow functions.
|
||||
|
||||
### New features
|
||||
|
||||
Add support for nullish coalescing.
|
||||
|
||||
Add support for `import.meta`.
|
||||
|
||||
Support `export * as ...` syntax.
|
||||
|
||||
Upgrade to Unicode 13.
|
||||
|
||||
## 6.4.1 (2020-03-09)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
More carefully check for valid UTF16 surrogate pairs in regexp validator.
|
||||
|
||||
## 7.1.1 (2020-03-01)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Treat `\8` and `\9` as invalid escapes in template strings.
|
||||
|
||||
Allow unicode escapes in property names that are keywords.
|
||||
|
||||
Don't error on an exponential operator expression as argument to `await`.
|
||||
|
||||
More carefully check for valid UTF16 surrogate pairs in regexp validator.
|
||||
|
||||
## 7.1.0 (2019-09-24)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Disallow trailing object literal commas when ecmaVersion is less than 5.
|
||||
|
||||
### New features
|
||||
|
||||
Add a static `acorn` property to the `Parser` class that contains the entire module interface, to allow plugins to access the instance of the library that they are acting on.
|
||||
|
||||
## 7.0.0 (2019-08-13)
|
||||
|
||||
### Breaking changes
|
||||
|
||||
Changes the node format for dynamic imports to use the `ImportExpression` node type, as defined in [ESTree](https://github.com/estree/estree/blob/master/es2020.md#importexpression).
|
||||
|
||||
Makes 10 (ES2019) the default value for the `ecmaVersion` option.
|
||||
|
||||
## 6.3.0 (2019-08-12)
|
||||
|
||||
### New features
|
||||
|
||||
`sourceType: "module"` can now be used even when `ecmaVersion` is less than 6, to parse module-style code that otherwise conforms to an older standard.
|
||||
|
||||
## 6.2.1 (2019-07-21)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix bug causing Acorn to treat some characters as identifier characters that shouldn't be treated as such.
|
||||
|
||||
Fix issue where setting the `allowReserved` option to `"never"` allowed reserved words in some circumstances.
|
||||
|
||||
## 6.2.0 (2019-07-04)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Improve valid assignment checking in `for`/`in` and `for`/`of` loops.
|
||||
|
||||
Disallow binding `let` in patterns.
|
||||
|
||||
### New features
|
||||
|
||||
Support bigint syntax with `ecmaVersion` >= 11.
|
||||
|
||||
Support dynamic `import` syntax with `ecmaVersion` >= 11.
|
||||
|
||||
Upgrade to Unicode version 12.
|
||||
|
||||
## 6.1.1 (2019-02-27)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix bug that caused parsing default exports of with names to fail.
|
||||
|
||||
## 6.1.0 (2019-02-08)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix scope checking when redefining a `var` as a lexical binding.
|
||||
|
||||
### New features
|
||||
|
||||
Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins.
|
||||
|
||||
## 6.0.7 (2019-02-04)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Check that exported bindings are defined.
|
||||
|
||||
Don't treat `\u180e` as a whitespace character.
|
||||
|
||||
Check for duplicate parameter names in methods.
|
||||
|
||||
Don't allow shorthand properties when they are generators or async methods.
|
||||
|
||||
Forbid binding `await` in async arrow function's parameter list.
|
||||
|
||||
## 6.0.6 (2019-01-30)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
The content of class declarations and expressions is now always parsed in strict mode.
|
||||
|
||||
Don't allow `let` or `const` to bind the variable name `let`.
|
||||
|
||||
Treat class declarations as lexical.
|
||||
|
||||
Don't allow a generator function declaration as the sole body of an `if` or `else`.
|
||||
|
||||
Ignore `"use strict"` when after an empty statement.
|
||||
|
||||
Allow string line continuations with special line terminator characters.
|
||||
|
||||
Treat `for` bodies as part of the `for` scope when checking for conflicting bindings.
|
||||
|
||||
Fix bug with parsing `yield` in a `for` loop initializer.
|
||||
|
||||
Implement special cases around scope checking for functions.
|
||||
|
||||
## 6.0.5 (2019-01-02)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type.
|
||||
|
||||
Don't treat `let` as a keyword when the next token is `{` on the next line.
|
||||
|
||||
Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on.
|
||||
|
||||
## 6.0.4 (2018-11-05)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Further improvements to tokenizing regular expressions in corner cases.
|
||||
|
||||
## 6.0.3 (2018-11-04)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression.
|
||||
|
||||
Remove stray symlink in the package tarball.
|
||||
|
||||
## 6.0.2 (2018-09-26)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix bug where default expressions could fail to parse inside an object destructuring assignment expression.
|
||||
|
||||
## 6.0.1 (2018-09-14)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix wrong value in `version` export.
|
||||
|
||||
## 6.0.0 (2018-09-14)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Better handle variable-redefinition checks for catch bindings and functions directly under if statements.
|
||||
|
||||
Forbid `new.target` in top-level arrow functions.
|
||||
|
||||
Fix issue with parsing a regexp after `yield` in some contexts.
|
||||
|
||||
### New features
|
||||
|
||||
The package now comes with TypeScript definitions.
|
||||
|
||||
### Breaking changes
|
||||
|
||||
The default value of the `ecmaVersion` option is now 9 (2018).
|
||||
|
||||
Plugins work differently, and will have to be rewritten to work with this version.
|
||||
|
||||
The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`).
|
||||
|
||||
## 5.7.3 (2018-09-10)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix failure to tokenize regexps after expressions like `x.of`.
|
||||
|
||||
Better error message for unterminated template literals.
|
||||
|
||||
## 5.7.2 (2018-08-24)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Properly handle `allowAwaitOutsideFunction` in for statements.
|
||||
|
||||
Treat function declarations at the top level of modules like let bindings.
|
||||
|
||||
Don't allow async function declarations as the only statement under a label.
|
||||
|
||||
## 5.7.0 (2018-06-15)
|
||||
|
||||
### New features
|
||||
|
||||
Upgraded to Unicode 11.
|
||||
|
||||
## 5.6.0 (2018-05-31)
|
||||
|
||||
### New features
|
||||
|
||||
Allow U+2028 and U+2029 in string when ECMAVersion >= 10.
|
||||
|
||||
Allow binding-less catch statements when ECMAVersion >= 10.
|
||||
|
||||
Add `allowAwaitOutsideFunction` option for parsing top-level `await`.
|
||||
|
||||
## 5.5.3 (2018-03-08)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps.
|
||||
|
||||
## 5.5.2 (2018-03-08)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0.
|
||||
|
||||
## 5.5.1 (2018-03-06)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix misleading error message for octal escapes in template strings.
|
||||
|
||||
## 5.5.0 (2018-02-27)
|
||||
|
||||
### New features
|
||||
|
||||
The identifier character categorization is now based on Unicode version 10.
|
||||
|
||||
Acorn will now validate the content of regular expressions, including new ES9 features.
|
||||
|
||||
## 5.4.0 (2018-02-01)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Disallow duplicate or escaped flags on regular expressions.
|
||||
|
||||
Disallow octal escapes in strings in strict mode.
|
||||
|
||||
### New features
|
||||
|
||||
Add support for async iteration.
|
||||
|
||||
Add support for object spread and rest.
|
||||
|
||||
## 5.3.0 (2017-12-28)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix parsing of floating point literals with leading zeroes in loose mode.
|
||||
|
||||
Allow duplicate property names in object patterns.
|
||||
|
||||
Don't allow static class methods named `prototype`.
|
||||
|
||||
Disallow async functions directly under `if` or `else`.
|
||||
|
||||
Parse right-hand-side of `for`/`of` as an assignment expression.
|
||||
|
||||
Stricter parsing of `for`/`in`.
|
||||
|
||||
Don't allow unicode escapes in contextual keywords.
|
||||
|
||||
### New features
|
||||
|
||||
Parsing class members was factored into smaller methods to allow plugins to hook into it.
|
||||
|
||||
## 5.2.1 (2017-10-30)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix a token context corruption bug.
|
||||
|
||||
## 5.2.0 (2017-10-30)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix token context tracking for `class` and `function` in property-name position.
|
||||
|
||||
Make sure `%*` isn't parsed as a valid operator.
|
||||
|
||||
Allow shorthand properties `get` and `set` to be followed by default values.
|
||||
|
||||
Disallow `super` when not in callee or object position.
|
||||
|
||||
### New features
|
||||
|
||||
Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements.
|
||||
|
||||
## 5.1.2 (2017-09-04)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Disable parsing of legacy HTML-style comments in modules.
|
||||
|
||||
Fix parsing of async methods whose names are keywords.
|
||||
|
||||
## 5.1.1 (2017-07-06)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix problem with disambiguating regexp and division after a class.
|
||||
|
||||
## 5.1.0 (2017-07-05)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`.
|
||||
|
||||
Parse zero-prefixed numbers with non-octal digits as decimal.
|
||||
|
||||
Allow object/array patterns in rest parameters.
|
||||
|
||||
Don't error when `yield` is used as a property name.
|
||||
|
||||
Allow `async` as a shorthand object property.
|
||||
|
||||
### New features
|
||||
|
||||
Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9.
|
||||
|
||||
## 5.0.3 (2017-04-01)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix spurious duplicate variable definition errors for named functions.
|
||||
|
||||
## 5.0.2 (2017-03-30)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error.
|
||||
|
||||
## 5.0.0 (2017-03-28)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Raise an error for duplicated lexical bindings.
|
||||
|
||||
Fix spurious error when an assignement expression occurred after a spread expression.
|
||||
|
||||
Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions.
|
||||
|
||||
Allow labels in front or `var` declarations, even in strict mode.
|
||||
|
||||
### Breaking changes
|
||||
|
||||
Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`.
|
||||
|
||||
## 4.0.11 (2017-02-07)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Allow all forms of member expressions to be parenthesized as lvalue.
|
||||
|
||||
## 4.0.10 (2017-02-07)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Don't expect semicolons after default-exported functions or classes, even when they are expressions.
|
||||
|
||||
Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode.
|
||||
|
||||
## 4.0.9 (2017-02-06)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again.
|
||||
|
||||
## 4.0.8 (2017-02-03)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet.
|
||||
|
||||
## 4.0.7 (2017-02-02)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Accept invalidly rejected code like `(x).y = 2` again.
|
||||
|
||||
Don't raise an error when a function _inside_ strict code has a non-simple parameter list.
|
||||
|
||||
## 4.0.6 (2017-02-02)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check.
|
||||
|
||||
## 4.0.5 (2017-02-02)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Disallow parenthesized pattern expressions.
|
||||
|
||||
Allow keywords as export names.
|
||||
|
||||
Don't allow the `async` keyword to be parenthesized.
|
||||
|
||||
Properly raise an error when a keyword contains a character escape.
|
||||
|
||||
Allow `"use strict"` to appear after other string literal expressions.
|
||||
|
||||
Disallow labeled declarations.
|
||||
|
||||
## 4.0.4 (2016-12-19)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix crash when `export` was followed by a keyword that can't be
|
||||
exported.
|
||||
|
||||
## 4.0.3 (2016-08-16)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode.
|
||||
|
||||
Properly parse properties named `async` in ES2017 mode.
|
||||
|
||||
Fix bug where reserved words were broken in ES2017 mode.
|
||||
|
||||
## 4.0.2 (2016-08-11)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Don't ignore period or 'e' characters after octal numbers.
|
||||
|
||||
Fix broken parsing for call expressions in default parameter values of arrow functions.
|
||||
|
||||
## 4.0.1 (2016-08-08)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix false positives in duplicated export name errors.
|
||||
|
||||
## 4.0.0 (2016-08-07)
|
||||
|
||||
### Breaking changes
|
||||
|
||||
The default `ecmaVersion` option value is now 7.
|
||||
|
||||
A number of internal method signatures changed, so plugins might need to be updated.
|
||||
|
||||
### Bug fixes
|
||||
|
||||
The parser now raises errors on duplicated export names.
|
||||
|
||||
`arguments` and `eval` can now be used in shorthand properties.
|
||||
|
||||
Duplicate parameter names in non-simple argument lists now always produce an error.
|
||||
|
||||
### New features
|
||||
|
||||
The `ecmaVersion` option now also accepts year-style version numbers
|
||||
(2015, etc).
|
||||
|
||||
Support for `async`/`await` syntax when `ecmaVersion` is >= 8.
|
||||
|
||||
Support for trailing commas in call expressions when `ecmaVersion` is >= 8.
|
||||
|
||||
## 3.3.0 (2016-07-25)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Fix bug in tokenizing of regexp operator after a function declaration.
|
||||
|
||||
Fix parser crash when parsing an array pattern with a hole.
|
||||
|
||||
### New features
|
||||
|
||||
Implement check against complex argument lists in functions that enable strict mode in ES7.
|
||||
|
||||
## 3.2.0 (2016-06-07)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Improve handling of lack of unicode regexp support in host
|
||||
environment.
|
||||
|
||||
Properly reject shorthand properties whose name is a keyword.
|
||||
|
||||
### New features
|
||||
|
||||
Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object.
|
||||
|
||||
## 3.1.0 (2016-04-18)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Properly tokenize the division operator directly after a function expression.
|
||||
|
||||
Allow trailing comma in destructuring arrays.
|
||||
|
||||
## 3.0.4 (2016-02-25)
|
||||
|
||||
### Fixes
|
||||
|
||||
Allow update expressions as left-hand-side of the ES7 exponential operator.
|
||||
|
||||
## 3.0.2 (2016-02-10)
|
||||
|
||||
### Fixes
|
||||
|
||||
Fix bug that accidentally made `undefined` a reserved word when parsing ES7.
|
||||
|
||||
## 3.0.0 (2016-02-10)
|
||||
|
||||
### Breaking changes
|
||||
|
||||
The default value of the `ecmaVersion` option is now 6 (used to be 5).
|
||||
|
||||
Support for comprehension syntax (which was dropped from the draft spec) has been removed.
|
||||
|
||||
### Fixes
|
||||
|
||||
`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code.
|
||||
|
||||
A parenthesized class or function expression after `export default` is now parsed correctly.
|
||||
|
||||
### New features
|
||||
|
||||
When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`).
|
||||
|
||||
The identifier character ranges are now based on Unicode 8.0.0.
|
||||
|
||||
Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled.
|
||||
|
||||
## 2.7.0 (2016-01-04)
|
||||
|
||||
### Fixes
|
||||
|
||||
Stop allowing rest parameters in setters.
|
||||
|
||||
Disallow `y` rexexp flag in ES5.
|
||||
|
||||
Disallow `\00` and `\000` escapes in strict mode.
|
||||
|
||||
Raise an error when an import name is a reserved word.
|
||||
|
||||
## 2.6.2 (2015-11-10)
|
||||
|
||||
### Fixes
|
||||
|
||||
Don't crash when no options object is passed.
|
||||
|
||||
## 2.6.0 (2015-11-09)
|
||||
|
||||
### Fixes
|
||||
|
||||
Add `await` as a reserved word in module sources.
|
||||
|
||||
Disallow `yield` in a parameter default value for a generator.
|
||||
|
||||
Forbid using a comma after a rest pattern in an array destructuring.
|
||||
|
||||
### New features
|
||||
|
||||
Support parsing stdin in command-line tool.
|
||||
|
||||
## 2.5.0 (2015-10-27)
|
||||
|
||||
### Fixes
|
||||
|
||||
Fix tokenizer support in the command-line tool.
|
||||
|
||||
Stop allowing `new.target` outside of functions.
|
||||
|
||||
Remove legacy `guard` and `guardedHandler` properties from try nodes.
|
||||
|
||||
Stop allowing multiple `__proto__` properties on an object literal in strict mode.
|
||||
|
||||
Don't allow rest parameters to be non-identifier patterns.
|
||||
|
||||
Check for duplicate paramter names in arrow functions.
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (C) 2012-2018 by various contributors (see AUTHORS)
|
||||
|
||||
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.
|
|
@ -0,0 +1,269 @@
|
|||
# Acorn
|
||||
|
||||
A tiny, fast JavaScript parser written in JavaScript.
|
||||
|
||||
## Community
|
||||
|
||||
Acorn is open source software released under an
|
||||
[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE).
|
||||
|
||||
You are welcome to
|
||||
[report bugs](https://github.com/acornjs/acorn/issues) or create pull
|
||||
requests on [github](https://github.com/acornjs/acorn). For questions
|
||||
and discussion, please use the
|
||||
[Tern discussion forum](https://discuss.ternjs.net).
|
||||
|
||||
## Installation
|
||||
|
||||
The easiest way to install acorn is from [`npm`](https://www.npmjs.com/):
|
||||
|
||||
```sh
|
||||
npm install acorn
|
||||
```
|
||||
|
||||
Alternately, you can download the source and build acorn yourself:
|
||||
|
||||
```sh
|
||||
git clone https://github.com/acornjs/acorn.git
|
||||
cd acorn
|
||||
npm install
|
||||
```
|
||||
|
||||
## Interface
|
||||
|
||||
**parse**`(input, options)` is the main interface to the library. The
|
||||
`input` parameter is a string, `options` can be undefined or an object
|
||||
setting some of the options listed below. The return value will be an
|
||||
abstract syntax tree object as specified by the [ESTree
|
||||
spec](https://github.com/estree/estree).
|
||||
|
||||
```javascript
|
||||
let acorn = require("acorn");
|
||||
console.log(acorn.parse("1 + 1"));
|
||||
```
|
||||
|
||||
When encountering a syntax error, the parser will raise a
|
||||
`SyntaxError` object with a meaningful message. The error object will
|
||||
have a `pos` property that indicates the string offset at which the
|
||||
error occurred, and a `loc` object that contains a `{line, column}`
|
||||
object referring to that same position.
|
||||
|
||||
Options can be provided by passing a second argument, which should be
|
||||
an object containing any of these fields:
|
||||
|
||||
- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be
|
||||
either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019) or 11
|
||||
(2020, partial support). This influences support for strict mode,
|
||||
the set of reserved words, and support for new syntax features.
|
||||
Default is 10.
|
||||
|
||||
**NOTE**: Only 'stage 4' (finalized) ECMAScript features are being
|
||||
implemented by Acorn. Other proposed new features can be implemented
|
||||
through plugins.
|
||||
|
||||
- **sourceType**: Indicate the mode the code should be parsed in. Can be
|
||||
either `"script"` or `"module"`. This influences global strict mode
|
||||
and parsing of `import` and `export` declarations.
|
||||
|
||||
**NOTE**: If set to `"module"`, then static `import` / `export` syntax
|
||||
will be valid, even if `ecmaVersion` is less than 6.
|
||||
|
||||
- **onInsertedSemicolon**: If given a callback, that callback will be
|
||||
called whenever a missing semicolon is inserted by the parser. The
|
||||
callback will be given the character offset of the point where the
|
||||
semicolon is inserted as argument, and if `locations` is on, also a
|
||||
`{line, column}` object representing this position.
|
||||
|
||||
- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing
|
||||
commas.
|
||||
|
||||
- **allowReserved**: If `false`, using a reserved word will generate
|
||||
an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher
|
||||
versions. When given the value `"never"`, reserved words and
|
||||
keywords can also not be used as property names (as in Internet
|
||||
Explorer's old parser).
|
||||
|
||||
- **allowReturnOutsideFunction**: By default, a return statement at
|
||||
the top level raises an error. Set this to `true` to accept such
|
||||
code.
|
||||
|
||||
- **allowImportExportEverywhere**: By default, `import` and `export`
|
||||
declarations can only appear at a program's top level. Setting this
|
||||
option to `true` allows them anywhere where a statement is allowed.
|
||||
|
||||
- **allowAwaitOutsideFunction**: By default, `await` expressions can
|
||||
only appear inside `async` functions. Setting this option to
|
||||
`true` allows to have top-level `await` expressions. They are
|
||||
still not allowed in non-`async` functions, though.
|
||||
|
||||
- **allowHashBang**: When this is enabled (off by default), if the
|
||||
code starts with the characters `#!` (as in a shellscript), the
|
||||
first line will be treated as a comment.
|
||||
|
||||
- **locations**: When `true`, each node has a `loc` object attached
|
||||
with `start` and `end` subobjects, each of which contains the
|
||||
one-based line and zero-based column numbers in `{line, column}`
|
||||
form. Default is `false`.
|
||||
|
||||
- **onToken**: If a function is passed for this option, each found
|
||||
token will be passed in same format as tokens returned from
|
||||
`tokenizer().getToken()`.
|
||||
|
||||
If array is passed, each found token is pushed to it.
|
||||
|
||||
Note that you are not allowed to call the parser from the
|
||||
callback—that will corrupt its internal state.
|
||||
|
||||
- **onComment**: If a function is passed for this option, whenever a
|
||||
comment is encountered the function will be called with the
|
||||
following parameters:
|
||||
|
||||
- `block`: `true` if the comment is a block comment, false if it
|
||||
is a line comment.
|
||||
- `text`: The content of the comment.
|
||||
- `start`: Character offset of the start of the comment.
|
||||
- `end`: Character offset of the end of the comment.
|
||||
|
||||
When the `locations` options is on, the `{line, column}` locations
|
||||
of the comment’s start and end are passed as two additional
|
||||
parameters.
|
||||
|
||||
If array is passed for this option, each found comment is pushed
|
||||
to it as object in Esprima format:
|
||||
|
||||
```javascript
|
||||
{
|
||||
"type": "Line" | "Block",
|
||||
"value": "comment text",
|
||||
"start": Number,
|
||||
"end": Number,
|
||||
// If `locations` option is on:
|
||||
"loc": {
|
||||
"start": {line: Number, column: Number}
|
||||
"end": {line: Number, column: Number}
|
||||
},
|
||||
// If `ranges` option is on:
|
||||
"range": [Number, Number]
|
||||
}
|
||||
```
|
||||
|
||||
Note that you are not allowed to call the parser from the
|
||||
callback—that will corrupt its internal state.
|
||||
|
||||
- **ranges**: Nodes have their start and end characters offsets
|
||||
recorded in `start` and `end` properties (directly on the node,
|
||||
rather than the `loc` object, which holds line/column data. To also
|
||||
add a
|
||||
[semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678)
|
||||
`range` property holding a `[start, end]` array with the same
|
||||
numbers, set the `ranges` option to `true`.
|
||||
|
||||
- **program**: It is possible to parse multiple files into a single
|
||||
AST by passing the tree produced by parsing the first file as the
|
||||
`program` option in subsequent parses. This will add the toplevel
|
||||
forms of the parsed file to the "Program" (top) node of an existing
|
||||
parse tree.
|
||||
|
||||
- **sourceFile**: When the `locations` option is `true`, you can pass
|
||||
this option to add a `source` attribute in every node’s `loc`
|
||||
object. Note that the contents of this option are not examined or
|
||||
processed in any way; you are free to use whatever format you
|
||||
choose.
|
||||
|
||||
- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property
|
||||
will be added (regardless of the `location` option) directly to the
|
||||
nodes, rather than the `loc` object.
|
||||
|
||||
- **preserveParens**: If this option is `true`, parenthesized expressions
|
||||
are represented by (non-standard) `ParenthesizedExpression` nodes
|
||||
that have a single `expression` property containing the expression
|
||||
inside parentheses.
|
||||
|
||||
**parseExpressionAt**`(input, offset, options)` will parse a single
|
||||
expression in a string, and return its AST. It will not complain if
|
||||
there is more of the string left after the expression.
|
||||
|
||||
**tokenizer**`(input, options)` returns an object with a `getToken`
|
||||
method that can be called repeatedly to get the next token, a `{start,
|
||||
end, type, value}` object (with added `loc` property when the
|
||||
`locations` option is enabled and `range` property when the `ranges`
|
||||
option is enabled). When the token's type is `tokTypes.eof`, you
|
||||
should stop calling the method, since it will keep returning that same
|
||||
token forever.
|
||||
|
||||
In ES6 environment, returned result can be used as any other
|
||||
protocol-compliant iterable:
|
||||
|
||||
```javascript
|
||||
for (let token of acorn.tokenizer(str)) {
|
||||
// iterate over the tokens
|
||||
}
|
||||
|
||||
// transform code to array of tokens:
|
||||
var tokens = [...acorn.tokenizer(str)];
|
||||
```
|
||||
|
||||
**tokTypes** holds an object mapping names to the token type objects
|
||||
that end up in the `type` properties of tokens.
|
||||
|
||||
**getLineInfo**`(input, offset)` can be used to get a `{line,
|
||||
column}` object for a given program string and offset.
|
||||
|
||||
### The `Parser` class
|
||||
|
||||
Instances of the **`Parser`** class contain all the state and logic
|
||||
that drives a parse. It has static methods `parse`,
|
||||
`parseExpressionAt`, and `tokenizer` that match the top-level
|
||||
functions by the same name.
|
||||
|
||||
When extending the parser with plugins, you need to call these methods
|
||||
on the extended version of the class. To extend a parser with plugins,
|
||||
you can use its static `extend` method.
|
||||
|
||||
```javascript
|
||||
var acorn = require("acorn");
|
||||
var jsx = require("acorn-jsx");
|
||||
var JSXParser = acorn.Parser.extend(jsx());
|
||||
JSXParser.parse("foo(<bar/>)");
|
||||
```
|
||||
|
||||
The `extend` method takes any number of plugin values, and returns a
|
||||
new `Parser` class that includes the extra parser logic provided by
|
||||
the plugins.
|
||||
|
||||
## Command line interface
|
||||
|
||||
The `bin/acorn` utility can be used to parse a file from the command
|
||||
line. It accepts as arguments its input file and the following
|
||||
options:
|
||||
|
||||
- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version
|
||||
to parse. Default is version 9.
|
||||
|
||||
- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise.
|
||||
|
||||
- `--locations`: Attaches a "loc" object to each node with "start" and
|
||||
"end" subobjects, each of which contains the one-based line and
|
||||
zero-based column numbers in `{line, column}` form.
|
||||
|
||||
- `--allow-hash-bang`: If the code starts with the characters #! (as
|
||||
in a shellscript), the first line will be treated as a comment.
|
||||
|
||||
- `--compact`: No whitespace is used in the AST output.
|
||||
|
||||
- `--silent`: Do not output the AST, just return the exit status.
|
||||
|
||||
- `--help`: Print the usage information and quit.
|
||||
|
||||
The utility spits out the syntax tree as JSON data.
|
||||
|
||||
## Existing plugins
|
||||
|
||||
- [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx)
|
||||
|
||||
Plugins for ECMAScript proposals:
|
||||
|
||||
- [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling:
|
||||
- [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields)
|
||||
- [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta)
|
||||
- [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n
|
|
@ -0,0 +1,4 @@
|
|||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
require('../dist/bin.js');
|
|
@ -0,0 +1,209 @@
|
|||
export as namespace acorn
|
||||
export = acorn
|
||||
|
||||
declare namespace acorn {
|
||||
function parse(input: string, options?: Options): Node
|
||||
|
||||
function parseExpressionAt(input: string, pos?: number, options?: Options): Node
|
||||
|
||||
function tokenizer(input: string, options?: Options): {
|
||||
getToken(): Token
|
||||
[Symbol.iterator](): Iterator<Token>
|
||||
}
|
||||
|
||||
interface Options {
|
||||
ecmaVersion?: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020
|
||||
sourceType?: 'script' | 'module'
|
||||
onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void
|
||||
onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void
|
||||
allowReserved?: boolean | 'never'
|
||||
allowReturnOutsideFunction?: boolean
|
||||
allowImportExportEverywhere?: boolean
|
||||
allowAwaitOutsideFunction?: boolean
|
||||
allowHashBang?: boolean
|
||||
locations?: boolean
|
||||
onToken?: ((token: Token) => any) | Token[]
|
||||
onComment?: ((
|
||||
isBlock: boolean, text: string, start: number, end: number, startLoc?: Position,
|
||||
endLoc?: Position
|
||||
) => void) | Comment[]
|
||||
ranges?: boolean
|
||||
program?: Node
|
||||
sourceFile?: string
|
||||
directSourceFile?: string
|
||||
preserveParens?: boolean
|
||||
}
|
||||
|
||||
class Parser {
|
||||
constructor(options: Options, input: string, startPos?: number)
|
||||
parse(this: Parser): Node
|
||||
static parse(this: typeof Parser, input: string, options?: Options): Node
|
||||
static parseExpressionAt(this: typeof Parser, input: string, pos: number, options?: Options): Node
|
||||
static tokenizer(this: typeof Parser, input: string, options?: Options): {
|
||||
getToken(): Token
|
||||
[Symbol.iterator](): Iterator<Token>
|
||||
}
|
||||
static extend(this: typeof Parser, ...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser
|
||||
}
|
||||
|
||||
interface Position { line: number; column: number; offset: number }
|
||||
|
||||
const defaultOptions: Options
|
||||
|
||||
function getLineInfo(input: string, offset: number): Position
|
||||
|
||||
class SourceLocation {
|
||||
start: Position
|
||||
end: Position
|
||||
source?: string | null
|
||||
constructor(p: Parser, start: Position, end: Position)
|
||||
}
|
||||
|
||||
class Node {
|
||||
type: string
|
||||
start: number
|
||||
end: number
|
||||
loc?: SourceLocation
|
||||
sourceFile?: string
|
||||
range?: [number, number]
|
||||
constructor(parser: Parser, pos: number, loc?: SourceLocation)
|
||||
}
|
||||
|
||||
class TokenType {
|
||||
label: string
|
||||
keyword: string
|
||||
beforeExpr: boolean
|
||||
startsExpr: boolean
|
||||
isLoop: boolean
|
||||
isAssign: boolean
|
||||
prefix: boolean
|
||||
postfix: boolean
|
||||
binop: number
|
||||
updateContext?: (prevType: TokenType) => void
|
||||
constructor(label: string, conf?: any)
|
||||
}
|
||||
|
||||
const tokTypes: {
|
||||
num: TokenType
|
||||
regexp: TokenType
|
||||
string: TokenType
|
||||
name: TokenType
|
||||
eof: TokenType
|
||||
bracketL: TokenType
|
||||
bracketR: TokenType
|
||||
braceL: TokenType
|
||||
braceR: TokenType
|
||||
parenL: TokenType
|
||||
parenR: TokenType
|
||||
comma: TokenType
|
||||
semi: TokenType
|
||||
colon: TokenType
|
||||
dot: TokenType
|
||||
question: TokenType
|
||||
arrow: TokenType
|
||||
template: TokenType
|
||||
ellipsis: TokenType
|
||||
backQuote: TokenType
|
||||
dollarBraceL: TokenType
|
||||
eq: TokenType
|
||||
assign: TokenType
|
||||
incDec: TokenType
|
||||
prefix: TokenType
|
||||
logicalOR: TokenType
|
||||
logicalAND: TokenType
|
||||
bitwiseOR: TokenType
|
||||
bitwiseXOR: TokenType
|
||||
bitwiseAND: TokenType
|
||||
equality: TokenType
|
||||
relational: TokenType
|
||||
bitShift: TokenType
|
||||
plusMin: TokenType
|
||||
modulo: TokenType
|
||||
star: TokenType
|
||||
slash: TokenType
|
||||
starstar: TokenType
|
||||
_break: TokenType
|
||||
_case: TokenType
|
||||
_catch: TokenType
|
||||
_continue: TokenType
|
||||
_debugger: TokenType
|
||||
_default: TokenType
|
||||
_do: TokenType
|
||||
_else: TokenType
|
||||
_finally: TokenType
|
||||
_for: TokenType
|
||||
_function: TokenType
|
||||
_if: TokenType
|
||||
_return: TokenType
|
||||
_switch: TokenType
|
||||
_throw: TokenType
|
||||
_try: TokenType
|
||||
_var: TokenType
|
||||
_const: TokenType
|
||||
_while: TokenType
|
||||
_with: TokenType
|
||||
_new: TokenType
|
||||
_this: TokenType
|
||||
_super: TokenType
|
||||
_class: TokenType
|
||||
_extends: TokenType
|
||||
_export: TokenType
|
||||
_import: TokenType
|
||||
_null: TokenType
|
||||
_true: TokenType
|
||||
_false: TokenType
|
||||
_in: TokenType
|
||||
_instanceof: TokenType
|
||||
_typeof: TokenType
|
||||
_void: TokenType
|
||||
_delete: TokenType
|
||||
}
|
||||
|
||||
class TokContext {
|
||||
constructor(token: string, isExpr: boolean, preserveSpace: boolean, override?: (p: Parser) => void)
|
||||
}
|
||||
|
||||
const tokContexts: {
|
||||
b_stat: TokContext
|
||||
b_expr: TokContext
|
||||
b_tmpl: TokContext
|
||||
p_stat: TokContext
|
||||
p_expr: TokContext
|
||||
q_tmpl: TokContext
|
||||
f_expr: TokContext
|
||||
}
|
||||
|
||||
function isIdentifierStart(code: number, astral?: boolean): boolean
|
||||
|
||||
function isIdentifierChar(code: number, astral?: boolean): boolean
|
||||
|
||||
interface AbstractToken {
|
||||
}
|
||||
|
||||
interface Comment extends AbstractToken {
|
||||
type: string
|
||||
value: string
|
||||
start: number
|
||||
end: number
|
||||
loc?: SourceLocation
|
||||
range?: [number, number]
|
||||
}
|
||||
|
||||
class Token {
|
||||
type: TokenType
|
||||
value: any
|
||||
start: number
|
||||
end: number
|
||||
loc?: SourceLocation
|
||||
range?: [number, number]
|
||||
constructor(p: Parser)
|
||||
}
|
||||
|
||||
function isNewLine(code: number): boolean
|
||||
|
||||
const lineBreak: RegExp
|
||||
|
||||
const lineBreakG: RegExp
|
||||
|
||||
const version: string
|
||||
}
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,2 @@
|
|||
import * as acorn from "./acorn";
|
||||
export = acorn;
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,64 @@
|
|||
'use strict';
|
||||
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
var acorn = require('./acorn.js');
|
||||
|
||||
var infile, forceFile, silent = false, compact = false, tokenize = false;
|
||||
var options = {};
|
||||
|
||||
function help(status) {
|
||||
var print = (status === 0) ? console.log : console.error;
|
||||
print("usage: " + path.basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|...|--ecma2015|--ecma2016|--ecma2017|--ecma2018|...]");
|
||||
print(" [--tokenize] [--locations] [---allow-hash-bang] [--compact] [--silent] [--module] [--help] [--] [infile]");
|
||||
process.exit(status);
|
||||
}
|
||||
|
||||
for (var i = 2; i < process.argv.length; ++i) {
|
||||
var arg = process.argv[i];
|
||||
if ((arg === "-" || arg[0] !== "-") && !infile) { infile = arg; }
|
||||
else if (arg === "--" && !infile && i + 2 === process.argv.length) { forceFile = infile = process.argv[++i]; }
|
||||
else if (arg === "--locations") { options.locations = true; }
|
||||
else if (arg === "--allow-hash-bang") { options.allowHashBang = true; }
|
||||
else if (arg === "--silent") { silent = true; }
|
||||
else if (arg === "--compact") { compact = true; }
|
||||
else if (arg === "--help") { help(0); }
|
||||
else if (arg === "--tokenize") { tokenize = true; }
|
||||
else if (arg === "--module") { options.sourceType = "module"; }
|
||||
else {
|
||||
var match = arg.match(/^--ecma(\d+)$/);
|
||||
if (match)
|
||||
{ options.ecmaVersion = +match[1]; }
|
||||
else
|
||||
{ help(1); }
|
||||
}
|
||||
}
|
||||
|
||||
function run(code) {
|
||||
var result;
|
||||
try {
|
||||
if (!tokenize) {
|
||||
result = acorn.parse(code, options);
|
||||
} else {
|
||||
result = [];
|
||||
var tokenizer = acorn.tokenizer(code, options), token;
|
||||
do {
|
||||
token = tokenizer.getToken();
|
||||
result.push(token);
|
||||
} while (token.type !== acorn.tokTypes.eof)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(infile && infile !== "-" ? e.message.replace(/\(\d+:\d+\)$/, function (m) { return m.slice(0, 1) + infile + " " + m.slice(1); }) : e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
if (!silent) { console.log(JSON.stringify(result, null, compact ? null : 2)); }
|
||||
}
|
||||
|
||||
if (forceFile || infile && infile !== "-") {
|
||||
run(fs.readFileSync(infile, "utf8"));
|
||||
} else {
|
||||
var code = "";
|
||||
process.stdin.resume();
|
||||
process.stdin.on("data", function (chunk) { return code += chunk; });
|
||||
process.stdin.on("end", function () { return run(code); });
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
{
|
||||
"_from": "acorn@^7.1.1",
|
||||
"_id": "acorn@7.4.1",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-nQyp0o1/mNdbTO1PO6kHkwSrmgZ0MT/jCCpNiwbUjGoRN4dlBhqJtoQuCnEOKzgTVwg0ZWiCoQy6SxMebQVh8A==",
|
||||
"_location": "/acorn",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "acorn@^7.1.1",
|
||||
"name": "acorn",
|
||||
"escapedName": "acorn",
|
||||
"rawSpec": "^7.1.1",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^7.1.1"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/acorn-globals",
|
||||
"/jsdom"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.1.tgz",
|
||||
"_shasum": "feaed255973d2e77555b83dbc08851a6c63520fa",
|
||||
"_spec": "acorn@^7.1.1",
|
||||
"_where": "/home/centos/markdown/node_modules/jsdom",
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/acornjs/acorn/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"deprecated": false,
|
||||
"description": "ECMAScript parser",
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
},
|
||||
"homepage": "https://github.com/acornjs/acorn",
|
||||
"license": "MIT",
|
||||
"main": "dist/acorn.js",
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "Marijn Haverbeke",
|
||||
"email": "marijnh@gmail.com",
|
||||
"url": "https://marijnhaverbeke.nl"
|
||||
},
|
||||
{
|
||||
"name": "Ingvar Stepanyan",
|
||||
"email": "me@rreverser.com",
|
||||
"url": "https://rreverser.com/"
|
||||
},
|
||||
{
|
||||
"name": "Adrian Heine",
|
||||
"url": "http://adrianheine.de"
|
||||
}
|
||||
],
|
||||
"module": "dist/acorn.mjs",
|
||||
"name": "acorn",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/acornjs/acorn.git"
|
||||
},
|
||||
"scripts": {
|
||||
"prepare": "cd ..; npm run build:main && npm run build:bin"
|
||||
},
|
||||
"types": "dist/acorn.d.ts",
|
||||
"version": "7.4.1"
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
var Ajv = require('ajv');
|
||||
var ajv = new Ajv({allErrors: true});
|
||||
|
||||
var schema = {
|
||||
"properties": {
|
||||
"foo": { "type": "string" },
|
||||
"bar": { "type": "number", "maximum": 3 }
|
||||
}
|
||||
};
|
||||
|
||||
var validate = ajv.compile(schema);
|
||||
|
||||
test({"foo": "abc", "bar": 2});
|
||||
test({"foo": 2, "bar": 4});
|
||||
|
||||
function test(data) {
|
||||
var valid = validate(data);
|
||||
if (valid) console.log('Valid!');
|
||||
else console.log('Invalid: ' + ajv.errorsText(validate.errors));
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-2017 Evgeny Poberezkin
|
||||
|
||||
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.
|
||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,397 @@
|
|||
declare var ajv: {
|
||||
(options?: ajv.Options): ajv.Ajv;
|
||||
new(options?: ajv.Options): ajv.Ajv;
|
||||
ValidationError: typeof AjvErrors.ValidationError;
|
||||
MissingRefError: typeof AjvErrors.MissingRefError;
|
||||
$dataMetaSchema: object;
|
||||
}
|
||||
|
||||
declare namespace AjvErrors {
|
||||
class ValidationError extends Error {
|
||||
constructor(errors: Array<ajv.ErrorObject>);
|
||||
|
||||
message: string;
|
||||
errors: Array<ajv.ErrorObject>;
|
||||
ajv: true;
|
||||
validation: true;
|
||||
}
|
||||
|
||||
class MissingRefError extends Error {
|
||||
constructor(baseId: string, ref: string, message?: string);
|
||||
static message: (baseId: string, ref: string) => string;
|
||||
|
||||
message: string;
|
||||
missingRef: string;
|
||||
missingSchema: string;
|
||||
}
|
||||
}
|
||||
|
||||
declare namespace ajv {
|
||||
type ValidationError = AjvErrors.ValidationError;
|
||||
|
||||
type MissingRefError = AjvErrors.MissingRefError;
|
||||
|
||||
interface Ajv {
|
||||
/**
|
||||
* Validate data using schema
|
||||
* Schema will be compiled and cached (using serialized JSON as key, [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize by default).
|
||||
* @param {string|object|Boolean} schemaKeyRef key, ref or schema object
|
||||
* @param {Any} data to be validated
|
||||
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
|
||||
*/
|
||||
validate(schemaKeyRef: object | string | boolean, data: any): boolean | PromiseLike<any>;
|
||||
/**
|
||||
* Create validating function for passed schema.
|
||||
* @param {object|Boolean} schema schema object
|
||||
* @return {Function} validating function
|
||||
*/
|
||||
compile(schema: object | boolean): ValidateFunction;
|
||||
/**
|
||||
* Creates validating function for passed schema with asynchronous loading of missing schemas.
|
||||
* `loadSchema` option should be a function that accepts schema uri and node-style callback.
|
||||
* @this Ajv
|
||||
* @param {object|Boolean} schema schema object
|
||||
* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
|
||||
* @param {Function} callback optional node-style callback, it is always called with 2 parameters: error (or null) and validating function.
|
||||
* @return {PromiseLike<ValidateFunction>} validating function
|
||||
*/
|
||||
compileAsync(schema: object | boolean, meta?: Boolean, callback?: (err: Error, validate: ValidateFunction) => any): PromiseLike<ValidateFunction>;
|
||||
/**
|
||||
* Adds schema to the instance.
|
||||
* @param {object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
|
||||
* @param {string} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
addSchema(schema: Array<object> | object, key?: string): Ajv;
|
||||
/**
|
||||
* Add schema that will be used to validate other schemas
|
||||
* options in META_IGNORE_OPTIONS are alway set to false
|
||||
* @param {object} schema schema object
|
||||
* @param {string} key optional schema key
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
addMetaSchema(schema: object, key?: string): Ajv;
|
||||
/**
|
||||
* Validate schema
|
||||
* @param {object|Boolean} schema schema to validate
|
||||
* @return {Boolean} true if schema is valid
|
||||
*/
|
||||
validateSchema(schema: object | boolean): boolean;
|
||||
/**
|
||||
* Get compiled schema from the instance by `key` or `ref`.
|
||||
* @param {string} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
|
||||
* @return {Function} schema validating function (with property `schema`). Returns undefined if keyRef can't be resolved to an existing schema.
|
||||
*/
|
||||
getSchema(keyRef: string): ValidateFunction | undefined;
|
||||
/**
|
||||
* Remove cached schema(s).
|
||||
* If no parameter is passed all schemas but meta-schemas are removed.
|
||||
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
|
||||
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
|
||||
* @param {string|object|RegExp|Boolean} schemaKeyRef key, ref, pattern to match key/ref or schema object
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
removeSchema(schemaKeyRef?: object | string | RegExp | boolean): Ajv;
|
||||
/**
|
||||
* Add custom format
|
||||
* @param {string} name format name
|
||||
* @param {string|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
addFormat(name: string, format: FormatValidator | FormatDefinition): Ajv;
|
||||
/**
|
||||
* Define custom keyword
|
||||
* @this Ajv
|
||||
* @param {string} keyword custom keyword, should be a valid identifier, should be different from all standard, custom and macro keywords.
|
||||
* @param {object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
addKeyword(keyword: string, definition: KeywordDefinition): Ajv;
|
||||
/**
|
||||
* Get keyword definition
|
||||
* @this Ajv
|
||||
* @param {string} keyword pre-defined or custom keyword.
|
||||
* @return {object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
|
||||
*/
|
||||
getKeyword(keyword: string): object | boolean;
|
||||
/**
|
||||
* Remove keyword
|
||||
* @this Ajv
|
||||
* @param {string} keyword pre-defined or custom keyword.
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
removeKeyword(keyword: string): Ajv;
|
||||
/**
|
||||
* Validate keyword
|
||||
* @this Ajv
|
||||
* @param {object} definition keyword definition object
|
||||
* @param {boolean} throwError true to throw exception if definition is invalid
|
||||
* @return {boolean} validation result
|
||||
*/
|
||||
validateKeyword(definition: KeywordDefinition, throwError: boolean): boolean;
|
||||
/**
|
||||
* Convert array of error message objects to string
|
||||
* @param {Array<object>} errors optional array of validation errors, if not passed errors from the instance are used.
|
||||
* @param {object} options optional options with properties `separator` and `dataVar`.
|
||||
* @return {string} human readable string with all errors descriptions
|
||||
*/
|
||||
errorsText(errors?: Array<ErrorObject> | null, options?: ErrorsTextOptions): string;
|
||||
errors?: Array<ErrorObject> | null;
|
||||
_opts: Options;
|
||||
}
|
||||
|
||||
interface CustomLogger {
|
||||
log(...args: any[]): any;
|
||||
warn(...args: any[]): any;
|
||||
error(...args: any[]): any;
|
||||
}
|
||||
|
||||
interface ValidateFunction {
|
||||
(
|
||||
data: any,
|
||||
dataPath?: string,
|
||||
parentData?: object | Array<any>,
|
||||
parentDataProperty?: string | number,
|
||||
rootData?: object | Array<any>
|
||||
): boolean | PromiseLike<any>;
|
||||
schema?: object | boolean;
|
||||
errors?: null | Array<ErrorObject>;
|
||||
refs?: object;
|
||||
refVal?: Array<any>;
|
||||
root?: ValidateFunction | object;
|
||||
$async?: true;
|
||||
source?: object;
|
||||
}
|
||||
|
||||
interface Options {
|
||||
$data?: boolean;
|
||||
allErrors?: boolean;
|
||||
verbose?: boolean;
|
||||
jsonPointers?: boolean;
|
||||
uniqueItems?: boolean;
|
||||
unicode?: boolean;
|
||||
format?: false | string;
|
||||
formats?: object;
|
||||
keywords?: object;
|
||||
unknownFormats?: true | string[] | 'ignore';
|
||||
schemas?: Array<object> | object;
|
||||
schemaId?: '$id' | 'id' | 'auto';
|
||||
missingRefs?: true | 'ignore' | 'fail';
|
||||
extendRefs?: true | 'ignore' | 'fail';
|
||||
loadSchema?: (uri: string, cb?: (err: Error, schema: object) => void) => PromiseLike<object | boolean>;
|
||||
removeAdditional?: boolean | 'all' | 'failing';
|
||||
useDefaults?: boolean | 'empty' | 'shared';
|
||||
coerceTypes?: boolean | 'array';
|
||||
strictDefaults?: boolean | 'log';
|
||||
strictKeywords?: boolean | 'log';
|
||||
strictNumbers?: boolean;
|
||||
async?: boolean | string;
|
||||
transpile?: string | ((code: string) => string);
|
||||
meta?: boolean | object;
|
||||
validateSchema?: boolean | 'log';
|
||||
addUsedSchema?: boolean;
|
||||
inlineRefs?: boolean | number;
|
||||
passContext?: boolean;
|
||||
loopRequired?: number;
|
||||
ownProperties?: boolean;
|
||||
multipleOfPrecision?: boolean | number;
|
||||
errorDataPath?: string,
|
||||
messages?: boolean;
|
||||
sourceCode?: boolean;
|
||||
processCode?: (code: string, schema: object) => string;
|
||||
cache?: object;
|
||||
logger?: CustomLogger | false;
|
||||
nullable?: boolean;
|
||||
serialize?: ((schema: object | boolean) => any) | false;
|
||||
}
|
||||
|
||||
type FormatValidator = string | RegExp | ((data: string) => boolean | PromiseLike<any>);
|
||||
type NumberFormatValidator = ((data: number) => boolean | PromiseLike<any>);
|
||||
|
||||
interface NumberFormatDefinition {
|
||||
type: "number",
|
||||
validate: NumberFormatValidator;
|
||||
compare?: (data1: number, data2: number) => number;
|
||||
async?: boolean;
|
||||
}
|
||||
|
||||
interface StringFormatDefinition {
|
||||
type?: "string",
|
||||
validate: FormatValidator;
|
||||
compare?: (data1: string, data2: string) => number;
|
||||
async?: boolean;
|
||||
}
|
||||
|
||||
type FormatDefinition = NumberFormatDefinition | StringFormatDefinition;
|
||||
|
||||
interface KeywordDefinition {
|
||||
type?: string | Array<string>;
|
||||
async?: boolean;
|
||||
$data?: boolean;
|
||||
errors?: boolean | string;
|
||||
metaSchema?: object;
|
||||
// schema: false makes validate not to expect schema (ValidateFunction)
|
||||
schema?: boolean;
|
||||
statements?: boolean;
|
||||
dependencies?: Array<string>;
|
||||
modifying?: boolean;
|
||||
valid?: boolean;
|
||||
// one and only one of the following properties should be present
|
||||
validate?: SchemaValidateFunction | ValidateFunction;
|
||||
compile?: (schema: any, parentSchema: object, it: CompilationContext) => ValidateFunction;
|
||||
macro?: (schema: any, parentSchema: object, it: CompilationContext) => object | boolean;
|
||||
inline?: (it: CompilationContext, keyword: string, schema: any, parentSchema: object) => string;
|
||||
}
|
||||
|
||||
interface CompilationContext {
|
||||
level: number;
|
||||
dataLevel: number;
|
||||
dataPathArr: string[];
|
||||
schema: any;
|
||||
schemaPath: string;
|
||||
baseId: string;
|
||||
async: boolean;
|
||||
opts: Options;
|
||||
formats: {
|
||||
[index: string]: FormatDefinition | undefined;
|
||||
};
|
||||
keywords: {
|
||||
[index: string]: KeywordDefinition | undefined;
|
||||
};
|
||||
compositeRule: boolean;
|
||||
validate: (schema: object) => boolean;
|
||||
util: {
|
||||
copy(obj: any, target?: any): any;
|
||||
toHash(source: string[]): { [index: string]: true | undefined };
|
||||
equal(obj: any, target: any): boolean;
|
||||
getProperty(str: string): string;
|
||||
schemaHasRules(schema: object, rules: any): string;
|
||||
escapeQuotes(str: string): string;
|
||||
toQuotedString(str: string): string;
|
||||
getData(jsonPointer: string, dataLevel: number, paths: string[]): string;
|
||||
escapeJsonPointer(str: string): string;
|
||||
unescapeJsonPointer(str: string): string;
|
||||
escapeFragment(str: string): string;
|
||||
unescapeFragment(str: string): string;
|
||||
};
|
||||
self: Ajv;
|
||||
}
|
||||
|
||||
interface SchemaValidateFunction {
|
||||
(
|
||||
schema: any,
|
||||
data: any,
|
||||
parentSchema?: object,
|
||||
dataPath?: string,
|
||||
parentData?: object | Array<any>,
|
||||
parentDataProperty?: string | number,
|
||||
rootData?: object | Array<any>
|
||||
): boolean | PromiseLike<any>;
|
||||
errors?: Array<ErrorObject>;
|
||||
}
|
||||
|
||||
interface ErrorsTextOptions {
|
||||
separator?: string;
|
||||
dataVar?: string;
|
||||
}
|
||||
|
||||
interface ErrorObject {
|
||||
keyword: string;
|
||||
dataPath: string;
|
||||
schemaPath: string;
|
||||
params: ErrorParameters;
|
||||
// Added to validation errors of propertyNames keyword schema
|
||||
propertyName?: string;
|
||||
// Excluded if messages set to false.
|
||||
message?: string;
|
||||
// These are added with the `verbose` option.
|
||||
schema?: any;
|
||||
parentSchema?: object;
|
||||
data?: any;
|
||||
}
|
||||
|
||||
type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams |
|
||||
DependenciesParams | FormatParams | ComparisonParams |
|
||||
MultipleOfParams | PatternParams | RequiredParams |
|
||||
TypeParams | UniqueItemsParams | CustomParams |
|
||||
PatternRequiredParams | PropertyNamesParams |
|
||||
IfParams | SwitchParams | NoParams | EnumParams;
|
||||
|
||||
interface RefParams {
|
||||
ref: string;
|
||||
}
|
||||
|
||||
interface LimitParams {
|
||||
limit: number;
|
||||
}
|
||||
|
||||
interface AdditionalPropertiesParams {
|
||||
additionalProperty: string;
|
||||
}
|
||||
|
||||
interface DependenciesParams {
|
||||
property: string;
|
||||
missingProperty: string;
|
||||
depsCount: number;
|
||||
deps: string;
|
||||
}
|
||||
|
||||
interface FormatParams {
|
||||
format: string
|
||||
}
|
||||
|
||||
interface ComparisonParams {
|
||||
comparison: string;
|
||||
limit: number | string;
|
||||
exclusive: boolean;
|
||||
}
|
||||
|
||||
interface MultipleOfParams {
|
||||
multipleOf: number;
|
||||
}
|
||||
|
||||
interface PatternParams {
|
||||
pattern: string;
|
||||
}
|
||||
|
||||
interface RequiredParams {
|
||||
missingProperty: string;
|
||||
}
|
||||
|
||||
interface TypeParams {
|
||||
type: string;
|
||||
}
|
||||
|
||||
interface UniqueItemsParams {
|
||||
i: number;
|
||||
j: number;
|
||||
}
|
||||
|
||||
interface CustomParams {
|
||||
keyword: string;
|
||||
}
|
||||
|
||||
interface PatternRequiredParams {
|
||||
missingPattern: string;
|
||||
}
|
||||
|
||||
interface PropertyNamesParams {
|
||||
propertyName: string;
|
||||
}
|
||||
|
||||
interface IfParams {
|
||||
failingKeyword: string;
|
||||
}
|
||||
|
||||
interface SwitchParams {
|
||||
caseIndex: number;
|
||||
}
|
||||
|
||||
interface NoParams { }
|
||||
|
||||
interface EnumParams {
|
||||
allowedValues: Array<any>;
|
||||
}
|
||||
}
|
||||
|
||||
export = ajv;
|
|
@ -0,0 +1,506 @@
|
|||
'use strict';
|
||||
|
||||
var compileSchema = require('./compile')
|
||||
, resolve = require('./compile/resolve')
|
||||
, Cache = require('./cache')
|
||||
, SchemaObject = require('./compile/schema_obj')
|
||||
, stableStringify = require('fast-json-stable-stringify')
|
||||
, formats = require('./compile/formats')
|
||||
, rules = require('./compile/rules')
|
||||
, $dataMetaSchema = require('./data')
|
||||
, util = require('./compile/util');
|
||||
|
||||
module.exports = Ajv;
|
||||
|
||||
Ajv.prototype.validate = validate;
|
||||
Ajv.prototype.compile = compile;
|
||||
Ajv.prototype.addSchema = addSchema;
|
||||
Ajv.prototype.addMetaSchema = addMetaSchema;
|
||||
Ajv.prototype.validateSchema = validateSchema;
|
||||
Ajv.prototype.getSchema = getSchema;
|
||||
Ajv.prototype.removeSchema = removeSchema;
|
||||
Ajv.prototype.addFormat = addFormat;
|
||||
Ajv.prototype.errorsText = errorsText;
|
||||
|
||||
Ajv.prototype._addSchema = _addSchema;
|
||||
Ajv.prototype._compile = _compile;
|
||||
|
||||
Ajv.prototype.compileAsync = require('./compile/async');
|
||||
var customKeyword = require('./keyword');
|
||||
Ajv.prototype.addKeyword = customKeyword.add;
|
||||
Ajv.prototype.getKeyword = customKeyword.get;
|
||||
Ajv.prototype.removeKeyword = customKeyword.remove;
|
||||
Ajv.prototype.validateKeyword = customKeyword.validate;
|
||||
|
||||
var errorClasses = require('./compile/error_classes');
|
||||
Ajv.ValidationError = errorClasses.Validation;
|
||||
Ajv.MissingRefError = errorClasses.MissingRef;
|
||||
Ajv.$dataMetaSchema = $dataMetaSchema;
|
||||
|
||||
var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
|
||||
|
||||
var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
|
||||
var META_SUPPORT_DATA = ['/properties'];
|
||||
|
||||
/**
|
||||
* Creates validator instance.
|
||||
* Usage: `Ajv(opts)`
|
||||
* @param {Object} opts optional options
|
||||
* @return {Object} ajv instance
|
||||
*/
|
||||
function Ajv(opts) {
|
||||
if (!(this instanceof Ajv)) return new Ajv(opts);
|
||||
opts = this._opts = util.copy(opts) || {};
|
||||
setLogger(this);
|
||||
this._schemas = {};
|
||||
this._refs = {};
|
||||
this._fragments = {};
|
||||
this._formats = formats(opts.format);
|
||||
|
||||
this._cache = opts.cache || new Cache;
|
||||
this._loadingSchemas = {};
|
||||
this._compilations = [];
|
||||
this.RULES = rules();
|
||||
this._getId = chooseGetId(opts);
|
||||
|
||||
opts.loopRequired = opts.loopRequired || Infinity;
|
||||
if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
|
||||
if (opts.serialize === undefined) opts.serialize = stableStringify;
|
||||
this._metaOpts = getMetaSchemaOptions(this);
|
||||
|
||||
if (opts.formats) addInitialFormats(this);
|
||||
if (opts.keywords) addInitialKeywords(this);
|
||||
addDefaultMetaSchema(this);
|
||||
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
|
||||
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
|
||||
addInitialSchemas(this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Validate data using schema
|
||||
* Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
|
||||
* @this Ajv
|
||||
* @param {String|Object} schemaKeyRef key, ref or schema object
|
||||
* @param {Any} data to be validated
|
||||
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
|
||||
*/
|
||||
function validate(schemaKeyRef, data) {
|
||||
var v;
|
||||
if (typeof schemaKeyRef == 'string') {
|
||||
v = this.getSchema(schemaKeyRef);
|
||||
if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
|
||||
} else {
|
||||
var schemaObj = this._addSchema(schemaKeyRef);
|
||||
v = schemaObj.validate || this._compile(schemaObj);
|
||||
}
|
||||
|
||||
var valid = v(data);
|
||||
if (v.$async !== true) this.errors = v.errors;
|
||||
return valid;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create validating function for passed schema.
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema object
|
||||
* @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
|
||||
* @return {Function} validating function
|
||||
*/
|
||||
function compile(schema, _meta) {
|
||||
var schemaObj = this._addSchema(schema, undefined, _meta);
|
||||
return schemaObj.validate || this._compile(schemaObj);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds schema to the instance.
|
||||
* @this Ajv
|
||||
* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
|
||||
* @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
|
||||
* @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
|
||||
* @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
function addSchema(schema, key, _skipValidation, _meta) {
|
||||
if (Array.isArray(schema)){
|
||||
for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
|
||||
return this;
|
||||
}
|
||||
var id = this._getId(schema);
|
||||
if (id !== undefined && typeof id != 'string')
|
||||
throw new Error('schema id must be string');
|
||||
key = resolve.normalizeId(key || id);
|
||||
checkUnique(this, key);
|
||||
this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add schema that will be used to validate other schemas
|
||||
* options in META_IGNORE_OPTIONS are alway set to false
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema object
|
||||
* @param {String} key optional schema key
|
||||
* @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
function addMetaSchema(schema, key, skipValidation) {
|
||||
this.addSchema(schema, key, skipValidation, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Validate schema
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema to validate
|
||||
* @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
|
||||
* @return {Boolean} true if schema is valid
|
||||
*/
|
||||
function validateSchema(schema, throwOrLogError) {
|
||||
var $schema = schema.$schema;
|
||||
if ($schema !== undefined && typeof $schema != 'string')
|
||||
throw new Error('$schema must be a string');
|
||||
$schema = $schema || this._opts.defaultMeta || defaultMeta(this);
|
||||
if (!$schema) {
|
||||
this.logger.warn('meta-schema not available');
|
||||
this.errors = null;
|
||||
return true;
|
||||
}
|
||||
var valid = this.validate($schema, schema);
|
||||
if (!valid && throwOrLogError) {
|
||||
var message = 'schema is invalid: ' + this.errorsText();
|
||||
if (this._opts.validateSchema == 'log') this.logger.error(message);
|
||||
else throw new Error(message);
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
|
||||
|
||||
function defaultMeta(self) {
|
||||
var meta = self._opts.meta;
|
||||
self._opts.defaultMeta = typeof meta == 'object'
|
||||
? self._getId(meta) || meta
|
||||
: self.getSchema(META_SCHEMA_ID)
|
||||
? META_SCHEMA_ID
|
||||
: undefined;
|
||||
return self._opts.defaultMeta;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get compiled schema from the instance by `key` or `ref`.
|
||||
* @this Ajv
|
||||
* @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
|
||||
* @return {Function} schema validating function (with property `schema`).
|
||||
*/
|
||||
function getSchema(keyRef) {
|
||||
var schemaObj = _getSchemaObj(this, keyRef);
|
||||
switch (typeof schemaObj) {
|
||||
case 'object': return schemaObj.validate || this._compile(schemaObj);
|
||||
case 'string': return this.getSchema(schemaObj);
|
||||
case 'undefined': return _getSchemaFragment(this, keyRef);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function _getSchemaFragment(self, ref) {
|
||||
var res = resolve.schema.call(self, { schema: {} }, ref);
|
||||
if (res) {
|
||||
var schema = res.schema
|
||||
, root = res.root
|
||||
, baseId = res.baseId;
|
||||
var v = compileSchema.call(self, schema, root, undefined, baseId);
|
||||
self._fragments[ref] = new SchemaObject({
|
||||
ref: ref,
|
||||
fragment: true,
|
||||
schema: schema,
|
||||
root: root,
|
||||
baseId: baseId,
|
||||
validate: v
|
||||
});
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function _getSchemaObj(self, keyRef) {
|
||||
keyRef = resolve.normalizeId(keyRef);
|
||||
return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Remove cached schema(s).
|
||||
* If no parameter is passed all schemas but meta-schemas are removed.
|
||||
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
|
||||
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
|
||||
* @this Ajv
|
||||
* @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
function removeSchema(schemaKeyRef) {
|
||||
if (schemaKeyRef instanceof RegExp) {
|
||||
_removeAllSchemas(this, this._schemas, schemaKeyRef);
|
||||
_removeAllSchemas(this, this._refs, schemaKeyRef);
|
||||
return this;
|
||||
}
|
||||
switch (typeof schemaKeyRef) {
|
||||
case 'undefined':
|
||||
_removeAllSchemas(this, this._schemas);
|
||||
_removeAllSchemas(this, this._refs);
|
||||
this._cache.clear();
|
||||
return this;
|
||||
case 'string':
|
||||
var schemaObj = _getSchemaObj(this, schemaKeyRef);
|
||||
if (schemaObj) this._cache.del(schemaObj.cacheKey);
|
||||
delete this._schemas[schemaKeyRef];
|
||||
delete this._refs[schemaKeyRef];
|
||||
return this;
|
||||
case 'object':
|
||||
var serialize = this._opts.serialize;
|
||||
var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
|
||||
this._cache.del(cacheKey);
|
||||
var id = this._getId(schemaKeyRef);
|
||||
if (id) {
|
||||
id = resolve.normalizeId(id);
|
||||
delete this._schemas[id];
|
||||
delete this._refs[id];
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
function _removeAllSchemas(self, schemas, regex) {
|
||||
for (var keyRef in schemas) {
|
||||
var schemaObj = schemas[keyRef];
|
||||
if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
|
||||
self._cache.del(schemaObj.cacheKey);
|
||||
delete schemas[keyRef];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* @this Ajv */
|
||||
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
|
||||
if (typeof schema != 'object' && typeof schema != 'boolean')
|
||||
throw new Error('schema should be object or boolean');
|
||||
var serialize = this._opts.serialize;
|
||||
var cacheKey = serialize ? serialize(schema) : schema;
|
||||
var cached = this._cache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
|
||||
|
||||
var id = resolve.normalizeId(this._getId(schema));
|
||||
if (id && shouldAddSchema) checkUnique(this, id);
|
||||
|
||||
var willValidate = this._opts.validateSchema !== false && !skipValidation;
|
||||
var recursiveMeta;
|
||||
if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
|
||||
this.validateSchema(schema, true);
|
||||
|
||||
var localRefs = resolve.ids.call(this, schema);
|
||||
|
||||
var schemaObj = new SchemaObject({
|
||||
id: id,
|
||||
schema: schema,
|
||||
localRefs: localRefs,
|
||||
cacheKey: cacheKey,
|
||||
meta: meta
|
||||
});
|
||||
|
||||
if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
|
||||
this._cache.put(cacheKey, schemaObj);
|
||||
|
||||
if (willValidate && recursiveMeta) this.validateSchema(schema, true);
|
||||
|
||||
return schemaObj;
|
||||
}
|
||||
|
||||
|
||||
/* @this Ajv */
|
||||
function _compile(schemaObj, root) {
|
||||
if (schemaObj.compiling) {
|
||||
schemaObj.validate = callValidate;
|
||||
callValidate.schema = schemaObj.schema;
|
||||
callValidate.errors = null;
|
||||
callValidate.root = root ? root : callValidate;
|
||||
if (schemaObj.schema.$async === true)
|
||||
callValidate.$async = true;
|
||||
return callValidate;
|
||||
}
|
||||
schemaObj.compiling = true;
|
||||
|
||||
var currentOpts;
|
||||
if (schemaObj.meta) {
|
||||
currentOpts = this._opts;
|
||||
this._opts = this._metaOpts;
|
||||
}
|
||||
|
||||
var v;
|
||||
try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
|
||||
catch(e) {
|
||||
delete schemaObj.validate;
|
||||
throw e;
|
||||
}
|
||||
finally {
|
||||
schemaObj.compiling = false;
|
||||
if (schemaObj.meta) this._opts = currentOpts;
|
||||
}
|
||||
|
||||
schemaObj.validate = v;
|
||||
schemaObj.refs = v.refs;
|
||||
schemaObj.refVal = v.refVal;
|
||||
schemaObj.root = v.root;
|
||||
return v;
|
||||
|
||||
|
||||
/* @this {*} - custom context, see passContext option */
|
||||
function callValidate() {
|
||||
/* jshint validthis: true */
|
||||
var _validate = schemaObj.validate;
|
||||
var result = _validate.apply(this, arguments);
|
||||
callValidate.errors = _validate.errors;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function chooseGetId(opts) {
|
||||
switch (opts.schemaId) {
|
||||
case 'auto': return _get$IdOrId;
|
||||
case 'id': return _getId;
|
||||
default: return _get$Id;
|
||||
}
|
||||
}
|
||||
|
||||
/* @this Ajv */
|
||||
function _getId(schema) {
|
||||
if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
|
||||
return schema.id;
|
||||
}
|
||||
|
||||
/* @this Ajv */
|
||||
function _get$Id(schema) {
|
||||
if (schema.id) this.logger.warn('schema id ignored', schema.id);
|
||||
return schema.$id;
|
||||
}
|
||||
|
||||
|
||||
function _get$IdOrId(schema) {
|
||||
if (schema.$id && schema.id && schema.$id != schema.id)
|
||||
throw new Error('schema $id is different from id');
|
||||
return schema.$id || schema.id;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Convert array of error message objects to string
|
||||
* @this Ajv
|
||||
* @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
|
||||
* @param {Object} options optional options with properties `separator` and `dataVar`.
|
||||
* @return {String} human readable string with all errors descriptions
|
||||
*/
|
||||
function errorsText(errors, options) {
|
||||
errors = errors || this.errors;
|
||||
if (!errors) return 'No errors';
|
||||
options = options || {};
|
||||
var separator = options.separator === undefined ? ', ' : options.separator;
|
||||
var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
|
||||
|
||||
var text = '';
|
||||
for (var i=0; i<errors.length; i++) {
|
||||
var e = errors[i];
|
||||
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
|
||||
}
|
||||
return text.slice(0, -separator.length);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add custom format
|
||||
* @this Ajv
|
||||
* @param {String} name format name
|
||||
* @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
|
||||
* @return {Ajv} this for method chaining
|
||||
*/
|
||||
function addFormat(name, format) {
|
||||
if (typeof format == 'string') format = new RegExp(format);
|
||||
this._formats[name] = format;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
function addDefaultMetaSchema(self) {
|
||||
var $dataSchema;
|
||||
if (self._opts.$data) {
|
||||
$dataSchema = require('./refs/data.json');
|
||||
self.addMetaSchema($dataSchema, $dataSchema.$id, true);
|
||||
}
|
||||
if (self._opts.meta === false) return;
|
||||
var metaSchema = require('./refs/json-schema-draft-07.json');
|
||||
if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
|
||||
self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
|
||||
self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
|
||||
}
|
||||
|
||||
|
||||
function addInitialSchemas(self) {
|
||||
var optsSchemas = self._opts.schemas;
|
||||
if (!optsSchemas) return;
|
||||
if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
|
||||
else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
|
||||
}
|
||||
|
||||
|
||||
function addInitialFormats(self) {
|
||||
for (var name in self._opts.formats) {
|
||||
var format = self._opts.formats[name];
|
||||
self.addFormat(name, format);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function addInitialKeywords(self) {
|
||||
for (var name in self._opts.keywords) {
|
||||
var keyword = self._opts.keywords[name];
|
||||
self.addKeyword(name, keyword);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function checkUnique(self, id) {
|
||||
if (self._schemas[id] || self._refs[id])
|
||||
throw new Error('schema with key or id "' + id + '" already exists');
|
||||
}
|
||||
|
||||
|
||||
function getMetaSchemaOptions(self) {
|
||||
var metaOpts = util.copy(self._opts);
|
||||
for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
|
||||
delete metaOpts[META_IGNORE_OPTIONS[i]];
|
||||
return metaOpts;
|
||||
}
|
||||
|
||||
|
||||
function setLogger(self) {
|
||||
var logger = self._opts.logger;
|
||||
if (logger === false) {
|
||||
self.logger = {log: noop, warn: noop, error: noop};
|
||||
} else {
|
||||
if (logger === undefined) logger = console;
|
||||
if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
|
||||
throw new Error('logger must implement log, warn and error methods');
|
||||
self.logger = logger;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function noop() {}
|
|
@ -0,0 +1,26 @@
|
|||
'use strict';
|
||||
|
||||
|
||||
var Cache = module.exports = function Cache() {
|
||||
this._cache = {};
|
||||
};
|
||||
|
||||
|
||||
Cache.prototype.put = function Cache_put(key, value) {
|
||||
this._cache[key] = value;
|
||||
};
|
||||
|
||||
|
||||
Cache.prototype.get = function Cache_get(key) {
|
||||
return this._cache[key];
|
||||
};
|
||||
|
||||
|
||||
Cache.prototype.del = function Cache_del(key) {
|
||||
delete this._cache[key];
|
||||
};
|
||||
|
||||
|
||||
Cache.prototype.clear = function Cache_clear() {
|
||||
this._cache = {};
|
||||
};
|
|
@ -0,0 +1,90 @@
|
|||
'use strict';
|
||||
|
||||
var MissingRefError = require('./error_classes').MissingRef;
|
||||
|
||||
module.exports = compileAsync;
|
||||
|
||||
|
||||
/**
|
||||
* Creates validating function for passed schema with asynchronous loading of missing schemas.
|
||||
* `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema object
|
||||
* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
|
||||
* @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
|
||||
* @return {Promise} promise that resolves with a validating function.
|
||||
*/
|
||||
function compileAsync(schema, meta, callback) {
|
||||
/* eslint no-shadow: 0 */
|
||||
/* global Promise */
|
||||
/* jshint validthis: true */
|
||||
var self = this;
|
||||
if (typeof this._opts.loadSchema != 'function')
|
||||
throw new Error('options.loadSchema should be a function');
|
||||
|
||||
if (typeof meta == 'function') {
|
||||
callback = meta;
|
||||
meta = undefined;
|
||||
}
|
||||
|
||||
var p = loadMetaSchemaOf(schema).then(function () {
|
||||
var schemaObj = self._addSchema(schema, undefined, meta);
|
||||
return schemaObj.validate || _compileAsync(schemaObj);
|
||||
});
|
||||
|
||||
if (callback) {
|
||||
p.then(
|
||||
function(v) { callback(null, v); },
|
||||
callback
|
||||
);
|
||||
}
|
||||
|
||||
return p;
|
||||
|
||||
|
||||
function loadMetaSchemaOf(sch) {
|
||||
var $schema = sch.$schema;
|
||||
return $schema && !self.getSchema($schema)
|
||||
? compileAsync.call(self, { $ref: $schema }, true)
|
||||
: Promise.resolve();
|
||||
}
|
||||
|
||||
|
||||
function _compileAsync(schemaObj) {
|
||||
try { return self._compile(schemaObj); }
|
||||
catch(e) {
|
||||
if (e instanceof MissingRefError) return loadMissingSchema(e);
|
||||
throw e;
|
||||
}
|
||||
|
||||
|
||||
function loadMissingSchema(e) {
|
||||
var ref = e.missingSchema;
|
||||
if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
|
||||
|
||||
var schemaPromise = self._loadingSchemas[ref];
|
||||
if (!schemaPromise) {
|
||||
schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
|
||||
schemaPromise.then(removePromise, removePromise);
|
||||
}
|
||||
|
||||
return schemaPromise.then(function (sch) {
|
||||
if (!added(ref)) {
|
||||
return loadMetaSchemaOf(sch).then(function () {
|
||||
if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
|
||||
});
|
||||
}
|
||||
}).then(function() {
|
||||
return _compileAsync(schemaObj);
|
||||
});
|
||||
|
||||
function removePromise() {
|
||||
delete self._loadingSchemas[ref];
|
||||
}
|
||||
|
||||
function added(ref) {
|
||||
return self._refs[ref] || self._schemas[ref];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
'use strict';
|
||||
|
||||
// do NOT remove this file - it would break pre-compiled schemas
|
||||
// https://github.com/ajv-validator/ajv/issues/889
|
||||
module.exports = require('fast-deep-equal');
|
|
@ -0,0 +1,34 @@
|
|||
'use strict';
|
||||
|
||||
var resolve = require('./resolve');
|
||||
|
||||
module.exports = {
|
||||
Validation: errorSubclass(ValidationError),
|
||||
MissingRef: errorSubclass(MissingRefError)
|
||||
};
|
||||
|
||||
|
||||
function ValidationError(errors) {
|
||||
this.message = 'validation failed';
|
||||
this.errors = errors;
|
||||
this.ajv = this.validation = true;
|
||||
}
|
||||
|
||||
|
||||
MissingRefError.message = function (baseId, ref) {
|
||||
return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
|
||||
};
|
||||
|
||||
|
||||
function MissingRefError(baseId, ref, message) {
|
||||
this.message = message || MissingRefError.message(baseId, ref);
|
||||
this.missingRef = resolve.url(baseId, ref);
|
||||
this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
|
||||
}
|
||||
|
||||
|
||||
function errorSubclass(Subclass) {
|
||||
Subclass.prototype = Object.create(Error.prototype);
|
||||
Subclass.prototype.constructor = Subclass;
|
||||
return Subclass;
|
||||
}
|
|
@ -0,0 +1,142 @@
|
|||
'use strict';
|
||||
|
||||
var util = require('./util');
|
||||
|
||||
var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
|
||||
var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31];
|
||||
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
|
||||
var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
|
||||
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
|
||||
var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
|
||||
// uri-template: https://tools.ietf.org/html/rfc6570
|
||||
var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
|
||||
// For the source: https://gist.github.com/dperini/729294
|
||||
// For test cases: https://mathiasbynens.be/demo/url-regex
|
||||
// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
|
||||
// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
|
||||
var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
|
||||
var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
|
||||
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
|
||||
var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
|
||||
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
|
||||
|
||||
|
||||
module.exports = formats;
|
||||
|
||||
function formats(mode) {
|
||||
mode = mode == 'full' ? 'full' : 'fast';
|
||||
return util.copy(formats[mode]);
|
||||
}
|
||||
|
||||
|
||||
formats.fast = {
|
||||
// date: http://tools.ietf.org/html/rfc3339#section-5.6
|
||||
date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
|
||||
// date-time: http://tools.ietf.org/html/rfc3339#section-5.6
|
||||
time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
|
||||
'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
|
||||
// uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
|
||||
uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
|
||||
'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
|
||||
'uri-template': URITEMPLATE,
|
||||
url: URL,
|
||||
// email (sources from jsen validator):
|
||||
// http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
|
||||
// http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
|
||||
email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
|
||||
hostname: HOSTNAME,
|
||||
// optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
|
||||
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
|
||||
// optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
|
||||
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
|
||||
regex: regex,
|
||||
// uuid: http://tools.ietf.org/html/rfc4122
|
||||
uuid: UUID,
|
||||
// JSON-pointer: https://tools.ietf.org/html/rfc6901
|
||||
// uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
|
||||
'json-pointer': JSON_POINTER,
|
||||
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
|
||||
// relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
|
||||
'relative-json-pointer': RELATIVE_JSON_POINTER
|
||||
};
|
||||
|
||||
|
||||
formats.full = {
|
||||
date: date,
|
||||
time: time,
|
||||
'date-time': date_time,
|
||||
uri: uri,
|
||||
'uri-reference': URIREF,
|
||||
'uri-template': URITEMPLATE,
|
||||
url: URL,
|
||||
email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
|
||||
hostname: HOSTNAME,
|
||||
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
|
||||
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
|
||||
regex: regex,
|
||||
uuid: UUID,
|
||||
'json-pointer': JSON_POINTER,
|
||||
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
|
||||
'relative-json-pointer': RELATIVE_JSON_POINTER
|
||||
};
|
||||
|
||||
|
||||
function isLeapYear(year) {
|
||||
// https://tools.ietf.org/html/rfc3339#appendix-C
|
||||
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
||||
}
|
||||
|
||||
|
||||
function date(str) {
|
||||
// full-date from http://tools.ietf.org/html/rfc3339#section-5.6
|
||||
var matches = str.match(DATE);
|
||||
if (!matches) return false;
|
||||
|
||||
var year = +matches[1];
|
||||
var month = +matches[2];
|
||||
var day = +matches[3];
|
||||
|
||||
return month >= 1 && month <= 12 && day >= 1 &&
|
||||
day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
|
||||
}
|
||||
|
||||
|
||||
function time(str, full) {
|
||||
var matches = str.match(TIME);
|
||||
if (!matches) return false;
|
||||
|
||||
var hour = matches[1];
|
||||
var minute = matches[2];
|
||||
var second = matches[3];
|
||||
var timeZone = matches[5];
|
||||
return ((hour <= 23 && minute <= 59 && second <= 59) ||
|
||||
(hour == 23 && minute == 59 && second == 60)) &&
|
||||
(!full || timeZone);
|
||||
}
|
||||
|
||||
|
||||
var DATE_TIME_SEPARATOR = /t|\s/i;
|
||||
function date_time(str) {
|
||||
// http://tools.ietf.org/html/rfc3339#section-5.6
|
||||
var dateTime = str.split(DATE_TIME_SEPARATOR);
|
||||
return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
|
||||
}
|
||||
|
||||
|
||||
var NOT_URI_FRAGMENT = /\/|:/;
|
||||
function uri(str) {
|
||||
// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
|
||||
return NOT_URI_FRAGMENT.test(str) && URI.test(str);
|
||||
}
|
||||
|
||||
|
||||
var Z_ANCHOR = /[^\\]\\Z/;
|
||||
function regex(str) {
|
||||
if (Z_ANCHOR.test(str)) return false;
|
||||
try {
|
||||
new RegExp(str);
|
||||
return true;
|
||||
} catch(e) {
|
||||
return false;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,387 @@
|
|||
'use strict';
|
||||
|
||||
var resolve = require('./resolve')
|
||||
, util = require('./util')
|
||||
, errorClasses = require('./error_classes')
|
||||
, stableStringify = require('fast-json-stable-stringify');
|
||||
|
||||
var validateGenerator = require('../dotjs/validate');
|
||||
|
||||
/**
|
||||
* Functions below are used inside compiled validations function
|
||||
*/
|
||||
|
||||
var ucs2length = util.ucs2length;
|
||||
var equal = require('fast-deep-equal');
|
||||
|
||||
// this error is thrown by async schemas to return validation errors via exception
|
||||
var ValidationError = errorClasses.Validation;
|
||||
|
||||
module.exports = compile;
|
||||
|
||||
|
||||
/**
|
||||
* Compiles schema to validation function
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema object
|
||||
* @param {Object} root object with information about the root schema for this schema
|
||||
* @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
|
||||
* @param {String} baseId base ID for IDs in the schema
|
||||
* @return {Function} validation function
|
||||
*/
|
||||
function compile(schema, root, localRefs, baseId) {
|
||||
/* jshint validthis: true, evil: true */
|
||||
/* eslint no-shadow: 0 */
|
||||
var self = this
|
||||
, opts = this._opts
|
||||
, refVal = [ undefined ]
|
||||
, refs = {}
|
||||
, patterns = []
|
||||
, patternsHash = {}
|
||||
, defaults = []
|
||||
, defaultsHash = {}
|
||||
, customRules = [];
|
||||
|
||||
root = root || { schema: schema, refVal: refVal, refs: refs };
|
||||
|
||||
var c = checkCompiling.call(this, schema, root, baseId);
|
||||
var compilation = this._compilations[c.index];
|
||||
if (c.compiling) return (compilation.callValidate = callValidate);
|
||||
|
||||
var formats = this._formats;
|
||||
var RULES = this.RULES;
|
||||
|
||||
try {
|
||||
var v = localCompile(schema, root, localRefs, baseId);
|
||||
compilation.validate = v;
|
||||
var cv = compilation.callValidate;
|
||||
if (cv) {
|
||||
cv.schema = v.schema;
|
||||
cv.errors = null;
|
||||
cv.refs = v.refs;
|
||||
cv.refVal = v.refVal;
|
||||
cv.root = v.root;
|
||||
cv.$async = v.$async;
|
||||
if (opts.sourceCode) cv.source = v.source;
|
||||
}
|
||||
return v;
|
||||
} finally {
|
||||
endCompiling.call(this, schema, root, baseId);
|
||||
}
|
||||
|
||||
/* @this {*} - custom context, see passContext option */
|
||||
function callValidate() {
|
||||
/* jshint validthis: true */
|
||||
var validate = compilation.validate;
|
||||
var result = validate.apply(this, arguments);
|
||||
callValidate.errors = validate.errors;
|
||||
return result;
|
||||
}
|
||||
|
||||
function localCompile(_schema, _root, localRefs, baseId) {
|
||||
var isRoot = !_root || (_root && _root.schema == _schema);
|
||||
if (_root.schema != root.schema)
|
||||
return compile.call(self, _schema, _root, localRefs, baseId);
|
||||
|
||||
var $async = _schema.$async === true;
|
||||
|
||||
var sourceCode = validateGenerator({
|
||||
isTop: true,
|
||||
schema: _schema,
|
||||
isRoot: isRoot,
|
||||
baseId: baseId,
|
||||
root: _root,
|
||||
schemaPath: '',
|
||||
errSchemaPath: '#',
|
||||
errorPath: '""',
|
||||
MissingRefError: errorClasses.MissingRef,
|
||||
RULES: RULES,
|
||||
validate: validateGenerator,
|
||||
util: util,
|
||||
resolve: resolve,
|
||||
resolveRef: resolveRef,
|
||||
usePattern: usePattern,
|
||||
useDefault: useDefault,
|
||||
useCustomRule: useCustomRule,
|
||||
opts: opts,
|
||||
formats: formats,
|
||||
logger: self.logger,
|
||||
self: self
|
||||
});
|
||||
|
||||
sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
|
||||
+ vars(defaults, defaultCode) + vars(customRules, customRuleCode)
|
||||
+ sourceCode;
|
||||
|
||||
if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
|
||||
// console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
|
||||
var validate;
|
||||
try {
|
||||
var makeValidate = new Function(
|
||||
'self',
|
||||
'RULES',
|
||||
'formats',
|
||||
'root',
|
||||
'refVal',
|
||||
'defaults',
|
||||
'customRules',
|
||||
'equal',
|
||||
'ucs2length',
|
||||
'ValidationError',
|
||||
sourceCode
|
||||
);
|
||||
|
||||
validate = makeValidate(
|
||||
self,
|
||||
RULES,
|
||||
formats,
|
||||
root,
|
||||
refVal,
|
||||
defaults,
|
||||
customRules,
|
||||
equal,
|
||||
ucs2length,
|
||||
ValidationError
|
||||
);
|
||||
|
||||
refVal[0] = validate;
|
||||
} catch(e) {
|
||||
self.logger.error('Error compiling schema, function code:', sourceCode);
|
||||
throw e;
|
||||
}
|
||||
|
||||
validate.schema = _schema;
|
||||
validate.errors = null;
|
||||
validate.refs = refs;
|
||||
validate.refVal = refVal;
|
||||
validate.root = isRoot ? validate : _root;
|
||||
if ($async) validate.$async = true;
|
||||
if (opts.sourceCode === true) {
|
||||
validate.source = {
|
||||
code: sourceCode,
|
||||
patterns: patterns,
|
||||
defaults: defaults
|
||||
};
|
||||
}
|
||||
|
||||
return validate;
|
||||
}
|
||||
|
||||
function resolveRef(baseId, ref, isRoot) {
|
||||
ref = resolve.url(baseId, ref);
|
||||
var refIndex = refs[ref];
|
||||
var _refVal, refCode;
|
||||
if (refIndex !== undefined) {
|
||||
_refVal = refVal[refIndex];
|
||||
refCode = 'refVal[' + refIndex + ']';
|
||||
return resolvedRef(_refVal, refCode);
|
||||
}
|
||||
if (!isRoot && root.refs) {
|
||||
var rootRefId = root.refs[ref];
|
||||
if (rootRefId !== undefined) {
|
||||
_refVal = root.refVal[rootRefId];
|
||||
refCode = addLocalRef(ref, _refVal);
|
||||
return resolvedRef(_refVal, refCode);
|
||||
}
|
||||
}
|
||||
|
||||
refCode = addLocalRef(ref);
|
||||
var v = resolve.call(self, localCompile, root, ref);
|
||||
if (v === undefined) {
|
||||
var localSchema = localRefs && localRefs[ref];
|
||||
if (localSchema) {
|
||||
v = resolve.inlineRef(localSchema, opts.inlineRefs)
|
||||
? localSchema
|
||||
: compile.call(self, localSchema, root, localRefs, baseId);
|
||||
}
|
||||
}
|
||||
|
||||
if (v === undefined) {
|
||||
removeLocalRef(ref);
|
||||
} else {
|
||||
replaceLocalRef(ref, v);
|
||||
return resolvedRef(v, refCode);
|
||||
}
|
||||
}
|
||||
|
||||
function addLocalRef(ref, v) {
|
||||
var refId = refVal.length;
|
||||
refVal[refId] = v;
|
||||
refs[ref] = refId;
|
||||
return 'refVal' + refId;
|
||||
}
|
||||
|
||||
function removeLocalRef(ref) {
|
||||
delete refs[ref];
|
||||
}
|
||||
|
||||
function replaceLocalRef(ref, v) {
|
||||
var refId = refs[ref];
|
||||
refVal[refId] = v;
|
||||
}
|
||||
|
||||
function resolvedRef(refVal, code) {
|
||||
return typeof refVal == 'object' || typeof refVal == 'boolean'
|
||||
? { code: code, schema: refVal, inline: true }
|
||||
: { code: code, $async: refVal && !!refVal.$async };
|
||||
}
|
||||
|
||||
function usePattern(regexStr) {
|
||||
var index = patternsHash[regexStr];
|
||||
if (index === undefined) {
|
||||
index = patternsHash[regexStr] = patterns.length;
|
||||
patterns[index] = regexStr;
|
||||
}
|
||||
return 'pattern' + index;
|
||||
}
|
||||
|
||||
function useDefault(value) {
|
||||
switch (typeof value) {
|
||||
case 'boolean':
|
||||
case 'number':
|
||||
return '' + value;
|
||||
case 'string':
|
||||
return util.toQuotedString(value);
|
||||
case 'object':
|
||||
if (value === null) return 'null';
|
||||
var valueStr = stableStringify(value);
|
||||
var index = defaultsHash[valueStr];
|
||||
if (index === undefined) {
|
||||
index = defaultsHash[valueStr] = defaults.length;
|
||||
defaults[index] = value;
|
||||
}
|
||||
return 'default' + index;
|
||||
}
|
||||
}
|
||||
|
||||
function useCustomRule(rule, schema, parentSchema, it) {
|
||||
if (self._opts.validateSchema !== false) {
|
||||
var deps = rule.definition.dependencies;
|
||||
if (deps && !deps.every(function(keyword) {
|
||||
return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
|
||||
}))
|
||||
throw new Error('parent schema must have all required keywords: ' + deps.join(','));
|
||||
|
||||
var validateSchema = rule.definition.validateSchema;
|
||||
if (validateSchema) {
|
||||
var valid = validateSchema(schema);
|
||||
if (!valid) {
|
||||
var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
|
||||
if (self._opts.validateSchema == 'log') self.logger.error(message);
|
||||
else throw new Error(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var compile = rule.definition.compile
|
||||
, inline = rule.definition.inline
|
||||
, macro = rule.definition.macro;
|
||||
|
||||
var validate;
|
||||
if (compile) {
|
||||
validate = compile.call(self, schema, parentSchema, it);
|
||||
} else if (macro) {
|
||||
validate = macro.call(self, schema, parentSchema, it);
|
||||
if (opts.validateSchema !== false) self.validateSchema(validate, true);
|
||||
} else if (inline) {
|
||||
validate = inline.call(self, it, rule.keyword, schema, parentSchema);
|
||||
} else {
|
||||
validate = rule.definition.validate;
|
||||
if (!validate) return;
|
||||
}
|
||||
|
||||
if (validate === undefined)
|
||||
throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
|
||||
|
||||
var index = customRules.length;
|
||||
customRules[index] = validate;
|
||||
|
||||
return {
|
||||
code: 'customRule' + index,
|
||||
validate: validate
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Checks if the schema is currently compiled
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema to compile
|
||||
* @param {Object} root root object
|
||||
* @param {String} baseId base schema ID
|
||||
* @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
|
||||
*/
|
||||
function checkCompiling(schema, root, baseId) {
|
||||
/* jshint validthis: true */
|
||||
var index = compIndex.call(this, schema, root, baseId);
|
||||
if (index >= 0) return { index: index, compiling: true };
|
||||
index = this._compilations.length;
|
||||
this._compilations[index] = {
|
||||
schema: schema,
|
||||
root: root,
|
||||
baseId: baseId
|
||||
};
|
||||
return { index: index, compiling: false };
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Removes the schema from the currently compiled list
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema to compile
|
||||
* @param {Object} root root object
|
||||
* @param {String} baseId base schema ID
|
||||
*/
|
||||
function endCompiling(schema, root, baseId) {
|
||||
/* jshint validthis: true */
|
||||
var i = compIndex.call(this, schema, root, baseId);
|
||||
if (i >= 0) this._compilations.splice(i, 1);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Index of schema compilation in the currently compiled list
|
||||
* @this Ajv
|
||||
* @param {Object} schema schema to compile
|
||||
* @param {Object} root root object
|
||||
* @param {String} baseId base schema ID
|
||||
* @return {Integer} compilation index
|
||||
*/
|
||||
function compIndex(schema, root, baseId) {
|
||||
/* jshint validthis: true */
|
||||
for (var i=0; i<this._compilations.length; i++) {
|
||||
var c = this._compilations[i];
|
||||
if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
function patternCode(i, patterns) {
|
||||
return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
|
||||
}
|
||||
|
||||
|
||||
function defaultCode(i) {
|
||||
return 'var default' + i + ' = defaults[' + i + '];';
|
||||
}
|
||||
|
||||
|
||||
function refValCode(i, refVal) {
|
||||
return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
|
||||
}
|
||||
|
||||
|
||||
function customRuleCode(i) {
|
||||
return 'var customRule' + i + ' = customRules[' + i + '];';
|
||||
}
|
||||
|
||||
|
||||
function vars(arr, statement) {
|
||||
if (!arr.length) return '';
|
||||
var code = '';
|
||||
for (var i=0; i<arr.length; i++)
|
||||
code += statement(i, arr);
|
||||
return code;
|
||||
}
|
|
@ -0,0 +1,270 @@
|
|||
'use strict';
|
||||
|
||||
var URI = require('uri-js')
|
||||
, equal = require('fast-deep-equal')
|
||||
, util = require('./util')
|
||||
, SchemaObject = require('./schema_obj')
|
||||
, traverse = require('json-schema-traverse');
|
||||
|
||||
module.exports = resolve;
|
||||
|
||||
resolve.normalizeId = normalizeId;
|
||||
resolve.fullPath = getFullPath;
|
||||
resolve.url = resolveUrl;
|
||||
resolve.ids = resolveIds;
|
||||
resolve.inlineRef = inlineRef;
|
||||
resolve.schema = resolveSchema;
|
||||
|
||||
/**
|
||||
* [resolve and compile the references ($ref)]
|
||||
* @this Ajv
|
||||
* @param {Function} compile reference to schema compilation funciton (localCompile)
|
||||
* @param {Object} root object with information about the root schema for the current schema
|
||||
* @param {String} ref reference to resolve
|
||||
* @return {Object|Function} schema object (if the schema can be inlined) or validation function
|
||||
*/
|
||||
function resolve(compile, root, ref) {
|
||||
/* jshint validthis: true */
|
||||
var refVal = this._refs[ref];
|
||||
if (typeof refVal == 'string') {
|
||||
if (this._refs[refVal]) refVal = this._refs[refVal];
|
||||
else return resolve.call(this, compile, root, refVal);
|
||||
}
|
||||
|
||||
refVal = refVal || this._schemas[ref];
|
||||
if (refVal instanceof SchemaObject) {
|
||||
return inlineRef(refVal.schema, this._opts.inlineRefs)
|
||||
? refVal.schema
|
||||
: refVal.validate || this._compile(refVal);
|
||||
}
|
||||
|
||||
var res = resolveSchema.call(this, root, ref);
|
||||
var schema, v, baseId;
|
||||
if (res) {
|
||||
schema = res.schema;
|
||||
root = res.root;
|
||||
baseId = res.baseId;
|
||||
}
|
||||
|
||||
if (schema instanceof SchemaObject) {
|
||||
v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
|
||||
} else if (schema !== undefined) {
|
||||
v = inlineRef(schema, this._opts.inlineRefs)
|
||||
? schema
|
||||
: compile.call(this, schema, root, undefined, baseId);
|
||||
}
|
||||
|
||||
return v;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Resolve schema, its root and baseId
|
||||
* @this Ajv
|
||||
* @param {Object} root root object with properties schema, refVal, refs
|
||||
* @param {String} ref reference to resolve
|
||||
* @return {Object} object with properties schema, root, baseId
|
||||
*/
|
||||
function resolveSchema(root, ref) {
|
||||
/* jshint validthis: true */
|
||||
var p = URI.parse(ref)
|
||||
, refPath = _getFullPath(p)
|
||||
, baseId = getFullPath(this._getId(root.schema));
|
||||
if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
|
||||
var id = normalizeId(refPath);
|
||||
var refVal = this._refs[id];
|
||||
if (typeof refVal == 'string') {
|
||||
return resolveRecursive.call(this, root, refVal, p);
|
||||
} else if (refVal instanceof SchemaObject) {
|
||||
if (!refVal.validate) this._compile(refVal);
|
||||
root = refVal;
|
||||
} else {
|
||||
refVal = this._schemas[id];
|
||||
if (refVal instanceof SchemaObject) {
|
||||
if (!refVal.validate) this._compile(refVal);
|
||||
if (id == normalizeId(ref))
|
||||
return { schema: refVal, root: root, baseId: baseId };
|
||||
root = refVal;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!root.schema) return;
|
||||
baseId = getFullPath(this._getId(root.schema));
|
||||
}
|
||||
return getJsonPointer.call(this, p, baseId, root.schema, root);
|
||||
}
|
||||
|
||||
|
||||
/* @this Ajv */
|
||||
function resolveRecursive(root, ref, parsedRef) {
|
||||
/* jshint validthis: true */
|
||||
var res = resolveSchema.call(this, root, ref);
|
||||
if (res) {
|
||||
var schema = res.schema;
|
||||
var baseId = res.baseId;
|
||||
root = res.root;
|
||||
var id = this._getId(schema);
|
||||
if (id) baseId = resolveUrl(baseId, id);
|
||||
return getJsonPointer.call(this, parsedRef, baseId, schema, root);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
|
||||
/* @this Ajv */
|
||||
function getJsonPointer(parsedRef, baseId, schema, root) {
|
||||
/* jshint validthis: true */
|
||||
parsedRef.fragment = parsedRef.fragment || '';
|
||||
if (parsedRef.fragment.slice(0,1) != '/') return;
|
||||
var parts = parsedRef.fragment.split('/');
|
||||
|
||||
for (var i = 1; i < parts.length; i++) {
|
||||
var part = parts[i];
|
||||
if (part) {
|
||||
part = util.unescapeFragment(part);
|
||||
schema = schema[part];
|
||||
if (schema === undefined) break;
|
||||
var id;
|
||||
if (!PREVENT_SCOPE_CHANGE[part]) {
|
||||
id = this._getId(schema);
|
||||
if (id) baseId = resolveUrl(baseId, id);
|
||||
if (schema.$ref) {
|
||||
var $ref = resolveUrl(baseId, schema.$ref);
|
||||
var res = resolveSchema.call(this, root, $ref);
|
||||
if (res) {
|
||||
schema = res.schema;
|
||||
root = res.root;
|
||||
baseId = res.baseId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (schema !== undefined && schema !== root.schema)
|
||||
return { schema: schema, root: root, baseId: baseId };
|
||||
}
|
||||
|
||||
|
||||
var SIMPLE_INLINED = util.toHash([
|
||||
'type', 'format', 'pattern',
|
||||
'maxLength', 'minLength',
|
||||
'maxProperties', 'minProperties',
|
||||
'maxItems', 'minItems',
|
||||
'maximum', 'minimum',
|
||||
'uniqueItems', 'multipleOf',
|
||||
'required', 'enum'
|
||||
]);
|
||||
function inlineRef(schema, limit) {
|
||||
if (limit === false) return false;
|
||||
if (limit === undefined || limit === true) return checkNoRef(schema);
|
||||
else if (limit) return countKeys(schema) <= limit;
|
||||
}
|
||||
|
||||
|
||||
function checkNoRef(schema) {
|
||||
var item;
|
||||
if (Array.isArray(schema)) {
|
||||
for (var i=0; i<schema.length; i++) {
|
||||
item = schema[i];
|
||||
if (typeof item == 'object' && !checkNoRef(item)) return false;
|
||||
}
|
||||
} else {
|
||||
for (var key in schema) {
|
||||
if (key == '$ref') return false;
|
||||
item = schema[key];
|
||||
if (typeof item == 'object' && !checkNoRef(item)) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
function countKeys(schema) {
|
||||
var count = 0, item;
|
||||
if (Array.isArray(schema)) {
|
||||
for (var i=0; i<schema.length; i++) {
|
||||
item = schema[i];
|
||||
if (typeof item == 'object') count += countKeys(item);
|
||||
if (count == Infinity) return Infinity;
|
||||
}
|
||||
} else {
|
||||
for (var key in schema) {
|
||||
if (key == '$ref') return Infinity;
|
||||
if (SIMPLE_INLINED[key]) {
|
||||
count++;
|
||||
} else {
|
||||
item = schema[key];
|
||||
if (typeof item == 'object') count += countKeys(item) + 1;
|
||||
if (count == Infinity) return Infinity;
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
|
||||
function getFullPath(id, normalize) {
|
||||
if (normalize !== false) id = normalizeId(id);
|
||||
var p = URI.parse(id);
|
||||
return _getFullPath(p);
|
||||
}
|
||||
|
||||
|
||||
function _getFullPath(p) {
|
||||
return URI.serialize(p).split('#')[0] + '#';
|
||||
}
|
||||
|
||||
|
||||
var TRAILING_SLASH_HASH = /#\/?$/;
|
||||
function normalizeId(id) {
|
||||
return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
|
||||
}
|
||||
|
||||
|
||||
function resolveUrl(baseId, id) {
|
||||
id = normalizeId(id);
|
||||
return URI.resolve(baseId, id);
|
||||
}
|
||||
|
||||
|
||||
/* @this Ajv */
|
||||
function resolveIds(schema) {
|
||||
var schemaId = normalizeId(this._getId(schema));
|
||||
var baseIds = {'': schemaId};
|
||||
var fullPaths = {'': getFullPath(schemaId, false)};
|
||||
var localRefs = {};
|
||||
var self = this;
|
||||
|
||||
traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
|
||||
if (jsonPtr === '') return;
|
||||
var id = self._getId(sch);
|
||||
var baseId = baseIds[parentJsonPtr];
|
||||
var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
|
||||
if (keyIndex !== undefined)
|
||||
fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));
|
||||
|
||||
if (typeof id == 'string') {
|
||||
id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
|
||||
|
||||
var refVal = self._refs[id];
|
||||
if (typeof refVal == 'string') refVal = self._refs[refVal];
|
||||
if (refVal && refVal.schema) {
|
||||
if (!equal(sch, refVal.schema))
|
||||
throw new Error('id "' + id + '" resolves to more than one schema');
|
||||
} else if (id != normalizeId(fullPath)) {
|
||||
if (id[0] == '#') {
|
||||
if (localRefs[id] && !equal(sch, localRefs[id]))
|
||||
throw new Error('id "' + id + '" resolves to more than one schema');
|
||||
localRefs[id] = sch;
|
||||
} else {
|
||||
self._refs[id] = fullPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
baseIds[jsonPtr] = baseId;
|
||||
fullPaths[jsonPtr] = fullPath;
|
||||
});
|
||||
|
||||
return localRefs;
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
'use strict';
|
||||
|
||||
var ruleModules = require('../dotjs')
|
||||
, toHash = require('./util').toHash;
|
||||
|
||||
module.exports = function rules() {
|
||||
var RULES = [
|
||||
{ type: 'number',
|
||||
rules: [ { 'maximum': ['exclusiveMaximum'] },
|
||||
{ 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
|
||||
{ type: 'string',
|
||||
rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
|
||||
{ type: 'array',
|
||||
rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] },
|
||||
{ type: 'object',
|
||||
rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
|
||||
{ 'properties': ['additionalProperties', 'patternProperties'] } ] },
|
||||
{ rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] }
|
||||
];
|
||||
|
||||
var ALL = [ 'type', '$comment' ];
|
||||
var KEYWORDS = [
|
||||
'$schema', '$id', 'id', '$data', '$async', 'title',
|
||||
'description', 'default', 'definitions',
|
||||
'examples', 'readOnly', 'writeOnly',
|
||||
'contentMediaType', 'contentEncoding',
|
||||
'additionalItems', 'then', 'else'
|
||||
];
|
||||
var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
|
||||
RULES.all = toHash(ALL);
|
||||
RULES.types = toHash(TYPES);
|
||||
|
||||
RULES.forEach(function (group) {
|
||||
group.rules = group.rules.map(function (keyword) {
|
||||
var implKeywords;
|
||||
if (typeof keyword == 'object') {
|
||||
var key = Object.keys(keyword)[0];
|
||||
implKeywords = keyword[key];
|
||||
keyword = key;
|
||||
implKeywords.forEach(function (k) {
|
||||
ALL.push(k);
|
||||
RULES.all[k] = true;
|
||||
});
|
||||
}
|
||||
ALL.push(keyword);
|
||||
var rule = RULES.all[keyword] = {
|
||||
keyword: keyword,
|
||||
code: ruleModules[keyword],
|
||||
implements: implKeywords
|
||||
};
|
||||
return rule;
|
||||
});
|
||||
|
||||
RULES.all.$comment = {
|
||||
keyword: '$comment',
|
||||
code: ruleModules.$comment
|
||||
};
|
||||
|
||||
if (group.type) RULES.types[group.type] = group;
|
||||
});
|
||||
|
||||
RULES.keywords = toHash(ALL.concat(KEYWORDS));
|
||||
RULES.custom = {};
|
||||
|
||||
return RULES;
|
||||
};
|
|
@ -0,0 +1,9 @@
|
|||
'use strict';
|
||||
|
||||
var util = require('./util');
|
||||
|
||||
module.exports = SchemaObject;
|
||||
|
||||
function SchemaObject(obj) {
|
||||
util.copy(obj, this);
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
'use strict';
|
||||
|
||||
// https://mathiasbynens.be/notes/javascript-encoding
|
||||
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
|
||||
module.exports = function ucs2length(str) {
|
||||
var length = 0
|
||||
, len = str.length
|
||||
, pos = 0
|
||||
, value;
|
||||
while (pos < len) {
|
||||
length++;
|
||||
value = str.charCodeAt(pos++);
|
||||
if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
|
||||
// high surrogate, and there is a next character
|
||||
value = str.charCodeAt(pos);
|
||||
if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
|
||||
}
|
||||
}
|
||||
return length;
|
||||
};
|
|
@ -0,0 +1,239 @@
|
|||
'use strict';
|
||||
|
||||
|
||||
module.exports = {
|
||||
copy: copy,
|
||||
checkDataType: checkDataType,
|
||||
checkDataTypes: checkDataTypes,
|
||||
coerceToTypes: coerceToTypes,
|
||||
toHash: toHash,
|
||||
getProperty: getProperty,
|
||||
escapeQuotes: escapeQuotes,
|
||||
equal: require('fast-deep-equal'),
|
||||
ucs2length: require('./ucs2length'),
|
||||
varOccurences: varOccurences,
|
||||
varReplace: varReplace,
|
||||
schemaHasRules: schemaHasRules,
|
||||
schemaHasRulesExcept: schemaHasRulesExcept,
|
||||
schemaUnknownRules: schemaUnknownRules,
|
||||
toQuotedString: toQuotedString,
|
||||
getPathExpr: getPathExpr,
|
||||
getPath: getPath,
|
||||
getData: getData,
|
||||
unescapeFragment: unescapeFragment,
|
||||
unescapeJsonPointer: unescapeJsonPointer,
|
||||
escapeFragment: escapeFragment,
|
||||
escapeJsonPointer: escapeJsonPointer
|
||||
};
|
||||
|
||||
|
||||
function copy(o, to) {
|
||||
to = to || {};
|
||||
for (var key in o) to[key] = o[key];
|
||||
return to;
|
||||
}
|
||||
|
||||
|
||||
function checkDataType(dataType, data, strictNumbers, negate) {
|
||||
var EQUAL = negate ? ' !== ' : ' === '
|
||||
, AND = negate ? ' || ' : ' && '
|
||||
, OK = negate ? '!' : ''
|
||||
, NOT = negate ? '' : '!';
|
||||
switch (dataType) {
|
||||
case 'null': return data + EQUAL + 'null';
|
||||
case 'array': return OK + 'Array.isArray(' + data + ')';
|
||||
case 'object': return '(' + OK + data + AND +
|
||||
'typeof ' + data + EQUAL + '"object"' + AND +
|
||||
NOT + 'Array.isArray(' + data + '))';
|
||||
case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
|
||||
NOT + '(' + data + ' % 1)' +
|
||||
AND + data + EQUAL + data +
|
||||
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
|
||||
case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' +
|
||||
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
|
||||
default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function checkDataTypes(dataTypes, data, strictNumbers) {
|
||||
switch (dataTypes.length) {
|
||||
case 1: return checkDataType(dataTypes[0], data, strictNumbers, true);
|
||||
default:
|
||||
var code = '';
|
||||
var types = toHash(dataTypes);
|
||||
if (types.array && types.object) {
|
||||
code = types.null ? '(': '(!' + data + ' || ';
|
||||
code += 'typeof ' + data + ' !== "object")';
|
||||
delete types.null;
|
||||
delete types.array;
|
||||
delete types.object;
|
||||
}
|
||||
if (types.number) delete types.integer;
|
||||
for (var t in types)
|
||||
code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true);
|
||||
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
|
||||
function coerceToTypes(optionCoerceTypes, dataTypes) {
|
||||
if (Array.isArray(dataTypes)) {
|
||||
var types = [];
|
||||
for (var i=0; i<dataTypes.length; i++) {
|
||||
var t = dataTypes[i];
|
||||
if (COERCE_TO_TYPES[t]) types[types.length] = t;
|
||||
else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
|
||||
}
|
||||
if (types.length) return types;
|
||||
} else if (COERCE_TO_TYPES[dataTypes]) {
|
||||
return [dataTypes];
|
||||
} else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
|
||||
return ['array'];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function toHash(arr) {
|
||||
var hash = {};
|
||||
for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
|
||||
return hash;
|
||||
}
|
||||
|
||||
|
||||
var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
|
||||
var SINGLE_QUOTE = /'|\\/g;
|
||||
function getProperty(key) {
|
||||
return typeof key == 'number'
|
||||
? '[' + key + ']'
|
||||
: IDENTIFIER.test(key)
|
||||
? '.' + key
|
||||
: "['" + escapeQuotes(key) + "']";
|
||||
}
|
||||
|
||||
|
||||
function escapeQuotes(str) {
|
||||
return str.replace(SINGLE_QUOTE, '\\$&')
|
||||
.replace(/\n/g, '\\n')
|
||||
.replace(/\r/g, '\\r')
|
||||
.replace(/\f/g, '\\f')
|
||||
.replace(/\t/g, '\\t');
|
||||
}
|
||||
|
||||
|
||||
function varOccurences(str, dataVar) {
|
||||
dataVar += '[^0-9]';
|
||||
var matches = str.match(new RegExp(dataVar, 'g'));
|
||||
return matches ? matches.length : 0;
|
||||
}
|
||||
|
||||
|
||||
function varReplace(str, dataVar, expr) {
|
||||
dataVar += '([^0-9])';
|
||||
expr = expr.replace(/\$/g, '$$$$');
|
||||
return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
|
||||
}
|
||||
|
||||
|
||||
function schemaHasRules(schema, rules) {
|
||||
if (typeof schema == 'boolean') return !schema;
|
||||
for (var key in schema) if (rules[key]) return true;
|
||||
}
|
||||
|
||||
|
||||
function schemaHasRulesExcept(schema, rules, exceptKeyword) {
|
||||
if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
|
||||
for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
|
||||
}
|
||||
|
||||
|
||||
function schemaUnknownRules(schema, rules) {
|
||||
if (typeof schema == 'boolean') return;
|
||||
for (var key in schema) if (!rules[key]) return key;
|
||||
}
|
||||
|
||||
|
||||
function toQuotedString(str) {
|
||||
return '\'' + escapeQuotes(str) + '\'';
|
||||
}
|
||||
|
||||
|
||||
function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
|
||||
var path = jsonPointers // false by default
|
||||
? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
|
||||
: (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
|
||||
return joinPaths(currentPath, path);
|
||||
}
|
||||
|
||||
|
||||
function getPath(currentPath, prop, jsonPointers) {
|
||||
var path = jsonPointers // false by default
|
||||
? toQuotedString('/' + escapeJsonPointer(prop))
|
||||
: toQuotedString(getProperty(prop));
|
||||
return joinPaths(currentPath, path);
|
||||
}
|
||||
|
||||
|
||||
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
|
||||
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
|
||||
function getData($data, lvl, paths) {
|
||||
var up, jsonPointer, data, matches;
|
||||
if ($data === '') return 'rootData';
|
||||
if ($data[0] == '/') {
|
||||
if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
|
||||
jsonPointer = $data;
|
||||
data = 'rootData';
|
||||
} else {
|
||||
matches = $data.match(RELATIVE_JSON_POINTER);
|
||||
if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
|
||||
up = +matches[1];
|
||||
jsonPointer = matches[2];
|
||||
if (jsonPointer == '#') {
|
||||
if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
|
||||
return paths[lvl - up];
|
||||
}
|
||||
|
||||
if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
|
||||
data = 'data' + ((lvl - up) || '');
|
||||
if (!jsonPointer) return data;
|
||||
}
|
||||
|
||||
var expr = data;
|
||||
var segments = jsonPointer.split('/');
|
||||
for (var i=0; i<segments.length; i++) {
|
||||
var segment = segments[i];
|
||||
if (segment) {
|
||||
data += getProperty(unescapeJsonPointer(segment));
|
||||
expr += ' && ' + data;
|
||||
}
|
||||
}
|
||||
return expr;
|
||||
}
|
||||
|
||||
|
||||
function joinPaths (a, b) {
|
||||
if (a == '""') return b;
|
||||
return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1');
|
||||
}
|
||||
|
||||
|
||||
function unescapeFragment(str) {
|
||||
return unescapeJsonPointer(decodeURIComponent(str));
|
||||
}
|
||||
|
||||
|
||||
function escapeFragment(str) {
|
||||
return encodeURIComponent(escapeJsonPointer(str));
|
||||
}
|
||||
|
||||
|
||||
function escapeJsonPointer(str) {
|
||||
return str.replace(/~/g, '~0').replace(/\//g, '~1');
|
||||
}
|
||||
|
||||
|
||||
function unescapeJsonPointer(str) {
|
||||
return str.replace(/~1/g, '/').replace(/~0/g, '~');
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
'use strict';
|
||||
|
||||
var KEYWORDS = [
|
||||
'multipleOf',
|
||||
'maximum',
|
||||
'exclusiveMaximum',
|
||||
'minimum',
|
||||
'exclusiveMinimum',
|
||||
'maxLength',
|
||||
'minLength',
|
||||
'pattern',
|
||||
'additionalItems',
|
||||
'maxItems',
|
||||
'minItems',
|
||||
'uniqueItems',
|
||||
'maxProperties',
|
||||
'minProperties',
|
||||
'required',
|
||||
'additionalProperties',
|
||||
'enum',
|
||||
'format',
|
||||
'const'
|
||||
];
|
||||
|
||||
module.exports = function (metaSchema, keywordsJsonPointers) {
|
||||
for (var i=0; i<keywordsJsonPointers.length; i++) {
|
||||
metaSchema = JSON.parse(JSON.stringify(metaSchema));
|
||||
var segments = keywordsJsonPointers[i].split('/');
|
||||
var keywords = metaSchema;
|
||||
var j;
|
||||
for (j=1; j<segments.length; j++)
|
||||
keywords = keywords[segments[j]];
|
||||
|
||||
for (j=0; j<KEYWORDS.length; j++) {
|
||||
var key = KEYWORDS[j];
|
||||
var schema = keywords[key];
|
||||
if (schema) {
|
||||
keywords[key] = {
|
||||
anyOf: [
|
||||
schema,
|
||||
{ $ref: 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
|
||||
]
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return metaSchema;
|
||||
};
|
|
@ -0,0 +1,37 @@
|
|||
'use strict';
|
||||
|
||||
var metaSchema = require('./refs/json-schema-draft-07.json');
|
||||
|
||||
module.exports = {
|
||||
$id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js',
|
||||
definitions: {
|
||||
simpleTypes: metaSchema.definitions.simpleTypes
|
||||
},
|
||||
type: 'object',
|
||||
dependencies: {
|
||||
schema: ['validate'],
|
||||
$data: ['validate'],
|
||||
statements: ['inline'],
|
||||
valid: {not: {required: ['macro']}}
|
||||
},
|
||||
properties: {
|
||||
type: metaSchema.properties.type,
|
||||
schema: {type: 'boolean'},
|
||||
statements: {type: 'boolean'},
|
||||
dependencies: {
|
||||
type: 'array',
|
||||
items: {type: 'string'}
|
||||
},
|
||||
metaSchema: {type: 'object'},
|
||||
modifying: {type: 'boolean'},
|
||||
valid: {type: 'boolean'},
|
||||
$data: {type: 'boolean'},
|
||||
async: {type: 'boolean'},
|
||||
errors: {
|
||||
anyOf: [
|
||||
{type: 'boolean'},
|
||||
{const: 'full'}
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
|
@ -0,0 +1,113 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{## def.setExclusiveLimit:
|
||||
$exclusive = true;
|
||||
$errorKeyword = $exclusiveKeyword;
|
||||
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
|
||||
#}}
|
||||
|
||||
{{
|
||||
var $isMax = $keyword == 'maximum'
|
||||
, $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum'
|
||||
, $schemaExcl = it.schema[$exclusiveKeyword]
|
||||
, $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data
|
||||
, $op = $isMax ? '<' : '>'
|
||||
, $notOp = $isMax ? '>' : '<'
|
||||
, $errorKeyword = undefined;
|
||||
|
||||
if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
|
||||
throw new Error($keyword + ' must be number');
|
||||
}
|
||||
if (!($isDataExcl || $schemaExcl === undefined
|
||||
|| typeof $schemaExcl == 'number'
|
||||
|| typeof $schemaExcl == 'boolean')) {
|
||||
throw new Error($exclusiveKeyword + ' must be number or boolean');
|
||||
}
|
||||
}}
|
||||
|
||||
{{? $isDataExcl }}
|
||||
{{
|
||||
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr)
|
||||
, $exclusive = 'exclusive' + $lvl
|
||||
, $exclType = 'exclType' + $lvl
|
||||
, $exclIsNumber = 'exclIsNumber' + $lvl
|
||||
, $opExpr = 'op' + $lvl
|
||||
, $opStr = '\' + ' + $opExpr + ' + \'';
|
||||
}}
|
||||
var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}};
|
||||
{{ $schemaValueExcl = 'schemaExcl' + $lvl; }}
|
||||
|
||||
var {{=$exclusive}};
|
||||
var {{=$exclType}} = typeof {{=$schemaValueExcl}};
|
||||
if ({{=$exclType}} != 'boolean' && {{=$exclType}} != 'undefined' && {{=$exclType}} != 'number') {
|
||||
{{ var $errorKeyword = $exclusiveKeyword; }}
|
||||
{{# def.error:'_exclusiveLimit' }}
|
||||
} else if ({{# def.$dataNotType:'number' }}
|
||||
{{=$exclType}} == 'number'
|
||||
? (
|
||||
({{=$exclusive}} = {{=$schemaValue}} === undefined || {{=$schemaValueExcl}} {{=$op}}= {{=$schemaValue}})
|
||||
? {{=$data}} {{=$notOp}}= {{=$schemaValueExcl}}
|
||||
: {{=$data}} {{=$notOp}} {{=$schemaValue}}
|
||||
)
|
||||
: (
|
||||
({{=$exclusive}} = {{=$schemaValueExcl}} === true)
|
||||
? {{=$data}} {{=$notOp}}= {{=$schemaValue}}
|
||||
: {{=$data}} {{=$notOp}} {{=$schemaValue}}
|
||||
)
|
||||
|| {{=$data}} !== {{=$data}}) {
|
||||
var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}=';
|
||||
{{
|
||||
if ($schema === undefined) {
|
||||
$errorKeyword = $exclusiveKeyword;
|
||||
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
|
||||
$schemaValue = $schemaValueExcl;
|
||||
$isData = $isDataExcl;
|
||||
}
|
||||
}}
|
||||
{{??}}
|
||||
{{
|
||||
var $exclIsNumber = typeof $schemaExcl == 'number'
|
||||
, $opStr = $op; /*used in error*/
|
||||
}}
|
||||
|
||||
{{? $exclIsNumber && $isData }}
|
||||
{{ var $opExpr = '\'' + $opStr + '\''; /*used in error*/ }}
|
||||
if ({{# def.$dataNotType:'number' }}
|
||||
( {{=$schemaValue}} === undefined
|
||||
|| {{=$schemaExcl}} {{=$op}}= {{=$schemaValue}}
|
||||
? {{=$data}} {{=$notOp}}= {{=$schemaExcl}}
|
||||
: {{=$data}} {{=$notOp}} {{=$schemaValue}} )
|
||||
|| {{=$data}} !== {{=$data}}) {
|
||||
{{??}}
|
||||
{{
|
||||
if ($exclIsNumber && $schema === undefined) {
|
||||
{{# def.setExclusiveLimit }}
|
||||
$schemaValue = $schemaExcl;
|
||||
$notOp += '=';
|
||||
} else {
|
||||
if ($exclIsNumber)
|
||||
$schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
|
||||
|
||||
if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
|
||||
{{# def.setExclusiveLimit }}
|
||||
$notOp += '=';
|
||||
} else {
|
||||
$exclusive = false;
|
||||
$opStr += '=';
|
||||
}
|
||||
}
|
||||
|
||||
var $opExpr = '\'' + $opStr + '\''; /*used in error*/
|
||||
}}
|
||||
|
||||
if ({{# def.$dataNotType:'number' }}
|
||||
{{=$data}} {{=$notOp}} {{=$schemaValue}}
|
||||
|| {{=$data}} !== {{=$data}}) {
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{ $errorKeyword = $errorKeyword || $keyword; }}
|
||||
{{# def.error:'_limit' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
|
@ -0,0 +1,12 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
{{ var $op = $keyword == 'maxItems' ? '>' : '<'; }}
|
||||
if ({{# def.$dataNotType:'number' }} {{=$data}}.length {{=$op}} {{=$schemaValue}}) {
|
||||
{{ var $errorKeyword = $keyword; }}
|
||||
{{# def.error:'_limitItems' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
|
@ -0,0 +1,12 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
{{ var $op = $keyword == 'maxLength' ? '>' : '<'; }}
|
||||
if ({{# def.$dataNotType:'number' }} {{# def.strLength }} {{=$op}} {{=$schemaValue}}) {
|
||||
{{ var $errorKeyword = $keyword; }}
|
||||
{{# def.error:'_limitLength' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
|
@ -0,0 +1,12 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
{{ var $op = $keyword == 'maxProperties' ? '>' : '<'; }}
|
||||
if ({{# def.$dataNotType:'number' }} Object.keys({{=$data}}).length {{=$op}} {{=$schemaValue}}) {
|
||||
{{ var $errorKeyword = $keyword; }}
|
||||
{{# def.error:'_limitProperties' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
|
@ -0,0 +1,32 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
{{
|
||||
var $currentBaseId = $it.baseId
|
||||
, $allSchemasEmpty = true;
|
||||
}}
|
||||
|
||||
{{~ $schema:$sch:$i }}
|
||||
{{? {{# def.nonEmptySchema:$sch }} }}
|
||||
{{
|
||||
$allSchemasEmpty = false;
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
}}
|
||||
|
||||
{{# def.insertSubschemaCode }}
|
||||
|
||||
{{# def.ifResultValid }}
|
||||
{{?}}
|
||||
{{~}}
|
||||
|
||||
{{? $breakOnError }}
|
||||
{{? $allSchemasEmpty }}
|
||||
if (true) {
|
||||
{{??}}
|
||||
{{= $closingBraces.slice(0,-1) }}
|
||||
{{?}}
|
||||
{{?}}
|
|
@ -0,0 +1,46 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
{{
|
||||
var $noEmptySchema = $schema.every(function($sch) {
|
||||
return {{# def.nonEmptySchema:$sch }};
|
||||
});
|
||||
}}
|
||||
{{? $noEmptySchema }}
|
||||
{{ var $currentBaseId = $it.baseId; }}
|
||||
var {{=$errs}} = errors;
|
||||
var {{=$valid}} = false;
|
||||
|
||||
{{# def.setCompositeRule }}
|
||||
|
||||
{{~ $schema:$sch:$i }}
|
||||
{{
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
}}
|
||||
|
||||
{{# def.insertSubschemaCode }}
|
||||
|
||||
{{=$valid}} = {{=$valid}} || {{=$nextValid}};
|
||||
|
||||
if (!{{=$valid}}) {
|
||||
{{ $closingBraces += '}'; }}
|
||||
{{~}}
|
||||
|
||||
{{# def.resetCompositeRule }}
|
||||
|
||||
{{= $closingBraces }}
|
||||
|
||||
if (!{{=$valid}}) {
|
||||
{{# def.extraError:'anyOf' }}
|
||||
} else {
|
||||
{{# def.resetErrors }}
|
||||
{{? it.opts.allErrors }} } {{?}}
|
||||
{{??}}
|
||||
{{? $breakOnError }}
|
||||
if (true) {
|
||||
{{?}}
|
||||
{{?}}
|
|
@ -0,0 +1,51 @@
|
|||
{{## def.coerceType:
|
||||
{{
|
||||
var $dataType = 'dataType' + $lvl
|
||||
, $coerced = 'coerced' + $lvl;
|
||||
}}
|
||||
var {{=$dataType}} = typeof {{=$data}};
|
||||
var {{=$coerced}} = undefined;
|
||||
|
||||
{{? it.opts.coerceTypes == 'array' }}
|
||||
if ({{=$dataType}} == 'object' && Array.isArray({{=$data}}) && {{=$data}}.length == 1) {
|
||||
{{=$data}} = {{=$data}}[0];
|
||||
{{=$dataType}} = typeof {{=$data}};
|
||||
if ({{=it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)}}) {{=$coerced}} = {{=$data}};
|
||||
}
|
||||
{{?}}
|
||||
|
||||
if ({{=$coerced}} !== undefined) ;
|
||||
{{~ $coerceToTypes:$type:$i }}
|
||||
{{? $type == 'string' }}
|
||||
else if ({{=$dataType}} == 'number' || {{=$dataType}} == 'boolean')
|
||||
{{=$coerced}} = '' + {{=$data}};
|
||||
else if ({{=$data}} === null) {{=$coerced}} = '';
|
||||
{{?? $type == 'number' || $type == 'integer' }}
|
||||
else if ({{=$dataType}} == 'boolean' || {{=$data}} === null
|
||||
|| ({{=$dataType}} == 'string' && {{=$data}} && {{=$data}} == +{{=$data}}
|
||||
{{? $type == 'integer' }} && !({{=$data}} % 1){{?}}))
|
||||
{{=$coerced}} = +{{=$data}};
|
||||
{{?? $type == 'boolean' }}
|
||||
else if ({{=$data}} === 'false' || {{=$data}} === 0 || {{=$data}} === null)
|
||||
{{=$coerced}} = false;
|
||||
else if ({{=$data}} === 'true' || {{=$data}} === 1)
|
||||
{{=$coerced}} = true;
|
||||
{{?? $type == 'null' }}
|
||||
else if ({{=$data}} === '' || {{=$data}} === 0 || {{=$data}} === false)
|
||||
{{=$coerced}} = null;
|
||||
{{?? it.opts.coerceTypes == 'array' && $type == 'array' }}
|
||||
else if ({{=$dataType}} == 'string' || {{=$dataType}} == 'number' || {{=$dataType}} == 'boolean' || {{=$data}} == null)
|
||||
{{=$coerced}} = [{{=$data}}];
|
||||
{{?}}
|
||||
{{~}}
|
||||
else {
|
||||
{{# def.error:'type' }}
|
||||
}
|
||||
|
||||
if ({{=$coerced}} !== undefined) {
|
||||
{{# def.setParentData }}
|
||||
{{=$data}} = {{=$coerced}};
|
||||
{{? !$dataLvl }}if ({{=$parentData}} !== undefined){{?}}
|
||||
{{=$parentData}}[{{=$parentDataProperty}}] = {{=$coerced}};
|
||||
}
|
||||
#}}
|
|
@ -0,0 +1,9 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.setupKeyword }}
|
||||
|
||||
{{ var $comment = it.util.toQuotedString($schema); }}
|
||||
{{? it.opts.$comment === true }}
|
||||
console.log({{=$comment}});
|
||||
{{?? typeof it.opts.$comment == 'function' }}
|
||||
self._opts.$comment({{=$comment}}, {{=it.util.toQuotedString($errSchemaPath)}}, validate.root.schema);
|
||||
{{?}}
|
|
@ -0,0 +1,11 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{? !$isData }}
|
||||
var schema{{=$lvl}} = validate.schema{{=$schemaPath}};
|
||||
{{?}}
|
||||
var {{=$valid}} = equal({{=$data}}, schema{{=$lvl}});
|
||||
{{# def.checkError:'const' }}
|
||||
{{? $breakOnError }} else { {{?}}
|
|
@ -0,0 +1,55 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
|
||||
{{
|
||||
var $idx = 'i' + $lvl
|
||||
, $dataNxt = $it.dataLevel = it.dataLevel + 1
|
||||
, $nextData = 'data' + $dataNxt
|
||||
, $currentBaseId = it.baseId
|
||||
, $nonEmptySchema = {{# def.nonEmptySchema:$schema }};
|
||||
}}
|
||||
|
||||
var {{=$errs}} = errors;
|
||||
var {{=$valid}};
|
||||
|
||||
{{? $nonEmptySchema }}
|
||||
{{# def.setCompositeRule }}
|
||||
|
||||
{{
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
}}
|
||||
|
||||
var {{=$nextValid}} = false;
|
||||
|
||||
for (var {{=$idx}} = 0; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) {
|
||||
{{
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
|
||||
var $passData = $data + '[' + $idx + ']';
|
||||
$it.dataPathArr[$dataNxt] = $idx;
|
||||
}}
|
||||
|
||||
{{# def.generateSubschemaCode }}
|
||||
{{# def.optimizeValidate }}
|
||||
|
||||
if ({{=$nextValid}}) break;
|
||||
}
|
||||
|
||||
{{# def.resetCompositeRule }}
|
||||
{{= $closingBraces }}
|
||||
|
||||
if (!{{=$nextValid}}) {
|
||||
{{??}}
|
||||
if ({{=$data}}.length == 0) {
|
||||
{{?}}
|
||||
|
||||
{{# def.error:'contains' }}
|
||||
} else {
|
||||
{{? $nonEmptySchema }}
|
||||
{{# def.resetErrors }}
|
||||
{{?}}
|
||||
{{? it.opts.allErrors }} } {{?}}
|
|
@ -0,0 +1,191 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{
|
||||
var $rule = this
|
||||
, $definition = 'definition' + $lvl
|
||||
, $rDef = $rule.definition
|
||||
, $closingBraces = '';
|
||||
var $validate = $rDef.validate;
|
||||
var $compile, $inline, $macro, $ruleValidate, $validateCode;
|
||||
}}
|
||||
|
||||
{{? $isData && $rDef.$data }}
|
||||
{{
|
||||
$validateCode = 'keywordValidate' + $lvl;
|
||||
var $validateSchema = $rDef.validateSchema;
|
||||
}}
|
||||
var {{=$definition}} = RULES.custom['{{=$keyword}}'].definition;
|
||||
var {{=$validateCode}} = {{=$definition}}.validate;
|
||||
{{??}}
|
||||
{{
|
||||
$ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
|
||||
if (!$ruleValidate) return;
|
||||
$schemaValue = 'validate.schema' + $schemaPath;
|
||||
$validateCode = $ruleValidate.code;
|
||||
$compile = $rDef.compile;
|
||||
$inline = $rDef.inline;
|
||||
$macro = $rDef.macro;
|
||||
}}
|
||||
{{?}}
|
||||
|
||||
{{
|
||||
var $ruleErrs = $validateCode + '.errors'
|
||||
, $i = 'i' + $lvl
|
||||
, $ruleErr = 'ruleErr' + $lvl
|
||||
, $asyncKeyword = $rDef.async;
|
||||
|
||||
if ($asyncKeyword && !it.async)
|
||||
throw new Error('async keyword in sync schema');
|
||||
}}
|
||||
|
||||
|
||||
{{? !($inline || $macro) }}{{=$ruleErrs}} = null;{{?}}
|
||||
var {{=$errs}} = errors;
|
||||
var {{=$valid}};
|
||||
|
||||
{{## def.callRuleValidate:
|
||||
{{=$validateCode}}.call(
|
||||
{{? it.opts.passContext }}this{{??}}self{{?}}
|
||||
{{? $compile || $rDef.schema === false }}
|
||||
, {{=$data}}
|
||||
{{??}}
|
||||
, {{=$schemaValue}}
|
||||
, {{=$data}}
|
||||
, validate.schema{{=it.schemaPath}}
|
||||
{{?}}
|
||||
, {{# def.dataPath }}
|
||||
{{# def.passParentData }}
|
||||
, rootData
|
||||
)
|
||||
#}}
|
||||
|
||||
{{## def.extendErrors:_inline:
|
||||
for (var {{=$i}}={{=$errs}}; {{=$i}}<errors; {{=$i}}++) {
|
||||
var {{=$ruleErr}} = vErrors[{{=$i}}];
|
||||
if ({{=$ruleErr}}.dataPath === undefined)
|
||||
{{=$ruleErr}}.dataPath = (dataPath || '') + {{= it.errorPath }};
|
||||
{{# _inline ? 'if (\{\{=$ruleErr\}\}.schemaPath === undefined) {' : '' }}
|
||||
{{=$ruleErr}}.schemaPath = "{{=$errSchemaPath}}";
|
||||
{{# _inline ? '}' : '' }}
|
||||
{{? it.opts.verbose }}
|
||||
{{=$ruleErr}}.schema = {{=$schemaValue}};
|
||||
{{=$ruleErr}}.data = {{=$data}};
|
||||
{{?}}
|
||||
}
|
||||
#}}
|
||||
|
||||
|
||||
{{? $isData && $rDef.$data }}
|
||||
{{ $closingBraces += '}'; }}
|
||||
if ({{=$schemaValue}} === undefined) {
|
||||
{{=$valid}} = true;
|
||||
} else {
|
||||
{{? $validateSchema }}
|
||||
{{ $closingBraces += '}'; }}
|
||||
{{=$valid}} = {{=$definition}}.validateSchema({{=$schemaValue}});
|
||||
if ({{=$valid}}) {
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{? $inline }}
|
||||
{{? $rDef.statements }}
|
||||
{{= $ruleValidate.validate }}
|
||||
{{??}}
|
||||
{{=$valid}} = {{= $ruleValidate.validate }};
|
||||
{{?}}
|
||||
{{?? $macro }}
|
||||
{{# def.setupNextLevel }}
|
||||
{{
|
||||
$it.schema = $ruleValidate.validate;
|
||||
$it.schemaPath = '';
|
||||
}}
|
||||
{{# def.setCompositeRule }}
|
||||
{{ var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); }}
|
||||
{{# def.resetCompositeRule }}
|
||||
{{= $code }}
|
||||
{{??}}
|
||||
{{# def.beginDefOut}}
|
||||
{{# def.callRuleValidate }}
|
||||
{{# def.storeDefOut:def_callRuleValidate }}
|
||||
|
||||
{{? $rDef.errors === false }}
|
||||
{{=$valid}} = {{? $asyncKeyword }}await {{?}}{{= def_callRuleValidate }};
|
||||
{{??}}
|
||||
{{? $asyncKeyword }}
|
||||
{{ $ruleErrs = 'customErrors' + $lvl; }}
|
||||
var {{=$ruleErrs}} = null;
|
||||
try {
|
||||
{{=$valid}} = await {{= def_callRuleValidate }};
|
||||
} catch (e) {
|
||||
{{=$valid}} = false;
|
||||
if (e instanceof ValidationError) {{=$ruleErrs}} = e.errors;
|
||||
else throw e;
|
||||
}
|
||||
{{??}}
|
||||
{{=$ruleErrs}} = null;
|
||||
{{=$valid}} = {{= def_callRuleValidate }};
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
{{? $rDef.modifying }}
|
||||
if ({{=$parentData}}) {{=$data}} = {{=$parentData}}[{{=$parentDataProperty}}];
|
||||
{{?}}
|
||||
|
||||
{{= $closingBraces }}
|
||||
|
||||
{{## def.notValidationResult:
|
||||
{{? $rDef.valid === undefined }}
|
||||
!{{? $macro }}{{=$nextValid}}{{??}}{{=$valid}}{{?}}
|
||||
{{??}}
|
||||
{{= !$rDef.valid }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
{{? $rDef.valid }}
|
||||
{{? $breakOnError }} if (true) { {{?}}
|
||||
{{??}}
|
||||
if ({{# def.notValidationResult }}) {
|
||||
{{ $errorKeyword = $rule.keyword; }}
|
||||
{{# def.beginDefOut}}
|
||||
{{# def.error:'custom' }}
|
||||
{{# def.storeDefOut:def_customError }}
|
||||
|
||||
{{? $inline }}
|
||||
{{? $rDef.errors }}
|
||||
{{? $rDef.errors != 'full' }}
|
||||
{{# def.extendErrors:true }}
|
||||
{{?}}
|
||||
{{??}}
|
||||
{{? $rDef.errors === false}}
|
||||
{{= def_customError }}
|
||||
{{??}}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{= def_customError }}
|
||||
} else {
|
||||
{{# def.extendErrors:true }}
|
||||
}
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{?? $macro }}
|
||||
{{# def.extraError:'custom' }}
|
||||
{{??}}
|
||||
{{? $rDef.errors === false}}
|
||||
{{= def_customError }}
|
||||
{{??}}
|
||||
if (Array.isArray({{=$ruleErrs}})) {
|
||||
if (vErrors === null) vErrors = {{=$ruleErrs}};
|
||||
else vErrors = vErrors.concat({{=$ruleErrs}});
|
||||
errors = vErrors.length;
|
||||
{{# def.extendErrors:false }}
|
||||
} else {
|
||||
{{= def_customError }}
|
||||
}
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
||||
} {{? $breakOnError }} else { {{?}}
|
||||
{{?}}
|
|
@ -0,0 +1,47 @@
|
|||
{{## def.assignDefault:
|
||||
{{? it.compositeRule }}
|
||||
{{
|
||||
if (it.opts.strictDefaults) {
|
||||
var $defaultMsg = 'default is ignored for: ' + $passData;
|
||||
if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
|
||||
else throw new Error($defaultMsg);
|
||||
}
|
||||
}}
|
||||
{{??}}
|
||||
if ({{=$passData}} === undefined
|
||||
{{? it.opts.useDefaults == 'empty' }}
|
||||
|| {{=$passData}} === null
|
||||
|| {{=$passData}} === ''
|
||||
{{?}}
|
||||
)
|
||||
{{=$passData}} = {{? it.opts.useDefaults == 'shared' }}
|
||||
{{= it.useDefault($sch.default) }}
|
||||
{{??}}
|
||||
{{= JSON.stringify($sch.default) }}
|
||||
{{?}};
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.defaultProperties:
|
||||
{{
|
||||
var $schema = it.schema.properties
|
||||
, $schemaKeys = Object.keys($schema); }}
|
||||
{{~ $schemaKeys:$propertyKey }}
|
||||
{{ var $sch = $schema[$propertyKey]; }}
|
||||
{{? $sch.default !== undefined }}
|
||||
{{ var $passData = $data + it.util.getProperty($propertyKey); }}
|
||||
{{# def.assignDefault }}
|
||||
{{?}}
|
||||
{{~}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.defaultItems:
|
||||
{{~ it.schema.items:$sch:$i }}
|
||||
{{? $sch.default !== undefined }}
|
||||
{{ var $passData = $data + '[' + $i + ']'; }}
|
||||
{{# def.assignDefault }}
|
||||
{{?}}
|
||||
{{~}}
|
||||
#}}
|
|
@ -0,0 +1,203 @@
|
|||
{{## def.setupKeyword:
|
||||
{{
|
||||
var $lvl = it.level;
|
||||
var $dataLvl = it.dataLevel;
|
||||
var $schema = it.schema[$keyword];
|
||||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
|
||||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
|
||||
var $breakOnError = !it.opts.allErrors;
|
||||
var $errorKeyword;
|
||||
|
||||
var $data = 'data' + ($dataLvl || '');
|
||||
var $valid = 'valid' + $lvl;
|
||||
var $errs = 'errs__' + $lvl;
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.setCompositeRule:
|
||||
{{
|
||||
var $wasComposite = it.compositeRule;
|
||||
it.compositeRule = $it.compositeRule = true;
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.resetCompositeRule:
|
||||
{{ it.compositeRule = $it.compositeRule = $wasComposite; }}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.setupNextLevel:
|
||||
{{
|
||||
var $it = it.util.copy(it);
|
||||
var $closingBraces = '';
|
||||
$it.level++;
|
||||
var $nextValid = 'valid' + $it.level;
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.ifValid:
|
||||
{{? $breakOnError }}
|
||||
if ({{=$valid}}) {
|
||||
{{ $closingBraces += '}'; }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.ifResultValid:
|
||||
{{? $breakOnError }}
|
||||
if ({{=$nextValid}}) {
|
||||
{{ $closingBraces += '}'; }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.elseIfValid:
|
||||
{{? $breakOnError }}
|
||||
{{ $closingBraces += '}'; }}
|
||||
else {
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.nonEmptySchema:_schema:
|
||||
(it.opts.strictKeywords
|
||||
? (typeof _schema == 'object' && Object.keys(_schema).length > 0)
|
||||
|| _schema === false
|
||||
: it.util.schemaHasRules(_schema, it.RULES.all))
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.strLength:
|
||||
{{? it.opts.unicode === false }}
|
||||
{{=$data}}.length
|
||||
{{??}}
|
||||
ucs2length({{=$data}})
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.willOptimize:
|
||||
it.util.varOccurences($code, $nextData) < 2
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.generateSubschemaCode:
|
||||
{{
|
||||
var $code = it.validate($it);
|
||||
$it.baseId = $currentBaseId;
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.insertSubschemaCode:
|
||||
{{= it.validate($it) }}
|
||||
{{ $it.baseId = $currentBaseId; }}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def._optimizeValidate:
|
||||
it.util.varReplace($code, $nextData, $passData)
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.optimizeValidate:
|
||||
{{? {{# def.willOptimize}} }}
|
||||
{{= {{# def._optimizeValidate }} }}
|
||||
{{??}}
|
||||
var {{=$nextData}} = {{=$passData}};
|
||||
{{= $code }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.$data:
|
||||
{{
|
||||
var $isData = it.opts.$data && $schema && $schema.$data
|
||||
, $schemaValue;
|
||||
}}
|
||||
{{? $isData }}
|
||||
var schema{{=$lvl}} = {{= it.util.getData($schema.$data, $dataLvl, it.dataPathArr) }};
|
||||
{{ $schemaValue = 'schema' + $lvl; }}
|
||||
{{??}}
|
||||
{{ $schemaValue = $schema; }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.$dataNotType:_type:
|
||||
{{?$isData}} ({{=$schemaValue}} !== undefined && typeof {{=$schemaValue}} != _type) || {{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.check$dataIsArray:
|
||||
if (schema{{=$lvl}} === undefined) {{=$valid}} = true;
|
||||
else if (!Array.isArray(schema{{=$lvl}})) {{=$valid}} = false;
|
||||
else {
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.numberKeyword:
|
||||
{{? !($isData || typeof $schema == 'number') }}
|
||||
{{ throw new Error($keyword + ' must be number'); }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.beginDefOut:
|
||||
{{
|
||||
var $$outStack = $$outStack || [];
|
||||
$$outStack.push(out);
|
||||
out = '';
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.storeDefOut:_variable:
|
||||
{{
|
||||
var _variable = out;
|
||||
out = $$outStack.pop();
|
||||
}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.dataPath:(dataPath || ''){{? it.errorPath != '""'}} + {{= it.errorPath }}{{?}}#}}
|
||||
|
||||
{{## def.setParentData:
|
||||
{{
|
||||
var $parentData = $dataLvl ? 'data' + (($dataLvl-1)||'') : 'parentData'
|
||||
, $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
|
||||
}}
|
||||
#}}
|
||||
|
||||
{{## def.passParentData:
|
||||
{{# def.setParentData }}
|
||||
, {{= $parentData }}
|
||||
, {{= $parentDataProperty }}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.iterateProperties:
|
||||
{{? $ownProperties }}
|
||||
{{=$dataProperties}} = {{=$dataProperties}} || Object.keys({{=$data}});
|
||||
for (var {{=$idx}}=0; {{=$idx}}<{{=$dataProperties}}.length; {{=$idx}}++) {
|
||||
var {{=$key}} = {{=$dataProperties}}[{{=$idx}}];
|
||||
{{??}}
|
||||
for (var {{=$key}} in {{=$data}}) {
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.noPropertyInData:
|
||||
{{=$useData}} === undefined
|
||||
{{? $ownProperties }}
|
||||
|| !{{# def.isOwnProperty }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.isOwnProperty:
|
||||
Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($propertyKey)}}')
|
||||
#}}
|
|
@ -0,0 +1,79 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.missing }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
|
||||
{{## def.propertyInData:
|
||||
{{=$data}}{{= it.util.getProperty($property) }} !== undefined
|
||||
{{? $ownProperties }}
|
||||
&& Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($property)}}')
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{
|
||||
var $schemaDeps = {}
|
||||
, $propertyDeps = {}
|
||||
, $ownProperties = it.opts.ownProperties;
|
||||
|
||||
for ($property in $schema) {
|
||||
if ($property == '__proto__') continue;
|
||||
var $sch = $schema[$property];
|
||||
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
|
||||
$deps[$property] = $sch;
|
||||
}
|
||||
}}
|
||||
|
||||
var {{=$errs}} = errors;
|
||||
|
||||
{{ var $currentErrorPath = it.errorPath; }}
|
||||
|
||||
var missing{{=$lvl}};
|
||||
{{ for (var $property in $propertyDeps) { }}
|
||||
{{ $deps = $propertyDeps[$property]; }}
|
||||
{{? $deps.length }}
|
||||
if ({{# def.propertyInData }}
|
||||
{{? $breakOnError }}
|
||||
&& ({{# def.checkMissingProperty:$deps }})) {
|
||||
{{# def.errorMissingProperty:'dependencies' }}
|
||||
{{??}}
|
||||
) {
|
||||
{{~ $deps:$propertyKey }}
|
||||
{{# def.allErrorsMissingProperty:'dependencies' }}
|
||||
{{~}}
|
||||
{{?}}
|
||||
} {{# def.elseIfValid }}
|
||||
{{?}}
|
||||
{{ } }}
|
||||
|
||||
{{
|
||||
it.errorPath = $currentErrorPath;
|
||||
var $currentBaseId = $it.baseId;
|
||||
}}
|
||||
|
||||
|
||||
{{ for (var $property in $schemaDeps) { }}
|
||||
{{ var $sch = $schemaDeps[$property]; }}
|
||||
{{? {{# def.nonEmptySchema:$sch }} }}
|
||||
{{=$nextValid}} = true;
|
||||
|
||||
if ({{# def.propertyInData }}) {
|
||||
{{
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + it.util.getProperty($property);
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
|
||||
}}
|
||||
|
||||
{{# def.insertSubschemaCode }}
|
||||
}
|
||||
|
||||
{{# def.ifResultValid }}
|
||||
{{?}}
|
||||
{{ } }}
|
||||
|
||||
{{? $breakOnError }}
|
||||
{{= $closingBraces }}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{?}}
|
|
@ -0,0 +1,30 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{
|
||||
var $i = 'i' + $lvl
|
||||
, $vSchema = 'schema' + $lvl;
|
||||
}}
|
||||
|
||||
{{? !$isData }}
|
||||
var {{=$vSchema}} = validate.schema{{=$schemaPath}};
|
||||
{{?}}
|
||||
var {{=$valid}};
|
||||
|
||||
{{?$isData}}{{# def.check$dataIsArray }}{{?}}
|
||||
|
||||
{{=$valid}} = false;
|
||||
|
||||
for (var {{=$i}}=0; {{=$i}}<{{=$vSchema}}.length; {{=$i}}++)
|
||||
if (equal({{=$data}}, {{=$vSchema}}[{{=$i}}])) {
|
||||
{{=$valid}} = true;
|
||||
break;
|
||||
}
|
||||
|
||||
{{? $isData }} } {{?}}
|
||||
|
||||
{{# def.checkError:'enum' }}
|
||||
|
||||
{{? $breakOnError }} else { {{?}}
|
|
@ -0,0 +1,194 @@
|
|||
{{# def.definitions }}
|
||||
|
||||
{{## def._error:_rule:
|
||||
{{ 'istanbul ignore else'; }}
|
||||
{{? it.createErrors !== false }}
|
||||
{
|
||||
keyword: '{{= $errorKeyword || _rule }}'
|
||||
, dataPath: (dataPath || '') + {{= it.errorPath }}
|
||||
, schemaPath: {{=it.util.toQuotedString($errSchemaPath)}}
|
||||
, params: {{# def._errorParams[_rule] }}
|
||||
{{? it.opts.messages !== false }}
|
||||
, message: {{# def._errorMessages[_rule] }}
|
||||
{{?}}
|
||||
{{? it.opts.verbose }}
|
||||
, schema: {{# def._errorSchemas[_rule] }}
|
||||
, parentSchema: validate.schema{{=it.schemaPath}}
|
||||
, data: {{=$data}}
|
||||
{{?}}
|
||||
}
|
||||
{{??}}
|
||||
{}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def._addError:_rule:
|
||||
if (vErrors === null) vErrors = [err];
|
||||
else vErrors.push(err);
|
||||
errors++;
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.addError:_rule:
|
||||
var err = {{# def._error:_rule }};
|
||||
{{# def._addError:_rule }}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.error:_rule:
|
||||
{{# def.beginDefOut}}
|
||||
{{# def._error:_rule }}
|
||||
{{# def.storeDefOut:__err }}
|
||||
|
||||
{{? !it.compositeRule && $breakOnError }}
|
||||
{{ 'istanbul ignore if'; }}
|
||||
{{? it.async }}
|
||||
throw new ValidationError([{{=__err}}]);
|
||||
{{??}}
|
||||
validate.errors = [{{=__err}}];
|
||||
return false;
|
||||
{{?}}
|
||||
{{??}}
|
||||
var err = {{=__err}};
|
||||
{{# def._addError:_rule }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.extraError:_rule:
|
||||
{{# def.addError:_rule}}
|
||||
{{? !it.compositeRule && $breakOnError }}
|
||||
{{ 'istanbul ignore if'; }}
|
||||
{{? it.async }}
|
||||
throw new ValidationError(vErrors);
|
||||
{{??}}
|
||||
validate.errors = vErrors;
|
||||
return false;
|
||||
{{?}}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.checkError:_rule:
|
||||
if (!{{=$valid}}) {
|
||||
{{# def.error:_rule }}
|
||||
}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.resetErrors:
|
||||
errors = {{=$errs}};
|
||||
if (vErrors !== null) {
|
||||
if ({{=$errs}}) vErrors.length = {{=$errs}};
|
||||
else vErrors = null;
|
||||
}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.concatSchema:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=$schema}}{{?}}#}}
|
||||
{{## def.appendSchema:{{?$isData}}' + {{=$schemaValue}}{{??}}{{=$schemaValue}}'{{?}}#}}
|
||||
{{## def.concatSchemaEQ:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=it.util.escapeQuotes($schema)}}{{?}}#}}
|
||||
|
||||
{{## def._errorMessages = {
|
||||
'false schema': "'boolean schema is false'",
|
||||
$ref: "'can\\\'t resolve reference {{=it.util.escapeQuotes($schema)}}'",
|
||||
additionalItems: "'should NOT have more than {{=$schema.length}} items'",
|
||||
additionalProperties: "'{{? it.opts._errorDataPathProperty }}is an invalid additional property{{??}}should NOT have additional properties{{?}}'",
|
||||
anyOf: "'should match some schema in anyOf'",
|
||||
const: "'should be equal to constant'",
|
||||
contains: "'should contain a valid item'",
|
||||
dependencies: "'should have {{? $deps.length == 1 }}property {{= it.util.escapeQuotes($deps[0]) }}{{??}}properties {{= it.util.escapeQuotes($deps.join(\", \")) }}{{?}} when property {{= it.util.escapeQuotes($property) }} is present'",
|
||||
'enum': "'should be equal to one of the allowed values'",
|
||||
format: "'should match format \"{{#def.concatSchemaEQ}}\"'",
|
||||
'if': "'should match \"' + {{=$ifClause}} + '\" schema'",
|
||||
_limit: "'should be {{=$opStr}} {{#def.appendSchema}}",
|
||||
_exclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'",
|
||||
_limitItems: "'should NOT have {{?$keyword=='maxItems'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} items'",
|
||||
_limitLength: "'should NOT be {{?$keyword=='maxLength'}}longer{{??}}shorter{{?}} than {{#def.concatSchema}} characters'",
|
||||
_limitProperties:"'should NOT have {{?$keyword=='maxProperties'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} properties'",
|
||||
multipleOf: "'should be multiple of {{#def.appendSchema}}",
|
||||
not: "'should NOT be valid'",
|
||||
oneOf: "'should match exactly one schema in oneOf'",
|
||||
pattern: "'should match pattern \"{{#def.concatSchemaEQ}}\"'",
|
||||
propertyNames: "'property name \\'{{=$invalidName}}\\' is invalid'",
|
||||
required: "'{{? it.opts._errorDataPathProperty }}is a required property{{??}}should have required property \\'{{=$missingProperty}}\\'{{?}}'",
|
||||
type: "'should be {{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}'",
|
||||
uniqueItems: "'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)'",
|
||||
custom: "'should pass \"{{=$rule.keyword}}\" keyword validation'",
|
||||
patternRequired: "'should have property matching pattern \\'{{=$missingPattern}}\\''",
|
||||
switch: "'should pass \"switch\" keyword validation'",
|
||||
_formatLimit: "'should be {{=$opStr}} \"{{#def.concatSchemaEQ}}\"'",
|
||||
_formatExclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'"
|
||||
} #}}
|
||||
|
||||
|
||||
{{## def.schemaRefOrVal: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=$schema}}{{?}} #}}
|
||||
{{## def.schemaRefOrQS: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}}
|
||||
|
||||
{{## def._errorSchemas = {
|
||||
'false schema': "false",
|
||||
$ref: "{{=it.util.toQuotedString($schema)}}",
|
||||
additionalItems: "false",
|
||||
additionalProperties: "false",
|
||||
anyOf: "validate.schema{{=$schemaPath}}",
|
||||
const: "validate.schema{{=$schemaPath}}",
|
||||
contains: "validate.schema{{=$schemaPath}}",
|
||||
dependencies: "validate.schema{{=$schemaPath}}",
|
||||
'enum': "validate.schema{{=$schemaPath}}",
|
||||
format: "{{#def.schemaRefOrQS}}",
|
||||
'if': "validate.schema{{=$schemaPath}}",
|
||||
_limit: "{{#def.schemaRefOrVal}}",
|
||||
_exclusiveLimit: "validate.schema{{=$schemaPath}}",
|
||||
_limitItems: "{{#def.schemaRefOrVal}}",
|
||||
_limitLength: "{{#def.schemaRefOrVal}}",
|
||||
_limitProperties:"{{#def.schemaRefOrVal}}",
|
||||
multipleOf: "{{#def.schemaRefOrVal}}",
|
||||
not: "validate.schema{{=$schemaPath}}",
|
||||
oneOf: "validate.schema{{=$schemaPath}}",
|
||||
pattern: "{{#def.schemaRefOrQS}}",
|
||||
propertyNames: "validate.schema{{=$schemaPath}}",
|
||||
required: "validate.schema{{=$schemaPath}}",
|
||||
type: "validate.schema{{=$schemaPath}}",
|
||||
uniqueItems: "{{#def.schemaRefOrVal}}",
|
||||
custom: "validate.schema{{=$schemaPath}}",
|
||||
patternRequired: "validate.schema{{=$schemaPath}}",
|
||||
switch: "validate.schema{{=$schemaPath}}",
|
||||
_formatLimit: "{{#def.schemaRefOrQS}}",
|
||||
_formatExclusiveLimit: "validate.schema{{=$schemaPath}}"
|
||||
} #}}
|
||||
|
||||
|
||||
{{## def.schemaValueQS: {{?$isData}}{{=$schemaValue}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}}
|
||||
|
||||
{{## def._errorParams = {
|
||||
'false schema': "{}",
|
||||
$ref: "{ ref: '{{=it.util.escapeQuotes($schema)}}' }",
|
||||
additionalItems: "{ limit: {{=$schema.length}} }",
|
||||
additionalProperties: "{ additionalProperty: '{{=$additionalProperty}}' }",
|
||||
anyOf: "{}",
|
||||
const: "{ allowedValue: schema{{=$lvl}} }",
|
||||
contains: "{}",
|
||||
dependencies: "{ property: '{{= it.util.escapeQuotes($property) }}', missingProperty: '{{=$missingProperty}}', depsCount: {{=$deps.length}}, deps: '{{= it.util.escapeQuotes($deps.length==1 ? $deps[0] : $deps.join(\", \")) }}' }",
|
||||
'enum': "{ allowedValues: schema{{=$lvl}} }",
|
||||
format: "{ format: {{#def.schemaValueQS}} }",
|
||||
'if': "{ failingKeyword: {{=$ifClause}} }",
|
||||
_limit: "{ comparison: {{=$opExpr}}, limit: {{=$schemaValue}}, exclusive: {{=$exclusive}} }",
|
||||
_exclusiveLimit: "{}",
|
||||
_limitItems: "{ limit: {{=$schemaValue}} }",
|
||||
_limitLength: "{ limit: {{=$schemaValue}} }",
|
||||
_limitProperties:"{ limit: {{=$schemaValue}} }",
|
||||
multipleOf: "{ multipleOf: {{=$schemaValue}} }",
|
||||
not: "{}",
|
||||
oneOf: "{ passingSchemas: {{=$passingSchemas}} }",
|
||||
pattern: "{ pattern: {{#def.schemaValueQS}} }",
|
||||
propertyNames: "{ propertyName: '{{=$invalidName}}' }",
|
||||
required: "{ missingProperty: '{{=$missingProperty}}' }",
|
||||
type: "{ type: '{{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}' }",
|
||||
uniqueItems: "{ i: i, j: j }",
|
||||
custom: "{ keyword: '{{=$rule.keyword}}' }",
|
||||
patternRequired: "{ missingPattern: '{{=$missingPattern}}' }",
|
||||
switch: "{ caseIndex: {{=$caseIndex}} }",
|
||||
_formatLimit: "{ comparison: {{=$opExpr}}, limit: {{#def.schemaValueQS}}, exclusive: {{=$exclusive}} }",
|
||||
_formatExclusiveLimit: "{}"
|
||||
} #}}
|
|
@ -0,0 +1,106 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
|
||||
{{## def.skipFormat:
|
||||
{{? $breakOnError }} if (true) { {{?}}
|
||||
{{ return out; }}
|
||||
#}}
|
||||
|
||||
{{? it.opts.format === false }}{{# def.skipFormat }}{{?}}
|
||||
|
||||
|
||||
{{# def.$data }}
|
||||
|
||||
|
||||
{{## def.$dataCheckFormat:
|
||||
{{# def.$dataNotType:'string' }}
|
||||
({{? $unknownFormats != 'ignore' }}
|
||||
({{=$schemaValue}} && !{{=$format}}
|
||||
{{? $allowUnknown }}
|
||||
&& self._opts.unknownFormats.indexOf({{=$schemaValue}}) == -1
|
||||
{{?}}) ||
|
||||
{{?}}
|
||||
({{=$format}} && {{=$formatType}} == '{{=$ruleType}}'
|
||||
&& !(typeof {{=$format}} == 'function'
|
||||
? {{? it.async}}
|
||||
(async{{=$lvl}} ? await {{=$format}}({{=$data}}) : {{=$format}}({{=$data}}))
|
||||
{{??}}
|
||||
{{=$format}}({{=$data}})
|
||||
{{?}}
|
||||
: {{=$format}}.test({{=$data}}))))
|
||||
#}}
|
||||
|
||||
{{## def.checkFormat:
|
||||
{{
|
||||
var $formatRef = 'formats' + it.util.getProperty($schema);
|
||||
if ($isObject) $formatRef += '.validate';
|
||||
}}
|
||||
{{? typeof $format == 'function' }}
|
||||
{{=$formatRef}}({{=$data}})
|
||||
{{??}}
|
||||
{{=$formatRef}}.test({{=$data}})
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
|
||||
{{
|
||||
var $unknownFormats = it.opts.unknownFormats
|
||||
, $allowUnknown = Array.isArray($unknownFormats);
|
||||
}}
|
||||
|
||||
{{? $isData }}
|
||||
{{
|
||||
var $format = 'format' + $lvl
|
||||
, $isObject = 'isObject' + $lvl
|
||||
, $formatType = 'formatType' + $lvl;
|
||||
}}
|
||||
var {{=$format}} = formats[{{=$schemaValue}}];
|
||||
var {{=$isObject}} = typeof {{=$format}} == 'object'
|
||||
&& !({{=$format}} instanceof RegExp)
|
||||
&& {{=$format}}.validate;
|
||||
var {{=$formatType}} = {{=$isObject}} && {{=$format}}.type || 'string';
|
||||
if ({{=$isObject}}) {
|
||||
{{? it.async}}
|
||||
var async{{=$lvl}} = {{=$format}}.async;
|
||||
{{?}}
|
||||
{{=$format}} = {{=$format}}.validate;
|
||||
}
|
||||
if ({{# def.$dataCheckFormat }}) {
|
||||
{{??}}
|
||||
{{ var $format = it.formats[$schema]; }}
|
||||
{{? !$format }}
|
||||
{{? $unknownFormats == 'ignore' }}
|
||||
{{ it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); }}
|
||||
{{# def.skipFormat }}
|
||||
{{?? $allowUnknown && $unknownFormats.indexOf($schema) >= 0 }}
|
||||
{{# def.skipFormat }}
|
||||
{{??}}
|
||||
{{ throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); }}
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{
|
||||
var $isObject = typeof $format == 'object'
|
||||
&& !($format instanceof RegExp)
|
||||
&& $format.validate;
|
||||
var $formatType = $isObject && $format.type || 'string';
|
||||
if ($isObject) {
|
||||
var $async = $format.async === true;
|
||||
$format = $format.validate;
|
||||
}
|
||||
}}
|
||||
{{? $formatType != $ruleType }}
|
||||
{{# def.skipFormat }}
|
||||
{{?}}
|
||||
{{? $async }}
|
||||
{{
|
||||
if (!it.async) throw new Error('async format in sync schema');
|
||||
var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
|
||||
}}
|
||||
if (!(await {{=$formatRef}}({{=$data}}))) {
|
||||
{{??}}
|
||||
if (!{{# def.checkFormat }}) {
|
||||
{{?}}
|
||||
{{?}}
|
||||
{{# def.error:'format' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
|
@ -0,0 +1,73 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
|
||||
{{## def.validateIfClause:_clause:
|
||||
{{
|
||||
$it.schema = it.schema['_clause'];
|
||||
$it.schemaPath = it.schemaPath + '._clause';
|
||||
$it.errSchemaPath = it.errSchemaPath + '/_clause';
|
||||
}}
|
||||
{{# def.insertSubschemaCode }}
|
||||
{{=$valid}} = {{=$nextValid}};
|
||||
{{? $thenPresent && $elsePresent }}
|
||||
{{ $ifClause = 'ifClause' + $lvl; }}
|
||||
var {{=$ifClause}} = '_clause';
|
||||
{{??}}
|
||||
{{ $ifClause = '\'_clause\''; }}
|
||||
{{?}}
|
||||
#}}
|
||||
|
||||
{{
|
||||
var $thenSch = it.schema['then']
|
||||
, $elseSch = it.schema['else']
|
||||
, $thenPresent = $thenSch !== undefined && {{# def.nonEmptySchema:$thenSch }}
|
||||
, $elsePresent = $elseSch !== undefined && {{# def.nonEmptySchema:$elseSch }}
|
||||
, $currentBaseId = $it.baseId;
|
||||
}}
|
||||
|
||||
{{? $thenPresent || $elsePresent }}
|
||||
{{
|
||||
var $ifClause;
|
||||
$it.createErrors = false;
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
}}
|
||||
var {{=$errs}} = errors;
|
||||
var {{=$valid}} = true;
|
||||
|
||||
{{# def.setCompositeRule }}
|
||||
{{# def.insertSubschemaCode }}
|
||||
{{ $it.createErrors = true; }}
|
||||
{{# def.resetErrors }}
|
||||
{{# def.resetCompositeRule }}
|
||||
|
||||
{{? $thenPresent }}
|
||||
if ({{=$nextValid}}) {
|
||||
{{# def.validateIfClause:then }}
|
||||
}
|
||||
{{? $elsePresent }}
|
||||
else {
|
||||
{{?}}
|
||||
{{??}}
|
||||
if (!{{=$nextValid}}) {
|
||||
{{?}}
|
||||
|
||||
{{? $elsePresent }}
|
||||
{{# def.validateIfClause:else }}
|
||||
}
|
||||
{{?}}
|
||||
|
||||
if (!{{=$valid}}) {
|
||||
{{# def.extraError:'if' }}
|
||||
}
|
||||
{{? $breakOnError }} else { {{?}}
|
||||
{{??}}
|
||||
{{? $breakOnError }}
|
||||
if (true) {
|
||||
{{?}}
|
||||
{{?}}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
|
||||
{{## def.validateItems:startFrom:
|
||||
for (var {{=$idx}} = {{=startFrom}}; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) {
|
||||
{{
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
|
||||
var $passData = $data + '[' + $idx + ']';
|
||||
$it.dataPathArr[$dataNxt] = $idx;
|
||||
}}
|
||||
|
||||
{{# def.generateSubschemaCode }}
|
||||
{{# def.optimizeValidate }}
|
||||
|
||||
{{? $breakOnError }}
|
||||
if (!{{=$nextValid}}) break;
|
||||
{{?}}
|
||||
}
|
||||
#}}
|
||||
|
||||
{{
|
||||
var $idx = 'i' + $lvl
|
||||
, $dataNxt = $it.dataLevel = it.dataLevel + 1
|
||||
, $nextData = 'data' + $dataNxt
|
||||
, $currentBaseId = it.baseId;
|
||||
}}
|
||||
|
||||
var {{=$errs}} = errors;
|
||||
var {{=$valid}};
|
||||
|
||||
{{? Array.isArray($schema) }}
|
||||
{{ /* 'items' is an array of schemas */}}
|
||||
{{ var $additionalItems = it.schema.additionalItems; }}
|
||||
{{? $additionalItems === false }}
|
||||
{{=$valid}} = {{=$data}}.length <= {{= $schema.length }};
|
||||
{{
|
||||
var $currErrSchemaPath = $errSchemaPath;
|
||||
$errSchemaPath = it.errSchemaPath + '/additionalItems';
|
||||
}}
|
||||
{{# def.checkError:'additionalItems' }}
|
||||
{{ $errSchemaPath = $currErrSchemaPath; }}
|
||||
{{# def.elseIfValid}}
|
||||
{{?}}
|
||||
|
||||
{{~ $schema:$sch:$i }}
|
||||
{{? {{# def.nonEmptySchema:$sch }} }}
|
||||
{{=$nextValid}} = true;
|
||||
|
||||
if ({{=$data}}.length > {{=$i}}) {
|
||||
{{
|
||||
var $passData = $data + '[' + $i + ']';
|
||||
$it.schema = $sch;
|
||||
$it.schemaPath = $schemaPath + '[' + $i + ']';
|
||||
$it.errSchemaPath = $errSchemaPath + '/' + $i;
|
||||
$it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
|
||||
$it.dataPathArr[$dataNxt] = $i;
|
||||
}}
|
||||
|
||||
{{# def.generateSubschemaCode }}
|
||||
{{# def.optimizeValidate }}
|
||||
}
|
||||
|
||||
{{# def.ifResultValid }}
|
||||
{{?}}
|
||||
{{~}}
|
||||
|
||||
{{? typeof $additionalItems == 'object' && {{# def.nonEmptySchema:$additionalItems }} }}
|
||||
{{
|
||||
$it.schema = $additionalItems;
|
||||
$it.schemaPath = it.schemaPath + '.additionalItems';
|
||||
$it.errSchemaPath = it.errSchemaPath + '/additionalItems';
|
||||
}}
|
||||
{{=$nextValid}} = true;
|
||||
|
||||
if ({{=$data}}.length > {{= $schema.length }}) {
|
||||
{{# def.validateItems: $schema.length }}
|
||||
}
|
||||
|
||||
{{# def.ifResultValid }}
|
||||
{{?}}
|
||||
|
||||
{{?? {{# def.nonEmptySchema:$schema }} }}
|
||||
{{ /* 'items' is a single schema */}}
|
||||
{{
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
}}
|
||||
{{# def.validateItems: 0 }}
|
||||
{{?}}
|
||||
|
||||
{{? $breakOnError }}
|
||||
{{= $closingBraces }}
|
||||
if ({{=$errs}} == errors) {
|
||||
{{?}}
|
|
@ -0,0 +1,39 @@
|
|||
{{## def.checkMissingProperty:_properties:
|
||||
{{~ _properties:$propertyKey:$i }}
|
||||
{{?$i}} || {{?}}
|
||||
{{
|
||||
var $prop = it.util.getProperty($propertyKey)
|
||||
, $useData = $data + $prop;
|
||||
}}
|
||||
( ({{# def.noPropertyInData }}) && (missing{{=$lvl}} = {{= it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) }}) )
|
||||
{{~}}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.errorMissingProperty:_error:
|
||||
{{
|
||||
var $propertyPath = 'missing' + $lvl
|
||||
, $missingProperty = '\' + ' + $propertyPath + ' + \'';
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.opts.jsonPointers
|
||||
? it.util.getPathExpr($currentErrorPath, $propertyPath, true)
|
||||
: $currentErrorPath + ' + ' + $propertyPath;
|
||||
}
|
||||
}}
|
||||
{{# def.error:_error }}
|
||||
#}}
|
||||
|
||||
|
||||
{{## def.allErrorsMissingProperty:_error:
|
||||
{{
|
||||
var $prop = it.util.getProperty($propertyKey)
|
||||
, $missingProperty = it.util.escapeQuotes($propertyKey)
|
||||
, $useData = $data + $prop;
|
||||
if (it.opts._errorDataPathProperty) {
|
||||
it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
|
||||
}
|
||||
}}
|
||||
if ({{# def.noPropertyInData }}) {
|
||||
{{# def.addError:_error }}
|
||||
}
|
||||
#}}
|
|
@ -0,0 +1,22 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.$data }}
|
||||
|
||||
{{# def.numberKeyword }}
|
||||
|
||||
var division{{=$lvl}};
|
||||
if ({{?$isData}}
|
||||
{{=$schemaValue}} !== undefined && (
|
||||
typeof {{=$schemaValue}} != 'number' ||
|
||||
{{?}}
|
||||
(division{{=$lvl}} = {{=$data}} / {{=$schemaValue}},
|
||||
{{? it.opts.multipleOfPrecision }}
|
||||
Math.abs(Math.round(division{{=$lvl}}) - division{{=$lvl}}) > 1e-{{=it.opts.multipleOfPrecision}}
|
||||
{{??}}
|
||||
division{{=$lvl}} !== parseInt(division{{=$lvl}})
|
||||
{{?}}
|
||||
)
|
||||
{{?$isData}} ) {{?}} ) {
|
||||
{{# def.error:'multipleOf' }}
|
||||
} {{? $breakOnError }} else { {{?}}
|
|
@ -0,0 +1,43 @@
|
|||
{{# def.definitions }}
|
||||
{{# def.errors }}
|
||||
{{# def.setupKeyword }}
|
||||
{{# def.setupNextLevel }}
|
||||
|
||||
{{? {{# def.nonEmptySchema:$schema }} }}
|
||||
{{
|
||||
$it.schema = $schema;
|
||||
$it.schemaPath = $schemaPath;
|
||||
$it.errSchemaPath = $errSchemaPath;
|
||||
}}
|
||||
|
||||
var {{=$errs}} = errors;
|
||||
|
||||
{{# def.setCompositeRule }}
|
||||
|
||||
{{
|
||||
$it.createErrors = false;
|
||||
var $allErrorsOption;
|
||||
if ($it.opts.allErrors) {
|
||||
$allErrorsOption = $it.opts.allErrors;
|
||||
$it.opts.allErrors = false;
|
||||
}
|
||||
}}
|
||||
{{= it.validate($it) }}
|
||||
{{
|
||||
$it.createErrors = true;
|
||||
if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
|
||||
}}
|
||||
|
||||
{{# def.resetCompositeRule }}
|
||||
|
||||
if ({{=$nextValid}}) {
|
||||
{{# def.error:'not' }}
|
||||
} else {
|
||||
{{# def.resetErrors }}
|
||||
{{? it.opts.allErrors }} } {{?}}
|
||||
{{??}}
|
||||
{{# def.addError:'not' }}
|
||||
{{? $breakOnError}}
|
||||
if (false) {
|
||||
{{?}}
|
||||
{{?}}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue