first commit

This commit is contained in:
monjack
2025-06-20 18:01:48 +08:00
commit 6daa6d65c1
24611 changed files with 2512443 additions and 0 deletions

21
app_vue/node_modules/vue-eslint-parser/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016 Toru Nagashima
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.

278
app_vue/node_modules/vue-eslint-parser/README.md generated vendored Normal file
View File

@ -0,0 +1,278 @@
# vue-eslint-parser
[![npm version](https://img.shields.io/npm/v/vue-eslint-parser.svg)](https://www.npmjs.com/package/vue-eslint-parser)
[![Downloads/month](https://img.shields.io/npm/dm/vue-eslint-parser.svg)](http://www.npmtrends.com/vue-eslint-parser)
[![Build Status](https://github.com/vuejs/vue-eslint-parser/workflows/CI/badge.svg)](https://github.com/vuejs/vue-eslint-parser/actions)
[![Coverage Status](https://codecov.io/gh/vuejs/vue-eslint-parser/branch/master/graph/badge.svg)](https://codecov.io/gh/vuejs/vue-eslint-parser)
[![Dependency Status](https://david-dm.org/vuejs/vue-eslint-parser.svg)](https://david-dm.org/vuejs/vue-eslint-parser)
The ESLint custom parser for `.vue` files.
## ⤴️ Motivation
This parser allows us to lint the `<template>` of `.vue` files. We can make mistakes easily on `<template>` if we use complex directives and expressions in the template. This parser and the rules of [eslint-plugin-vue](https://github.com/vuejs/eslint-plugin-vue) would catch some of the mistakes.
## 💿 Installation
```bash
npm install --save-dev eslint vue-eslint-parser
```
- Requires Node.js ^12.22.0, ^14.17.0, 16.0.0 or later.
- Requires ESLint 6.0.0 or later.
## 📖 Usage
1. Write `parser` option into your `.eslintrc.*` file.
2. Use glob patterns or `--ext .vue` CLI option.
```json
{
"extends": "eslint:recommended",
"parser": "vue-eslint-parser"
}
```
```console
$ eslint "src/**/*.{js,vue}"
# or
$ eslint src --ext .vue
```
## 🔧 Options
`parserOptions` has the same properties as what [espree](https://github.com/eslint/espree#usage), the default parser of ESLint, is supporting.
For example:
```json
{
"parser": "vue-eslint-parser",
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2018,
"ecmaFeatures": {
"globalReturn": false,
"impliedStrict": false,
"jsx": false
}
}
}
```
### parserOptions.parser
You can use `parserOptions.parser` property to specify a custom parser to parse `<script>` tags.
Other properties than parser would be given to the specified parser.
For example:
```json
{
"parser": "vue-eslint-parser",
"parserOptions": {
"parser": "@babel/eslint-parser",
"sourceType": "module"
}
}
```
```json
{
"parser": "vue-eslint-parser",
"parserOptions": {
"parser": "@typescript-eslint/parser",
"sourceType": "module"
}
}
```
You can also specify an object and change the parser separately for `<script lang="...">`.
```jsonc
{
"parser": "vue-eslint-parser",
"parserOptions": {
"parser": {
// Script parser for `<script>`
"js": "espree",
// Script parser for `<script lang="ts">`
"ts": "@typescript-eslint/parser",
// Script parser for vue directives (e.g. `v-if=` or `:attribute=`)
// and vue interpolations (e.g. `{{variable}}`).
// If not specified, the parser determined by `<script lang ="...">` is used.
"<template>": "espree",
}
}
}
```
If the `parserOptions.parser` is `false`, the `vue-eslint-parser` skips parsing `<script>` tags completely.
This is useful for people who use the language ESLint community doesn't provide custom parser implementation.
### parserOptions.vueFeatures
You can use `parserOptions.vueFeatures` property to specify how to parse related to Vue features.
For example:
```json
{
"parser": "vue-eslint-parser",
"parserOptions": {
"vueFeatures": {
"filter": true,
"interpolationAsNonHTML": true,
"styleCSSVariableInjection": true,
}
}
}
```
### parserOptions.vueFeatures.filter
You can use `parserOptions.vueFeatures.filter` property to specify whether to parse the Vue2 filter. If you specify `false`, the parser does not parse `|` as a filter.
For example:
```json
{
"parser": "vue-eslint-parser",
"parserOptions": {
"vueFeatures": {
"filter": false
}
}
}
```
If you specify `false`, it can be parsed in the same way as Vue 3.
The following template parses as a bitwise operation.
```vue
<template>
<div>{{ a | b }}</div>
</template>
```
However, the following template that are valid in Vue 2 cannot be parsed.
```vue
<template>
<div>{{ a | valid:filter }}</div>
</template>
```
### parserOptions.vueFeatures.interpolationAsNonHTML
You can use `parserOptions.vueFeatures.interpolationAsNonHTML` property to specify whether to parse the interpolation as HTML. If you specify `true`, the parser handles the interpolation as non-HTML (However, you can use HTML escaping in the interpolation). Default is `true`.
For example:
```json
{
"parser": "vue-eslint-parser",
"parserOptions": {
"vueFeatures": {
"interpolationAsNonHTML": true
}
}
}
```
If you specify `true`, it can be parsed in the same way as Vue 3.
The following template can be parsed well.
```vue
<template>
<div>{{a<b}}</div>
</template>
```
But, it cannot be parsed with Vue 2.
### parserOptions.vueFeatures.styleCSSVariableInjection
If set to `true`, to parse expressions in `v-bind` CSS functions inside `<style>` tags. `v-bind()` is parsed into the `VExpressionContainer` AST node and held in the `VElement` of `<style>`. Default is `true`.
See also to [here](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0043-sfc-style-variables.md).
## 🎇 Usage for custom rules / plugins
- This parser provides `parserServices` to traverse `<template>`.
- `defineTemplateBodyVisitor(templateVisitor, scriptVisitor, options)` ... returns ESLint visitor to traverse `<template>`.
- `getTemplateBodyTokenStore()` ... returns ESLint `TokenStore` to get the tokens of `<template>`.
- `getDocumentFragment()` ... returns the root `VDocumentFragment`.
- `defineCustomBlocksVisitor(context, customParser, rule, scriptVisitor)` ... returns ESLint visitor that parses and traverses the contents of the custom block.
- `defineDocumentVisitor(documentVisitor, options)` ... returns ESLint visitor to traverses the document.
- [ast.md](./docs/ast.md) is `<template>` AST specification.
- [mustache-interpolation-spacing.js](https://github.com/vuejs/eslint-plugin-vue/blob/b434ff99d37f35570fa351681e43ba2cf5746db3/lib/rules/mustache-interpolation-spacing.js) is an example.
### `defineTemplateBodyVisitor(templateBodyVisitor, scriptVisitor, options)`
*Arguments*
- `templateBodyVisitor` ... Event handlers for `<template>`.
- `scriptVisitor` ... Event handlers for `<script>` or scripts. (optional)
- `options` ... Options. (optional)
- `templateBodyTriggerSelector` ... Script AST node selector that triggers the templateBodyVisitor. Default is `"Program:exit"`. (optional)
```ts
import { AST } from "vue-eslint-parser"
export function create(context) {
return context.parserServices.defineTemplateBodyVisitor(
// Event handlers for <template>.
{
VElement(node: AST.VElement): void {
//...
}
},
// Event handlers for <script> or scripts. (optional)
{
Program(node: AST.ESLintProgram): void {
//...
}
},
// Options. (optional)
{
templateBodyTriggerSelector: "Program:exit"
}
)
}
```
## ⚠️ Known Limitations
Some rules make warnings due to the outside of `<script>` tags.
Please disable those rules for `.vue` files as necessary.
- [eol-last](http://eslint.org/docs/rules/eol-last)
- [linebreak-style](http://eslint.org/docs/rules/linebreak-style)
- [max-len](http://eslint.org/docs/rules/max-len)
- [max-lines](http://eslint.org/docs/rules/max-lines)
- [no-trailing-spaces](http://eslint.org/docs/rules/no-trailing-spaces)
- [unicode-bom](http://eslint.org/docs/rules/unicode-bom)
- Other rules which are using the source code text instead of AST might be confused as well.
## 📰 Changelog
- [GitHub Releases](https://github.com/vuejs/vue-eslint-parser/releases)
## 🍻 Contributing
Welcome contributing!
Please use GitHub's Issues/PRs.
If you want to write code, please execute `npm install && npm run setup` after you cloned this repository.
The `npm install` command installs dependencies.
The `npm run setup` command initializes ESLint as git submodules for tests.
### Development Tools
- `npm test` runs tests and measures coverage.
- `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`.
- `npm run coverage` shows the coverage result of `npm test` command with the default browser.
- `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`.
- `npm run lint` runs ESLint.
- `npm run setup` setups submodules to develop.
- `npm run update-fixtures` updates files in `test/fixtures/ast` directory based on `test/fixtures/ast/*/source.vue` files.
- `npm run watch` runs `build`, `update-fixtures`, and tests with `--watch` option.

653
app_vue/node_modules/vue-eslint-parser/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,653 @@
// Generated by dts-bundle v0.7.3
// Dependencies for this module:
// ../eslint-scope
// ../eslint-visitor-keys
declare module 'vue-eslint-parser' {
import * as AST from "vue-eslint-parser/ast";
export function parseForESLint(code: string, parserOptions: any): AST.ESLintExtendedProgram;
export function parse(code: string, options: any): AST.ESLintProgram;
export { AST };
}
declare module 'vue-eslint-parser/ast' {
export * from "vue-eslint-parser/ast/errors";
export * from "vue-eslint-parser/ast/locations";
export * from "vue-eslint-parser/ast/nodes";
export * from "vue-eslint-parser/ast/tokens";
export * from "vue-eslint-parser/ast/traverse";
}
declare module 'vue-eslint-parser/ast/errors' {
export class ParseError extends SyntaxError {
code?: ErrorCode;
index: number;
lineNumber: number;
column: number;
static fromCode(code: ErrorCode, offset: number, line: number, column: number): ParseError;
static normalize(x: any): ParseError | null;
constructor(message: string, code: ErrorCode | undefined, offset: number, line: number, column: number);
static isParseError(x: any): x is ParseError;
}
export type ErrorCode = "abrupt-closing-of-empty-comment" | "absence-of-digits-in-numeric-character-reference" | "cdata-in-html-content" | "character-reference-outside-unicode-range" | "control-character-in-input-stream" | "control-character-reference" | "eof-before-tag-name" | "eof-in-cdata" | "eof-in-comment" | "eof-in-tag" | "incorrectly-closed-comment" | "incorrectly-opened-comment" | "invalid-first-character-of-tag-name" | "missing-attribute-value" | "missing-end-tag-name" | "missing-semicolon-after-character-reference" | "missing-whitespace-between-attributes" | "nested-comment" | "noncharacter-character-reference" | "noncharacter-in-input-stream" | "null-character-reference" | "surrogate-character-reference" | "surrogate-in-input-stream" | "unexpected-character-in-attribute-name" | "unexpected-character-in-unquoted-attribute-value" | "unexpected-equals-sign-before-attribute-name" | "unexpected-null-character" | "unexpected-question-mark-instead-of-tag-name" | "unexpected-solidus-in-tag" | "unknown-named-character-reference" | "end-tag-with-attributes" | "duplicate-attribute" | "end-tag-with-trailing-solidus" | "non-void-html-element-start-tag-with-trailing-solidus" | "x-invalid-end-tag" | "x-invalid-namespace" | "x-missing-interpolation-end";
}
declare module 'vue-eslint-parser/ast/locations' {
export interface Location {
line: number;
column: number;
}
export interface LocationRange {
start: Location;
end: Location;
}
export type Offset = number;
export type OffsetRange = [Offset, Offset];
export interface HasLocation {
range: OffsetRange;
loc: LocationRange;
start?: number;
end?: number;
}
}
declare module 'vue-eslint-parser/ast/nodes' {
import type { ScopeManager } from "eslint-scope";
import type { ParseError } from "vue-eslint-parser/ast/errors";
import type { HasLocation } from "vue-eslint-parser/ast/locations";
import type { Token } from "vue-eslint-parser/ast/tokens";
export interface HasParent {
parent?: Node | null;
}
export type Node = ESLintNode | VNode | VForExpression | VOnExpression | VSlotScopeExpression | VFilterSequenceExpression | VFilter;
export type ESLintNode = ESLintIdentifier | ESLintLiteral | ESLintProgram | ESLintSwitchCase | ESLintCatchClause | ESLintVariableDeclarator | ESLintStatement | ESLintExpression | ESLintProperty | ESLintAssignmentProperty | ESLintSuper | ESLintTemplateElement | ESLintSpreadElement | ESLintPattern | ESLintClassBody | ESLintMethodDefinition | ESLintPropertyDefinition | ESLintStaticBlock | ESLintPrivateIdentifier | ESLintModuleDeclaration | ESLintModuleSpecifier | ESLintImportExpression | ESLintLegacyRestProperty;
export interface ESLintExtendedProgram {
ast: ESLintProgram;
services?: {};
visitorKeys?: {
[type: string]: string[];
};
scopeManager?: ScopeManager;
}
export interface ESLintProgram extends HasLocation, HasParent {
type: "Program";
sourceType: "script" | "module";
body: (ESLintStatement | ESLintModuleDeclaration)[];
templateBody?: VElement & HasConcreteInfo;
tokens?: Token[];
comments?: Token[];
errors?: ParseError[];
}
export type ESLintStatement = ESLintExpressionStatement | ESLintBlockStatement | ESLintEmptyStatement | ESLintDebuggerStatement | ESLintWithStatement | ESLintReturnStatement | ESLintLabeledStatement | ESLintBreakStatement | ESLintContinueStatement | ESLintIfStatement | ESLintSwitchStatement | ESLintThrowStatement | ESLintTryStatement | ESLintWhileStatement | ESLintDoWhileStatement | ESLintForStatement | ESLintForInStatement | ESLintForOfStatement | ESLintDeclaration;
export interface ESLintEmptyStatement extends HasLocation, HasParent {
type: "EmptyStatement";
}
export interface ESLintBlockStatement extends HasLocation, HasParent {
type: "BlockStatement";
body: ESLintStatement[];
}
export interface ESLintExpressionStatement extends HasLocation, HasParent {
type: "ExpressionStatement";
expression: ESLintExpression;
}
export interface ESLintIfStatement extends HasLocation, HasParent {
type: "IfStatement";
test: ESLintExpression;
consequent: ESLintStatement;
alternate: ESLintStatement | null;
}
export interface ESLintSwitchStatement extends HasLocation, HasParent {
type: "SwitchStatement";
discriminant: ESLintExpression;
cases: ESLintSwitchCase[];
}
export interface ESLintSwitchCase extends HasLocation, HasParent {
type: "SwitchCase";
test: ESLintExpression | null;
consequent: ESLintStatement[];
}
export interface ESLintWhileStatement extends HasLocation, HasParent {
type: "WhileStatement";
test: ESLintExpression;
body: ESLintStatement;
}
export interface ESLintDoWhileStatement extends HasLocation, HasParent {
type: "DoWhileStatement";
body: ESLintStatement;
test: ESLintExpression;
}
export interface ESLintForStatement extends HasLocation, HasParent {
type: "ForStatement";
init: ESLintVariableDeclaration | ESLintExpression | null;
test: ESLintExpression | null;
update: ESLintExpression | null;
body: ESLintStatement;
}
export interface ESLintForInStatement extends HasLocation, HasParent {
type: "ForInStatement";
left: ESLintVariableDeclaration | ESLintPattern;
right: ESLintExpression;
body: ESLintStatement;
}
export interface ESLintForOfStatement extends HasLocation, HasParent {
type: "ForOfStatement";
left: ESLintVariableDeclaration | ESLintPattern;
right: ESLintExpression;
body: ESLintStatement;
await: boolean;
}
export interface ESLintLabeledStatement extends HasLocation, HasParent {
type: "LabeledStatement";
label: ESLintIdentifier;
body: ESLintStatement;
}
export interface ESLintBreakStatement extends HasLocation, HasParent {
type: "BreakStatement";
label: ESLintIdentifier | null;
}
export interface ESLintContinueStatement extends HasLocation, HasParent {
type: "ContinueStatement";
label: ESLintIdentifier | null;
}
export interface ESLintReturnStatement extends HasLocation, HasParent {
type: "ReturnStatement";
argument: ESLintExpression | null;
}
export interface ESLintThrowStatement extends HasLocation, HasParent {
type: "ThrowStatement";
argument: ESLintExpression;
}
export interface ESLintTryStatement extends HasLocation, HasParent {
type: "TryStatement";
block: ESLintBlockStatement;
handler: ESLintCatchClause | null;
finalizer: ESLintBlockStatement | null;
}
export interface ESLintCatchClause extends HasLocation, HasParent {
type: "CatchClause";
param: ESLintPattern | null;
body: ESLintBlockStatement;
}
export interface ESLintWithStatement extends HasLocation, HasParent {
type: "WithStatement";
object: ESLintExpression;
body: ESLintStatement;
}
export interface ESLintDebuggerStatement extends HasLocation, HasParent {
type: "DebuggerStatement";
}
export type ESLintDeclaration = ESLintFunctionDeclaration | ESLintVariableDeclaration | ESLintClassDeclaration;
export interface ESLintFunctionDeclaration extends HasLocation, HasParent {
type: "FunctionDeclaration";
async: boolean;
generator: boolean;
id: ESLintIdentifier | null;
params: ESLintPattern[];
body: ESLintBlockStatement;
}
export interface ESLintVariableDeclaration extends HasLocation, HasParent {
type: "VariableDeclaration";
kind: "var" | "let" | "const";
declarations: ESLintVariableDeclarator[];
}
export interface ESLintVariableDeclarator extends HasLocation, HasParent {
type: "VariableDeclarator";
id: ESLintPattern;
init: ESLintExpression | null;
}
export interface ESLintClassDeclaration extends HasLocation, HasParent {
type: "ClassDeclaration";
id: ESLintIdentifier | null;
superClass: ESLintExpression | null;
body: ESLintClassBody;
}
export interface ESLintClassBody extends HasLocation, HasParent {
type: "ClassBody";
body: (ESLintMethodDefinition | ESLintPropertyDefinition | ESLintStaticBlock)[];
}
export interface ESLintMethodDefinition extends HasLocation, HasParent {
type: "MethodDefinition";
kind: "constructor" | "method" | "get" | "set";
computed: boolean;
static: boolean;
key: ESLintExpression | ESLintPrivateIdentifier;
value: ESLintFunctionExpression;
}
export interface ESLintPropertyDefinition extends HasLocation, HasParent {
type: "PropertyDefinition";
computed: boolean;
static: boolean;
key: ESLintExpression | ESLintPrivateIdentifier;
value: ESLintExpression | null;
}
export interface ESLintStaticBlock extends HasLocation, HasParent, Omit<ESLintBlockStatement, "type"> {
type: "StaticBlock";
body: ESLintStatement[];
}
export interface ESLintPrivateIdentifier extends HasLocation, HasParent {
type: "PrivateIdentifier";
name: string;
}
export type ESLintModuleDeclaration = ESLintImportDeclaration | ESLintExportNamedDeclaration | ESLintExportDefaultDeclaration | ESLintExportAllDeclaration;
export type ESLintModuleSpecifier = ESLintImportSpecifier | ESLintImportDefaultSpecifier | ESLintImportNamespaceSpecifier | ESLintExportSpecifier;
export interface ESLintImportDeclaration extends HasLocation, HasParent {
type: "ImportDeclaration";
specifiers: (ESLintImportSpecifier | ESLintImportDefaultSpecifier | ESLintImportNamespaceSpecifier)[];
source: ESLintLiteral;
}
export interface ESLintImportSpecifier extends HasLocation, HasParent {
type: "ImportSpecifier";
imported: ESLintIdentifier | ESLintStringLiteral;
local: ESLintIdentifier;
}
export interface ESLintImportDefaultSpecifier extends HasLocation, HasParent {
type: "ImportDefaultSpecifier";
local: ESLintIdentifier;
}
export interface ESLintImportNamespaceSpecifier extends HasLocation, HasParent {
type: "ImportNamespaceSpecifier";
local: ESLintIdentifier;
}
export interface ESLintImportExpression extends HasLocation, HasParent {
type: "ImportExpression";
source: ESLintExpression;
}
export interface ESLintExportNamedDeclaration extends HasLocation, HasParent {
type: "ExportNamedDeclaration";
declaration?: ESLintDeclaration | null;
specifiers: ESLintExportSpecifier[];
source?: ESLintLiteral | null;
}
export interface ESLintExportSpecifier extends HasLocation, HasParent {
type: "ExportSpecifier";
local: ESLintIdentifier | ESLintStringLiteral;
exported: ESLintIdentifier | ESLintStringLiteral;
}
export interface ESLintExportDefaultDeclaration extends HasLocation, HasParent {
type: "ExportDefaultDeclaration";
declaration: ESLintDeclaration | ESLintExpression;
}
export interface ESLintExportAllDeclaration extends HasLocation, HasParent {
type: "ExportAllDeclaration";
exported: ESLintIdentifier | ESLintStringLiteral | null;
source: ESLintLiteral;
}
export type ESLintExpression = ESLintThisExpression | ESLintArrayExpression | ESLintObjectExpression | ESLintFunctionExpression | ESLintArrowFunctionExpression | ESLintYieldExpression | ESLintLiteral | ESLintUnaryExpression | ESLintUpdateExpression | ESLintBinaryExpression | ESLintAssignmentExpression | ESLintLogicalExpression | ESLintMemberExpression | ESLintConditionalExpression | ESLintCallExpression | ESLintNewExpression | ESLintSequenceExpression | ESLintTemplateLiteral | ESLintTaggedTemplateExpression | ESLintClassExpression | ESLintMetaProperty | ESLintIdentifier | ESLintAwaitExpression | ESLintChainExpression;
export interface ESLintIdentifier extends HasLocation, HasParent {
type: "Identifier";
name: string;
}
interface ESLintLiteralBase extends HasLocation, HasParent {
type: "Literal";
value: string | boolean | null | number | RegExp | bigint;
raw: string;
regex?: {
pattern: string;
flags: string;
};
bigint?: string;
}
export interface ESLintStringLiteral extends ESLintLiteralBase {
value: string;
regex?: undefined;
bigint?: undefined;
}
export interface ESLintBooleanLiteral extends ESLintLiteralBase {
value: boolean;
regex?: undefined;
bigint?: undefined;
}
export interface ESLintNullLiteral extends ESLintLiteralBase {
value: null;
regex?: undefined;
bigint?: undefined;
}
export interface ESLintNumberLiteral extends ESLintLiteralBase {
value: number;
regex?: undefined;
bigint?: undefined;
}
export interface ESLintRegExpLiteral extends ESLintLiteralBase {
value: null | RegExp;
regex: {
pattern: string;
flags: string;
};
bigint?: undefined;
}
export interface ESLintBigIntLiteral extends ESLintLiteralBase {
value: null | bigint;
regex?: undefined;
bigint: string;
}
export type ESLintLiteral = ESLintStringLiteral | ESLintBooleanLiteral | ESLintNullLiteral | ESLintNumberLiteral | ESLintRegExpLiteral | ESLintBigIntLiteral;
export interface ESLintThisExpression extends HasLocation, HasParent {
type: "ThisExpression";
}
export interface ESLintArrayExpression extends HasLocation, HasParent {
type: "ArrayExpression";
elements: (ESLintExpression | ESLintSpreadElement)[];
}
export interface ESLintObjectExpression extends HasLocation, HasParent {
type: "ObjectExpression";
properties: (ESLintProperty | ESLintSpreadElement | ESLintLegacySpreadProperty)[];
}
export interface ESLintProperty extends HasLocation, HasParent {
type: "Property";
kind: "init" | "get" | "set";
method: boolean;
shorthand: boolean;
computed: boolean;
key: ESLintExpression;
value: ESLintExpression | ESLintPattern;
}
export interface ESLintFunctionExpression extends HasLocation, HasParent {
type: "FunctionExpression";
async: boolean;
generator: boolean;
id: ESLintIdentifier | null;
params: ESLintPattern[];
body: ESLintBlockStatement;
}
export interface ESLintArrowFunctionExpression extends HasLocation, HasParent {
type: "ArrowFunctionExpression";
async: boolean;
generator: boolean;
id: ESLintIdentifier | null;
params: ESLintPattern[];
body: ESLintBlockStatement;
}
export interface ESLintSequenceExpression extends HasLocation, HasParent {
type: "SequenceExpression";
expressions: ESLintExpression[];
}
export interface ESLintUnaryExpression extends HasLocation, HasParent {
type: "UnaryExpression";
operator: "-" | "+" | "!" | "~" | "typeof" | "void" | "delete";
prefix: boolean;
argument: ESLintExpression;
}
export interface ESLintBinaryExpression extends HasLocation, HasParent {
type: "BinaryExpression";
operator: "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "**" | "|" | "^" | "&" | "in" | "instanceof";
left: ESLintExpression | ESLintPrivateIdentifier;
right: ESLintExpression;
}
export interface ESLintAssignmentExpression extends HasLocation, HasParent {
type: "AssignmentExpression";
operator: "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "**=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&=" | "||=" | "&&=" | "??=";
left: ESLintPattern;
right: ESLintExpression;
}
export interface ESLintUpdateExpression extends HasLocation, HasParent {
type: "UpdateExpression";
operator: "++" | "--";
argument: ESLintExpression;
prefix: boolean;
}
export interface ESLintLogicalExpression extends HasLocation, HasParent {
type: "LogicalExpression";
operator: "||" | "&&" | "??";
left: ESLintExpression;
right: ESLintExpression;
}
export interface ESLintConditionalExpression extends HasLocation, HasParent {
type: "ConditionalExpression";
test: ESLintExpression;
alternate: ESLintExpression;
consequent: ESLintExpression;
}
export interface ESLintCallExpression extends HasLocation, HasParent {
type: "CallExpression";
optional: boolean;
callee: ESLintExpression | ESLintSuper;
arguments: (ESLintExpression | ESLintSpreadElement)[];
}
export interface ESLintSuper extends HasLocation, HasParent {
type: "Super";
}
export interface ESLintNewExpression extends HasLocation, HasParent {
type: "NewExpression";
callee: ESLintExpression;
arguments: (ESLintExpression | ESLintSpreadElement)[];
}
export interface ESLintMemberExpression extends HasLocation, HasParent {
type: "MemberExpression";
optional: boolean;
computed: boolean;
object: ESLintExpression | ESLintSuper;
property: ESLintExpression | ESLintPrivateIdentifier;
}
export interface ESLintYieldExpression extends HasLocation, HasParent {
type: "YieldExpression";
delegate: boolean;
argument: ESLintExpression | null;
}
export interface ESLintAwaitExpression extends HasLocation, HasParent {
type: "AwaitExpression";
argument: ESLintExpression;
}
export interface ESLintTemplateLiteral extends HasLocation, HasParent {
type: "TemplateLiteral";
quasis: ESLintTemplateElement[];
expressions: ESLintExpression[];
}
export interface ESLintTaggedTemplateExpression extends HasLocation, HasParent {
type: "TaggedTemplateExpression";
tag: ESLintExpression;
quasi: ESLintTemplateLiteral;
}
export interface ESLintTemplateElement extends HasLocation, HasParent {
type: "TemplateElement";
tail: boolean;
value: {
cooked: string | null;
raw: string;
};
}
export interface ESLintClassExpression extends HasLocation, HasParent {
type: "ClassExpression";
id: ESLintIdentifier | null;
superClass: ESLintExpression | null;
body: ESLintClassBody;
}
export interface ESLintMetaProperty extends HasLocation, HasParent {
type: "MetaProperty";
meta: ESLintIdentifier;
property: ESLintIdentifier;
}
export type ESLintPattern = ESLintIdentifier | ESLintObjectPattern | ESLintArrayPattern | ESLintRestElement | ESLintAssignmentPattern | ESLintMemberExpression | ESLintLegacyRestProperty;
export interface ESLintObjectPattern extends HasLocation, HasParent {
type: "ObjectPattern";
properties: (ESLintAssignmentProperty | ESLintRestElement | ESLintLegacyRestProperty)[];
}
export interface ESLintAssignmentProperty extends ESLintProperty {
value: ESLintPattern;
kind: "init";
method: false;
}
export interface ESLintArrayPattern extends HasLocation, HasParent {
type: "ArrayPattern";
elements: ESLintPattern[];
}
export interface ESLintRestElement extends HasLocation, HasParent {
type: "RestElement";
argument: ESLintPattern;
}
export interface ESLintSpreadElement extends HasLocation, HasParent {
type: "SpreadElement";
argument: ESLintExpression;
}
export interface ESLintAssignmentPattern extends HasLocation, HasParent {
type: "AssignmentPattern";
left: ESLintPattern;
right: ESLintExpression;
}
export type ESLintChainElement = ESLintCallExpression | ESLintMemberExpression;
export interface ESLintChainExpression extends HasLocation, HasParent {
type: "ChainExpression";
expression: ESLintChainElement;
}
export interface ESLintLegacyRestProperty extends HasLocation, HasParent {
type: "RestProperty" | "ExperimentalRestProperty";
argument: ESLintPattern;
}
export interface ESLintLegacySpreadProperty extends HasLocation, HasParent {
type: "SpreadProperty" | "ExperimentalSpreadProperty";
argument: ESLintExpression;
}
export const NS: Readonly<{
HTML: "http://www.w3.org/1999/xhtml";
MathML: "http://www.w3.org/1998/Math/MathML";
SVG: "http://www.w3.org/2000/svg";
XLink: "http://www.w3.org/1999/xlink";
XML: "http://www.w3.org/XML/1998/namespace";
XMLNS: "http://www.w3.org/2000/xmlns/";
}>;
export type Namespace = typeof NS.HTML | typeof NS.MathML | typeof NS.SVG | typeof NS.XLink | typeof NS.XML | typeof NS.XMLNS;
export interface Variable {
id: ESLintIdentifier;
kind: "v-for" | "scope";
references: Reference[];
}
export interface Reference {
id: ESLintIdentifier;
mode: "rw" | "r" | "w";
variable: Variable | null;
}
export interface VForExpression extends HasLocation, HasParent {
type: "VForExpression";
parent: VExpressionContainer;
left: ESLintPattern[];
right: ESLintExpression;
}
export interface VOnExpression extends HasLocation, HasParent {
type: "VOnExpression";
parent: VExpressionContainer;
body: ESLintStatement[];
}
export interface VSlotScopeExpression extends HasLocation, HasParent {
type: "VSlotScopeExpression";
parent: VExpressionContainer;
params: ESLintPattern[];
}
export interface VFilterSequenceExpression extends HasLocation, HasParent {
type: "VFilterSequenceExpression";
parent: VExpressionContainer;
expression: ESLintExpression;
filters: VFilter[];
}
export interface VFilter extends HasLocation, HasParent {
type: "VFilter";
parent: VFilterSequenceExpression;
callee: ESLintIdentifier;
arguments: (ESLintExpression | ESLintSpreadElement)[];
}
export type VNode = VAttribute | VDirective | VDirectiveKey | VDocumentFragment | VElement | VEndTag | VExpressionContainer | VIdentifier | VLiteral | VStartTag | VText;
export interface VText extends HasLocation, HasParent {
type: "VText";
parent: VDocumentFragment | VElement;
value: string;
}
export interface VExpressionContainer extends HasLocation, HasParent {
type: "VExpressionContainer";
parent: VDocumentFragment | VElement | VDirective | VDirectiveKey;
expression: ESLintExpression | VFilterSequenceExpression | VForExpression | VOnExpression | VSlotScopeExpression | null;
references: Reference[];
}
export interface VIdentifier extends HasLocation, HasParent {
type: "VIdentifier";
parent: VAttribute | VDirectiveKey;
name: string;
rawName: string;
}
export interface VDirectiveKey extends HasLocation, HasParent {
type: "VDirectiveKey";
parent: VDirective;
name: VIdentifier;
argument: VExpressionContainer | VIdentifier | null;
modifiers: VIdentifier[];
}
export interface VLiteral extends HasLocation, HasParent {
type: "VLiteral";
parent: VAttribute;
value: string;
}
export interface VAttribute extends HasLocation, HasParent {
type: "VAttribute";
parent: VStartTag;
directive: false;
key: VIdentifier;
value: VLiteral | null;
}
export interface VDirective extends HasLocation, HasParent {
type: "VAttribute";
parent: VStartTag;
directive: true;
key: VDirectiveKey;
value: VExpressionContainer | null;
}
export interface VStartTag extends HasLocation, HasParent {
type: "VStartTag";
parent: VElement;
selfClosing: boolean;
attributes: (VAttribute | VDirective)[];
}
export interface VEndTag extends HasLocation, HasParent {
type: "VEndTag";
parent: VElement;
}
export interface HasConcreteInfo {
tokens: Token[];
comments: Token[];
errors: ParseError[];
}
export interface VElement extends HasLocation, HasParent {
type: "VElement";
parent: VDocumentFragment | VElement;
namespace: Namespace;
name: string;
rawName: string;
startTag: VStartTag;
children: (VElement | VText | VExpressionContainer)[];
endTag: VEndTag | null;
variables: Variable[];
}
export interface VDocumentFragment extends HasLocation, HasParent, HasConcreteInfo {
type: "VDocumentFragment";
parent: null;
children: (VElement | VText | VExpressionContainer | VStyleElement)[];
}
export interface VStyleElement extends VElement {
type: "VElement";
name: "style";
style: true;
children: (VText | VExpressionContainer)[];
}
export {};
}
declare module 'vue-eslint-parser/ast/tokens' {
import type { HasLocation } from "vue-eslint-parser/ast/locations";
export interface Token extends HasLocation {
type: string;
value: string;
}
}
declare module 'vue-eslint-parser/ast/traverse' {
import type { VisitorKeys } from "eslint-visitor-keys";
import type { Node } from "vue-eslint-parser/ast/nodes";
export const KEYS: Readonly<{
[type: string]: readonly string[] | undefined;
}>;
function getFallbackKeys(node: Node): string[];
export interface Visitor {
visitorKeys?: VisitorKeys;
enterNode(node: Node, parent: Node | null): void;
leaveNode(node: Node, parent: Node | null): void;
}
export function traverseNodes(node: Node, visitor: Visitor): void;
export { getFallbackKeys };
}

5645
app_vue/node_modules/vue-eslint-parser/index.js generated vendored Normal file

File diff suppressed because one or more lines are too long

1
app_vue/node_modules/vue-eslint-parser/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../semver/bin/semver.js" "$@"
else
exec node "$basedir/../semver/bin/semver.js" "$@"
fi

View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %*

View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
} else {
& "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../semver/bin/semver.js" $args
} else {
& "node$exe" "$basedir/../semver/bin/semver.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

View File

@ -0,0 +1,22 @@
Copyright JS Foundation and other contributors, https://js.foundation
Copyright (C) 2012-2013 Yusuke Suzuki (twitter: @Constellation) and other contributors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.

View File

@ -0,0 +1,70 @@
[![npm version](https://img.shields.io/npm/v/eslint-scope.svg)](https://www.npmjs.com/package/eslint-scope)
[![Downloads](https://img.shields.io/npm/dm/eslint-scope.svg)](https://www.npmjs.com/package/eslint-scope)
[![Build Status](https://github.com/eslint/eslint-scope/workflows/CI/badge.svg)](https://github.com/eslint/eslint-scope/actions)
# ESLint Scope
ESLint Scope is the [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) scope analyzer used in ESLint. It is a fork of [escope](http://github.com/estools/escope).
## Install
```
npm i eslint-scope --save
```
## 📖 Usage
To use in an ESM file:
```js
import * as eslintScope from 'eslint-scope';
```
To use in a CommonJS file:
```js
const eslintScope = require('eslint-scope');
```
Example:
```js
import * as eslintScope from 'eslint-scope';
import * as espree from 'espree';
import estraverse from 'estraverse';
const ast = espree.parse(code, { range: true });
const scopeManager = eslintScope.analyze(ast);
const currentScope = scopeManager.acquire(ast); // global scope
estraverse.traverse(ast, {
enter (node, parent) {
// do stuff
if (/Function/.test(node.type)) {
currentScope = scopeManager.acquire(node); // get current function scope
}
},
leave(node, parent) {
if (/Function/.test(node.type)) {
currentScope = currentScope.upper; // set to parent scope
}
// do stuff
}
});
```
## Contributing
Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/eslint-scope/issues).
## Build Commands
* `npm test` - run all linting and tests
* `npm run lint` - run all linting
## License
ESLint Scope is licensed under a permissive BSD 2-clause license.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,85 @@
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.
*/
import Variable from "./variable.js";
/**
* @constructor Definition
*/
class Definition {
constructor(type, name, node, parent, index, kind) {
/**
* @member {string} Definition#type - type of the occurrence (e.g. "Parameter", "Variable", ...).
*/
this.type = type;
/**
* @member {espree.Identifier} Definition#name - the identifier AST node of the occurrence.
*/
this.name = name;
/**
* @member {espree.Node} Definition#node - the enclosing node of the identifier.
*/
this.node = node;
/**
* @member {espree.Node?} Definition#parent - the enclosing statement node of the identifier.
*/
this.parent = parent;
/**
* @member {number?} Definition#index - the index in the declaration statement.
*/
this.index = index;
/**
* @member {string?} Definition#kind - the kind of the declaration statement.
*/
this.kind = kind;
}
}
/**
* @constructor ParameterDefinition
*/
class ParameterDefinition extends Definition {
constructor(name, node, index, rest) {
super(Variable.Parameter, name, node, null, index, null);
/**
* Whether the parameter definition is a part of a rest parameter.
* @member {boolean} ParameterDefinition#rest
*/
this.rest = rest;
}
}
export {
ParameterDefinition,
Definition
};
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@ -0,0 +1,172 @@
/*
Copyright (C) 2012-2014 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2013 Alex Seville <hi@alexanderseville.com>
Copyright (C) 2014 Thiago de Arruda <tpadilha84@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.
*/
/**
* Escope (<a href="http://github.com/estools/escope">escope</a>) is an <a
* href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript</a>
* scope analyzer extracted from the <a
* href="http://github.com/estools/esmangle">esmangle project</a/>.
* <p>
* <em>escope</em> finds lexical scopes in a source program, i.e. areas of that
* program where different occurrences of the same identifier refer to the same
* variable. With each scope the contained variables are collected, and each
* identifier reference in code is linked to its corresponding variable (if
* possible).
* <p>
* <em>escope</em> works on a syntax tree of the parsed source code which has
* to adhere to the <a
* href="https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API">
* Mozilla Parser API</a>. E.g. <a href="https://github.com/eslint/espree">espree</a> is a parser
* that produces such syntax trees.
* <p>
* The main interface is the {@link analyze} function.
* @module escope
*/
/* eslint no-underscore-dangle: ["error", { "allow": ["__currentScope"] }] */
import assert from "assert";
import ScopeManager from "./scope-manager.js";
import Referencer from "./referencer.js";
import Reference from "./reference.js";
import Variable from "./variable.js";
import eslintScopeVersion from "./version.js";
/**
* Set the default options
* @returns {Object} options
*/
function defaultOptions() {
return {
optimistic: false,
directive: false,
nodejsScope: false,
impliedStrict: false,
sourceType: "script", // one of ['script', 'module', 'commonjs']
ecmaVersion: 5,
childVisitorKeys: null,
fallback: "iteration"
};
}
/**
* Preform deep update on option object
* @param {Object} target Options
* @param {Object} override Updates
* @returns {Object} Updated options
*/
function updateDeeply(target, override) {
/**
* Is hash object
* @param {Object} value Test value
* @returns {boolean} Result
*/
function isHashObject(value) {
return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp);
}
for (const key in override) {
if (Object.prototype.hasOwnProperty.call(override, key)) {
const val = override[key];
if (isHashObject(val)) {
if (isHashObject(target[key])) {
updateDeeply(target[key], val);
} else {
target[key] = updateDeeply({}, val);
}
} else {
target[key] = val;
}
}
}
return target;
}
/**
* Main interface function. Takes an Espree syntax tree and returns the
* analyzed scopes.
* @function analyze
* @param {espree.Tree} tree Abstract Syntax Tree
* @param {Object} providedOptions Options that tailor the scope analysis
* @param {boolean} [providedOptions.optimistic=false] the optimistic flag
* @param {boolean} [providedOptions.directive=false] the directive flag
* @param {boolean} [providedOptions.ignoreEval=false] whether to check 'eval()' calls
* @param {boolean} [providedOptions.nodejsScope=false] whether the whole
* script is executed under node.js environment. When enabled, escope adds
* a function scope immediately following the global scope.
* @param {boolean} [providedOptions.impliedStrict=false] implied strict mode
* (if ecmaVersion >= 5).
* @param {string} [providedOptions.sourceType='script'] the source type of the script. one of 'script', 'module', and 'commonjs'
* @param {number} [providedOptions.ecmaVersion=5] which ECMAScript version is considered
* @param {Object} [providedOptions.childVisitorKeys=null] Additional known visitor keys. See [esrecurse](https://github.com/estools/esrecurse)'s the `childVisitorKeys` option.
* @param {string} [providedOptions.fallback='iteration'] A kind of the fallback in order to encounter with unknown node. See [esrecurse](https://github.com/estools/esrecurse)'s the `fallback` option.
* @returns {ScopeManager} ScopeManager
*/
function analyze(tree, providedOptions) {
const options = updateDeeply(defaultOptions(), providedOptions);
const scopeManager = new ScopeManager(options);
const referencer = new Referencer(options, scopeManager);
referencer.visit(tree);
assert(scopeManager.__currentScope === null, "currentScope should be null.");
return scopeManager;
}
export {
/** @name module:escope.version */
eslintScopeVersion as version,
/** @name module:escope.Reference */
Reference,
/** @name module:escope.Variable */
Variable,
/** @name module:escope.ScopeManager */
ScopeManager,
/** @name module:escope.Referencer */
Referencer,
analyze
};
/** @name module:escope.Definition */
export { Definition } from "./definition.js";
/** @name module:escope.PatternVisitor */
export { default as PatternVisitor } from "./pattern-visitor.js";
/** @name module:escope.Scope */
export { Scope } from "./scope.js";
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@ -0,0 +1,153 @@
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.
*/
/* eslint-disable no-undefined */
import estraverse from "estraverse";
import esrecurse from "esrecurse";
const { Syntax } = estraverse;
/**
* Get last array element
* @param {Array} xs array
* @returns {any} Last elment
*/
function getLast(xs) {
return xs[xs.length - 1] || null;
}
class PatternVisitor extends esrecurse.Visitor {
static isPattern(node) {
const nodeType = node.type;
return (
nodeType === Syntax.Identifier ||
nodeType === Syntax.ObjectPattern ||
nodeType === Syntax.ArrayPattern ||
nodeType === Syntax.SpreadElement ||
nodeType === Syntax.RestElement ||
nodeType === Syntax.AssignmentPattern
);
}
constructor(options, rootPattern, callback) {
super(null, options);
this.rootPattern = rootPattern;
this.callback = callback;
this.assignments = [];
this.rightHandNodes = [];
this.restElements = [];
}
Identifier(pattern) {
const lastRestElement = getLast(this.restElements);
this.callback(pattern, {
topLevel: pattern === this.rootPattern,
rest: lastRestElement !== null && lastRestElement !== undefined && lastRestElement.argument === pattern,
assignments: this.assignments
});
}
Property(property) {
// Computed property's key is a right hand node.
if (property.computed) {
this.rightHandNodes.push(property.key);
}
// If it's shorthand, its key is same as its value.
// If it's shorthand and has its default value, its key is same as its value.left (the value is AssignmentPattern).
// If it's not shorthand, the name of new variable is its value's.
this.visit(property.value);
}
ArrayPattern(pattern) {
for (let i = 0, iz = pattern.elements.length; i < iz; ++i) {
const element = pattern.elements[i];
this.visit(element);
}
}
AssignmentPattern(pattern) {
this.assignments.push(pattern);
this.visit(pattern.left);
this.rightHandNodes.push(pattern.right);
this.assignments.pop();
}
RestElement(pattern) {
this.restElements.push(pattern);
this.visit(pattern.argument);
this.restElements.pop();
}
MemberExpression(node) {
// Computed property's key is a right hand node.
if (node.computed) {
this.rightHandNodes.push(node.property);
}
// the object is only read, write to its property.
this.rightHandNodes.push(node.object);
}
//
// ForInStatement.left and AssignmentExpression.left are LeftHandSideExpression.
// By spec, LeftHandSideExpression is Pattern or MemberExpression.
// (see also: https://github.com/estree/estree/pull/20#issuecomment-74584758)
// But espree 2.0 parses to ArrayExpression, ObjectExpression, etc...
//
SpreadElement(node) {
this.visit(node.argument);
}
ArrayExpression(node) {
node.elements.forEach(this.visit, this);
}
AssignmentExpression(node) {
this.assignments.push(node);
this.visit(node.left);
this.rightHandNodes.push(node.right);
this.assignments.pop();
}
CallExpression(node) {
// arguments are right hand nodes.
node.arguments.forEach(a => {
this.rightHandNodes.push(a);
});
this.visit(node.callee);
}
}
export default PatternVisitor;
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@ -0,0 +1,166 @@
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.
*/
const READ = 0x1;
const WRITE = 0x2;
const RW = READ | WRITE;
/**
* A Reference represents a single occurrence of an identifier in code.
* @constructor Reference
*/
class Reference {
constructor(ident, scope, flag, writeExpr, maybeImplicitGlobal, partial, init) {
/**
* Identifier syntax node.
* @member {espreeIdentifier} Reference#identifier
*/
this.identifier = ident;
/**
* Reference to the enclosing Scope.
* @member {Scope} Reference#from
*/
this.from = scope;
/**
* Whether the reference comes from a dynamic scope (such as 'eval',
* 'with', etc.), and may be trapped by dynamic scopes.
* @member {boolean} Reference#tainted
*/
this.tainted = false;
/**
* The variable this reference is resolved with.
* @member {Variable} Reference#resolved
*/
this.resolved = null;
/**
* The read-write mode of the reference. (Value is one of {@link
* Reference.READ}, {@link Reference.RW}, {@link Reference.WRITE}).
* @member {number} Reference#flag
* @private
*/
this.flag = flag;
if (this.isWrite()) {
/**
* If reference is writeable, this is the tree being written to it.
* @member {espreeNode} Reference#writeExpr
*/
this.writeExpr = writeExpr;
/**
* Whether the Reference might refer to a partial value of writeExpr.
* @member {boolean} Reference#partial
*/
this.partial = partial;
/**
* Whether the Reference is to write of initialization.
* @member {boolean} Reference#init
*/
this.init = init;
}
this.__maybeImplicitGlobal = maybeImplicitGlobal;
}
/**
* Whether the reference is static.
* @function Reference#isStatic
* @returns {boolean} static
*/
isStatic() {
return !this.tainted && this.resolved && this.resolved.scope.isStatic();
}
/**
* Whether the reference is writeable.
* @function Reference#isWrite
* @returns {boolean} write
*/
isWrite() {
return !!(this.flag & Reference.WRITE);
}
/**
* Whether the reference is readable.
* @function Reference#isRead
* @returns {boolean} read
*/
isRead() {
return !!(this.flag & Reference.READ);
}
/**
* Whether the reference is read-only.
* @function Reference#isReadOnly
* @returns {boolean} read only
*/
isReadOnly() {
return this.flag === Reference.READ;
}
/**
* Whether the reference is write-only.
* @function Reference#isWriteOnly
* @returns {boolean} write only
*/
isWriteOnly() {
return this.flag === Reference.WRITE;
}
/**
* Whether the reference is read-write.
* @function Reference#isReadWrite
* @returns {boolean} read write
*/
isReadWrite() {
return this.flag === Reference.RW;
}
}
/**
* @constant Reference.READ
* @private
*/
Reference.READ = READ;
/**
* @constant Reference.WRITE
* @private
*/
Reference.WRITE = WRITE;
/**
* @constant Reference.RW
* @private
*/
Reference.RW = RW;
export default Reference;
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@ -0,0 +1,654 @@
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.
*/
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-undefined */
import estraverse from "estraverse";
import esrecurse from "esrecurse";
import Reference from "./reference.js";
import Variable from "./variable.js";
import PatternVisitor from "./pattern-visitor.js";
import { Definition, ParameterDefinition } from "./definition.js";
import assert from "assert";
const { Syntax } = estraverse;
/**
* Traverse identifier in pattern
* @param {Object} options options
* @param {pattern} rootPattern root pattern
* @param {Refencer} referencer referencer
* @param {callback} callback callback
* @returns {void}
*/
function traverseIdentifierInPattern(options, rootPattern, referencer, callback) {
// Call the callback at left hand identifier nodes, and Collect right hand nodes.
const visitor = new PatternVisitor(options, rootPattern, callback);
visitor.visit(rootPattern);
// Process the right hand nodes recursively.
if (referencer !== null && referencer !== undefined) {
visitor.rightHandNodes.forEach(referencer.visit, referencer);
}
}
// Importing ImportDeclaration.
// http://people.mozilla.org/~jorendorff/es6-draft.html#sec-moduledeclarationinstantiation
// https://github.com/estree/estree/blob/master/es6.md#importdeclaration
// FIXME: Now, we don't create module environment, because the context is
// implementation dependent.
class Importer extends esrecurse.Visitor {
constructor(declaration, referencer) {
super(null, referencer.options);
this.declaration = declaration;
this.referencer = referencer;
}
visitImport(id, specifier) {
this.referencer.visitPattern(id, pattern => {
this.referencer.currentScope().__define(pattern,
new Definition(
Variable.ImportBinding,
pattern,
specifier,
this.declaration,
null,
null
));
});
}
ImportNamespaceSpecifier(node) {
const local = (node.local || node.id);
if (local) {
this.visitImport(local, node);
}
}
ImportDefaultSpecifier(node) {
const local = (node.local || node.id);
this.visitImport(local, node);
}
ImportSpecifier(node) {
const local = (node.local || node.id);
if (node.name) {
this.visitImport(node.name, node);
} else {
this.visitImport(local, node);
}
}
}
// Referencing variables and creating bindings.
class Referencer extends esrecurse.Visitor {
constructor(options, scopeManager) {
super(null, options);
this.options = options;
this.scopeManager = scopeManager;
this.parent = null;
this.isInnerMethodDefinition = false;
}
currentScope() {
return this.scopeManager.__currentScope;
}
close(node) {
while (this.currentScope() && node === this.currentScope().block) {
this.scopeManager.__currentScope = this.currentScope().__close(this.scopeManager);
}
}
pushInnerMethodDefinition(isInnerMethodDefinition) {
const previous = this.isInnerMethodDefinition;
this.isInnerMethodDefinition = isInnerMethodDefinition;
return previous;
}
popInnerMethodDefinition(isInnerMethodDefinition) {
this.isInnerMethodDefinition = isInnerMethodDefinition;
}
referencingDefaultValue(pattern, assignments, maybeImplicitGlobal, init) {
const scope = this.currentScope();
assignments.forEach(assignment => {
scope.__referencing(
pattern,
Reference.WRITE,
assignment.right,
maybeImplicitGlobal,
pattern !== assignment.left,
init
);
});
}
visitPattern(node, options, callback) {
let visitPatternOptions = options;
let visitPatternCallback = callback;
if (typeof options === "function") {
visitPatternCallback = options;
visitPatternOptions = { processRightHandNodes: false };
}
traverseIdentifierInPattern(
this.options,
node,
visitPatternOptions.processRightHandNodes ? this : null,
visitPatternCallback
);
}
visitFunction(node) {
let i, iz;
// FunctionDeclaration name is defined in upper scope
// NOTE: Not referring variableScope. It is intended.
// Since
// in ES5, FunctionDeclaration should be in FunctionBody.
// in ES6, FunctionDeclaration should be block scoped.
if (node.type === Syntax.FunctionDeclaration) {
// id is defined in upper scope
this.currentScope().__define(node.id,
new Definition(
Variable.FunctionName,
node.id,
node,
null,
null,
null
));
}
// FunctionExpression with name creates its special scope;
// FunctionExpressionNameScope.
if (node.type === Syntax.FunctionExpression && node.id) {
this.scopeManager.__nestFunctionExpressionNameScope(node);
}
// Consider this function is in the MethodDefinition.
this.scopeManager.__nestFunctionScope(node, this.isInnerMethodDefinition);
const that = this;
/**
* Visit pattern callback
* @param {pattern} pattern pattern
* @param {Object} info info
* @returns {void}
*/
function visitPatternCallback(pattern, info) {
that.currentScope().__define(pattern,
new ParameterDefinition(
pattern,
node,
i,
info.rest
));
that.referencingDefaultValue(pattern, info.assignments, null, true);
}
// Process parameter declarations.
for (i = 0, iz = node.params.length; i < iz; ++i) {
this.visitPattern(node.params[i], { processRightHandNodes: true }, visitPatternCallback);
}
// if there's a rest argument, add that
if (node.rest) {
this.visitPattern({
type: "RestElement",
argument: node.rest
}, pattern => {
this.currentScope().__define(pattern,
new ParameterDefinition(
pattern,
node,
node.params.length,
true
));
});
}
// In TypeScript there are a number of function-like constructs which have no body,
// so check it exists before traversing
if (node.body) {
// Skip BlockStatement to prevent creating BlockStatement scope.
if (node.body.type === Syntax.BlockStatement) {
this.visitChildren(node.body);
} else {
this.visit(node.body);
}
}
this.close(node);
}
visitClass(node) {
if (node.type === Syntax.ClassDeclaration) {
this.currentScope().__define(node.id,
new Definition(
Variable.ClassName,
node.id,
node,
null,
null,
null
));
}
this.visit(node.superClass);
this.scopeManager.__nestClassScope(node);
if (node.id) {
this.currentScope().__define(node.id,
new Definition(
Variable.ClassName,
node.id,
node
));
}
this.visit(node.body);
this.close(node);
}
visitProperty(node) {
let previous;
if (node.computed) {
this.visit(node.key);
}
const isMethodDefinition = node.type === Syntax.MethodDefinition;
if (isMethodDefinition) {
previous = this.pushInnerMethodDefinition(true);
}
this.visit(node.value);
if (isMethodDefinition) {
this.popInnerMethodDefinition(previous);
}
}
visitForIn(node) {
if (node.left.type === Syntax.VariableDeclaration && node.left.kind !== "var") {
this.scopeManager.__nestForScope(node);
}
if (node.left.type === Syntax.VariableDeclaration) {
this.visit(node.left);
this.visitPattern(node.left.declarations[0].id, pattern => {
this.currentScope().__referencing(pattern, Reference.WRITE, node.right, null, true, true);
});
} else {
this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => {
let maybeImplicitGlobal = null;
if (!this.currentScope().isStrict) {
maybeImplicitGlobal = {
pattern,
node
};
}
this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);
this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, true, false);
});
}
this.visit(node.right);
this.visit(node.body);
this.close(node);
}
visitVariableDeclaration(variableTargetScope, type, node, index) {
const decl = node.declarations[index];
const init = decl.init;
this.visitPattern(decl.id, { processRightHandNodes: true }, (pattern, info) => {
variableTargetScope.__define(
pattern,
new Definition(
type,
pattern,
decl,
node,
index,
node.kind
)
);
this.referencingDefaultValue(pattern, info.assignments, null, true);
if (init) {
this.currentScope().__referencing(pattern, Reference.WRITE, init, null, !info.topLevel, true);
}
});
}
AssignmentExpression(node) {
if (PatternVisitor.isPattern(node.left)) {
if (node.operator === "=") {
this.visitPattern(node.left, { processRightHandNodes: true }, (pattern, info) => {
let maybeImplicitGlobal = null;
if (!this.currentScope().isStrict) {
maybeImplicitGlobal = {
pattern,
node
};
}
this.referencingDefaultValue(pattern, info.assignments, maybeImplicitGlobal, false);
this.currentScope().__referencing(pattern, Reference.WRITE, node.right, maybeImplicitGlobal, !info.topLevel, false);
});
} else {
this.currentScope().__referencing(node.left, Reference.RW, node.right);
}
} else {
this.visit(node.left);
}
this.visit(node.right);
}
CatchClause(node) {
this.scopeManager.__nestCatchScope(node);
this.visitPattern(node.param, { processRightHandNodes: true }, (pattern, info) => {
this.currentScope().__define(pattern,
new Definition(
Variable.CatchClause,
node.param,
node,
null,
null,
null
));
this.referencingDefaultValue(pattern, info.assignments, null, true);
});
this.visit(node.body);
this.close(node);
}
Program(node) {
this.scopeManager.__nestGlobalScope(node);
if (this.scopeManager.isGlobalReturn()) {
// Force strictness of GlobalScope to false when using node.js scope.
this.currentScope().isStrict = false;
this.scopeManager.__nestFunctionScope(node, false);
}
if (this.scopeManager.__isES6() && this.scopeManager.isModule()) {
this.scopeManager.__nestModuleScope(node);
}
if (this.scopeManager.isStrictModeSupported() && this.scopeManager.isImpliedStrict()) {
this.currentScope().isStrict = true;
}
this.visitChildren(node);
this.close(node);
}
Identifier(node) {
this.currentScope().__referencing(node);
}
// eslint-disable-next-line class-methods-use-this
PrivateIdentifier() {
// Do nothing.
}
UpdateExpression(node) {
if (PatternVisitor.isPattern(node.argument)) {
this.currentScope().__referencing(node.argument, Reference.RW, null);
} else {
this.visitChildren(node);
}
}
MemberExpression(node) {
this.visit(node.object);
if (node.computed) {
this.visit(node.property);
}
}
Property(node) {
this.visitProperty(node);
}
PropertyDefinition(node) {
const { computed, key, value } = node;
if (computed) {
this.visit(key);
}
if (value) {
this.scopeManager.__nestClassFieldInitializerScope(value);
this.visit(value);
this.close(value);
}
}
StaticBlock(node) {
this.scopeManager.__nestClassStaticBlockScope(node);
this.visitChildren(node);
this.close(node);
}
MethodDefinition(node) {
this.visitProperty(node);
}
BreakStatement() {} // eslint-disable-line class-methods-use-this
ContinueStatement() {} // eslint-disable-line class-methods-use-this
LabeledStatement(node) {
this.visit(node.body);
}
ForStatement(node) {
// Create ForStatement declaration.
// NOTE: In ES6, ForStatement dynamically generates
// per iteration environment. However, escope is
// a static analyzer, we only generate one scope for ForStatement.
if (node.init && node.init.type === Syntax.VariableDeclaration && node.init.kind !== "var") {
this.scopeManager.__nestForScope(node);
}
this.visitChildren(node);
this.close(node);
}
ClassExpression(node) {
this.visitClass(node);
}
ClassDeclaration(node) {
this.visitClass(node);
}
CallExpression(node) {
// Check this is direct call to eval
if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") {
// NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and
// let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment.
this.currentScope().variableScope.__detectEval();
}
this.visitChildren(node);
}
BlockStatement(node) {
if (this.scopeManager.__isES6()) {
this.scopeManager.__nestBlockScope(node);
}
this.visitChildren(node);
this.close(node);
}
ThisExpression() {
this.currentScope().variableScope.__detectThis();
}
WithStatement(node) {
this.visit(node.object);
// Then nest scope for WithStatement.
this.scopeManager.__nestWithScope(node);
this.visit(node.body);
this.close(node);
}
VariableDeclaration(node) {
const variableTargetScope = (node.kind === "var") ? this.currentScope().variableScope : this.currentScope();
for (let i = 0, iz = node.declarations.length; i < iz; ++i) {
const decl = node.declarations[i];
this.visitVariableDeclaration(variableTargetScope, Variable.Variable, node, i);
if (decl.init) {
this.visit(decl.init);
}
}
}
// sec 13.11.8
SwitchStatement(node) {
this.visit(node.discriminant);
if (this.scopeManager.__isES6()) {
this.scopeManager.__nestSwitchScope(node);
}
for (let i = 0, iz = node.cases.length; i < iz; ++i) {
this.visit(node.cases[i]);
}
this.close(node);
}
FunctionDeclaration(node) {
this.visitFunction(node);
}
FunctionExpression(node) {
this.visitFunction(node);
}
ForOfStatement(node) {
this.visitForIn(node);
}
ForInStatement(node) {
this.visitForIn(node);
}
ArrowFunctionExpression(node) {
this.visitFunction(node);
}
ImportDeclaration(node) {
assert(this.scopeManager.__isES6() && this.scopeManager.isModule(), "ImportDeclaration should appear when the mode is ES6 and in the module context.");
const importer = new Importer(node, this);
importer.visit(node);
}
visitExportDeclaration(node) {
if (node.source) {
return;
}
if (node.declaration) {
this.visit(node.declaration);
return;
}
this.visitChildren(node);
}
// TODO: ExportDeclaration doesn't exist. for bc?
ExportDeclaration(node) {
this.visitExportDeclaration(node);
}
ExportAllDeclaration(node) {
this.visitExportDeclaration(node);
}
ExportDefaultDeclaration(node) {
this.visitExportDeclaration(node);
}
ExportNamedDeclaration(node) {
this.visitExportDeclaration(node);
}
ExportSpecifier(node) {
// TODO: `node.id` doesn't exist. for bc?
const local = (node.id || node.local);
this.visit(local);
}
MetaProperty() { // eslint-disable-line class-methods-use-this
// do nothing.
}
}
export default Referencer;
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@ -0,0 +1,255 @@
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.
*/
/* eslint-disable no-underscore-dangle */
import {
BlockScope,
CatchScope,
ClassFieldInitializerScope,
ClassStaticBlockScope,
ClassScope,
ForScope,
FunctionExpressionNameScope,
FunctionScope,
GlobalScope,
ModuleScope,
SwitchScope,
WithScope
} from "./scope.js";
import assert from "assert";
/**
* @constructor ScopeManager
*/
class ScopeManager {
constructor(options) {
this.scopes = [];
this.globalScope = null;
this.__nodeToScope = new WeakMap();
this.__currentScope = null;
this.__options = options;
this.__declaredVariables = new WeakMap();
}
__useDirective() {
return this.__options.directive;
}
__isOptimistic() {
return this.__options.optimistic;
}
__ignoreEval() {
return this.__options.ignoreEval;
}
isGlobalReturn() {
return this.__options.nodejsScope || this.__options.sourceType === "commonjs";
}
isModule() {
return this.__options.sourceType === "module";
}
isImpliedStrict() {
return this.__options.impliedStrict;
}
isStrictModeSupported() {
return this.__options.ecmaVersion >= 5;
}
// Returns appropriate scope for this node.
__get(node) {
return this.__nodeToScope.get(node);
}
/**
* Get variables that are declared by the node.
*
* "are declared by the node" means the node is same as `Variable.defs[].node` or `Variable.defs[].parent`.
* If the node declares nothing, this method returns an empty array.
* CAUTION: This API is experimental. See https://github.com/estools/escope/pull/69 for more details.
* @param {Espree.Node} node a node to get.
* @returns {Variable[]} variables that declared by the node.
*/
getDeclaredVariables(node) {
return this.__declaredVariables.get(node) || [];
}
/**
* acquire scope from node.
* @function ScopeManager#acquire
* @param {Espree.Node} node node for the acquired scope.
* @param {?boolean} [inner=false] look up the most inner scope, default value is false.
* @returns {Scope?} Scope from node
*/
acquire(node, inner) {
/**
* predicate
* @param {Scope} testScope scope to test
* @returns {boolean} predicate
*/
function predicate(testScope) {
if (testScope.type === "function" && testScope.functionExpressionScope) {
return false;
}
return true;
}
const scopes = this.__get(node);
if (!scopes || scopes.length === 0) {
return null;
}
// Heuristic selection from all scopes.
// If you would like to get all scopes, please use ScopeManager#acquireAll.
if (scopes.length === 1) {
return scopes[0];
}
if (inner) {
for (let i = scopes.length - 1; i >= 0; --i) {
const scope = scopes[i];
if (predicate(scope)) {
return scope;
}
}
} else {
for (let i = 0, iz = scopes.length; i < iz; ++i) {
const scope = scopes[i];
if (predicate(scope)) {
return scope;
}
}
}
return null;
}
/**
* acquire all scopes from node.
* @function ScopeManager#acquireAll
* @param {Espree.Node} node node for the acquired scope.
* @returns {Scopes?} Scope array
*/
acquireAll(node) {
return this.__get(node);
}
/**
* release the node.
* @function ScopeManager#release
* @param {Espree.Node} node releasing node.
* @param {?boolean} [inner=false] look up the most inner scope, default value is false.
* @returns {Scope?} upper scope for the node.
*/
release(node, inner) {
const scopes = this.__get(node);
if (scopes && scopes.length) {
const scope = scopes[0].upper;
if (!scope) {
return null;
}
return this.acquire(scope.block, inner);
}
return null;
}
attach() { } // eslint-disable-line class-methods-use-this
detach() { } // eslint-disable-line class-methods-use-this
__nestScope(scope) {
if (scope instanceof GlobalScope) {
assert(this.__currentScope === null);
this.globalScope = scope;
}
this.__currentScope = scope;
return scope;
}
__nestGlobalScope(node) {
return this.__nestScope(new GlobalScope(this, node));
}
__nestBlockScope(node) {
return this.__nestScope(new BlockScope(this, this.__currentScope, node));
}
__nestFunctionScope(node, isMethodDefinition) {
return this.__nestScope(new FunctionScope(this, this.__currentScope, node, isMethodDefinition));
}
__nestForScope(node) {
return this.__nestScope(new ForScope(this, this.__currentScope, node));
}
__nestCatchScope(node) {
return this.__nestScope(new CatchScope(this, this.__currentScope, node));
}
__nestWithScope(node) {
return this.__nestScope(new WithScope(this, this.__currentScope, node));
}
__nestClassScope(node) {
return this.__nestScope(new ClassScope(this, this.__currentScope, node));
}
__nestClassFieldInitializerScope(node) {
return this.__nestScope(new ClassFieldInitializerScope(this, this.__currentScope, node));
}
__nestClassStaticBlockScope(node) {
return this.__nestScope(new ClassStaticBlockScope(this, this.__currentScope, node));
}
__nestSwitchScope(node) {
return this.__nestScope(new SwitchScope(this, this.__currentScope, node));
}
__nestModuleScope(node) {
return this.__nestScope(new ModuleScope(this, this.__currentScope, node));
}
__nestFunctionExpressionNameScope(node) {
return this.__nestScope(new FunctionExpressionNameScope(this, this.__currentScope, node));
}
__isES6() {
return this.__options.ecmaVersion >= 6;
}
}
export default ScopeManager;
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@ -0,0 +1,772 @@
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.
*/
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-undefined */
import estraverse from "estraverse";
import Reference from "./reference.js";
import Variable from "./variable.js";
import { Definition } from "./definition.js";
import assert from "assert";
const { Syntax } = estraverse;
/**
* Test if scope is struct
* @param {Scope} scope scope
* @param {Block} block block
* @param {boolean} isMethodDefinition is method definition
* @param {boolean} useDirective use directive
* @returns {boolean} is strict scope
*/
function isStrictScope(scope, block, isMethodDefinition, useDirective) {
let body;
// When upper scope is exists and strict, inner scope is also strict.
if (scope.upper && scope.upper.isStrict) {
return true;
}
if (isMethodDefinition) {
return true;
}
if (scope.type === "class" || scope.type === "module") {
return true;
}
if (scope.type === "block" || scope.type === "switch") {
return false;
}
if (scope.type === "function") {
if (block.type === Syntax.ArrowFunctionExpression && block.body.type !== Syntax.BlockStatement) {
return false;
}
if (block.type === Syntax.Program) {
body = block;
} else {
body = block.body;
}
if (!body) {
return false;
}
} else if (scope.type === "global") {
body = block;
} else {
return false;
}
// Search 'use strict' directive.
if (useDirective) {
for (let i = 0, iz = body.body.length; i < iz; ++i) {
const stmt = body.body[i];
if (stmt.type !== Syntax.DirectiveStatement) {
break;
}
if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") {
return true;
}
}
} else {
for (let i = 0, iz = body.body.length; i < iz; ++i) {
const stmt = body.body[i];
if (stmt.type !== Syntax.ExpressionStatement) {
break;
}
const expr = stmt.expression;
if (expr.type !== Syntax.Literal || typeof expr.value !== "string") {
break;
}
if (expr.raw !== null && expr.raw !== undefined) {
if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") {
return true;
}
} else {
if (expr.value === "use strict") {
return true;
}
}
}
}
return false;
}
/**
* Register scope
* @param {ScopeManager} scopeManager scope manager
* @param {Scope} scope scope
* @returns {void}
*/
function registerScope(scopeManager, scope) {
scopeManager.scopes.push(scope);
const scopes = scopeManager.__nodeToScope.get(scope.block);
if (scopes) {
scopes.push(scope);
} else {
scopeManager.__nodeToScope.set(scope.block, [scope]);
}
}
/**
* Should be statically
* @param {Object} def def
* @returns {boolean} should be statically
*/
function shouldBeStatically(def) {
return (
(def.type === Variable.ClassName) ||
(def.type === Variable.Variable && def.parent.kind !== "var")
);
}
/**
* @constructor Scope
*/
class Scope {
constructor(scopeManager, type, upperScope, block, isMethodDefinition) {
/**
* One of "global", "module", "function", "function-expression-name", "block", "switch", "catch", "with", "for",
* "class", "class-field-initializer", "class-static-block".
* @member {string} Scope#type
*/
this.type = type;
/**
* The scoped {@link Variable}s of this scope, as <code>{ Variable.name
* : Variable }</code>.
* @member {Map} Scope#set
*/
this.set = new Map();
/**
* The tainted variables of this scope, as <code>{ Variable.name :
* boolean }</code>.
* @member {Map} Scope#taints */
this.taints = new Map();
/**
* Generally, through the lexical scoping of JS you can always know
* which variable an identifier in the source code refers to. There are
* a few exceptions to this rule. With 'global' and 'with' scopes you
* can only decide at runtime which variable a reference refers to.
* Moreover, if 'eval()' is used in a scope, it might introduce new
* bindings in this or its parent scopes.
* All those scopes are considered 'dynamic'.
* @member {boolean} Scope#dynamic
*/
this.dynamic = this.type === "global" || this.type === "with";
/**
* A reference to the scope-defining syntax node.
* @member {espree.Node} Scope#block
*/
this.block = block;
/**
* The {@link Reference|references} that are not resolved with this scope.
* @member {Reference[]} Scope#through
*/
this.through = [];
/**
* The scoped {@link Variable}s of this scope. In the case of a
* 'function' scope this includes the automatic argument <em>arguments</em> as
* its first element, as well as all further formal arguments.
* @member {Variable[]} Scope#variables
*/
this.variables = [];
/**
* Any variable {@link Reference|reference} found in this scope. This
* includes occurrences of local variables as well as variables from
* parent scopes (including the global scope). For local variables
* this also includes defining occurrences (like in a 'var' statement).
* In a 'function' scope this does not include the occurrences of the
* formal parameter in the parameter list.
* @member {Reference[]} Scope#references
*/
this.references = [];
/**
* For 'global' and 'function' scopes, this is a self-reference. For
* other scope types this is the <em>variableScope</em> value of the
* parent scope.
* @member {Scope} Scope#variableScope
*/
this.variableScope =
this.type === "global" ||
this.type === "module" ||
this.type === "function" ||
this.type === "class-field-initializer" ||
this.type === "class-static-block"
? this
: upperScope.variableScope;
/**
* Whether this scope is created by a FunctionExpression.
* @member {boolean} Scope#functionExpressionScope
*/
this.functionExpressionScope = false;
/**
* Whether this is a scope that contains an 'eval()' invocation.
* @member {boolean} Scope#directCallToEvalScope
*/
this.directCallToEvalScope = false;
/**
* @member {boolean} Scope#thisFound
*/
this.thisFound = false;
this.__left = [];
/**
* Reference to the parent {@link Scope|scope}.
* @member {Scope} Scope#upper
*/
this.upper = upperScope;
/**
* Whether 'use strict' is in effect in this scope.
* @member {boolean} Scope#isStrict
*/
this.isStrict = scopeManager.isStrictModeSupported()
? isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective())
: false;
/**
* List of nested {@link Scope}s.
* @member {Scope[]} Scope#childScopes
*/
this.childScopes = [];
if (this.upper) {
this.upper.childScopes.push(this);
}
this.__declaredVariables = scopeManager.__declaredVariables;
registerScope(scopeManager, this);
}
__shouldStaticallyClose(scopeManager) {
return (!this.dynamic || scopeManager.__isOptimistic());
}
__shouldStaticallyCloseForGlobal(ref) {
// On global scope, let/const/class declarations should be resolved statically.
const name = ref.identifier.name;
if (!this.set.has(name)) {
return false;
}
const variable = this.set.get(name);
const defs = variable.defs;
return defs.length > 0 && defs.every(shouldBeStatically);
}
__staticCloseRef(ref) {
if (!this.__resolve(ref)) {
this.__delegateToUpperScope(ref);
}
}
__dynamicCloseRef(ref) {
// notify all names are through to global
let current = this;
do {
current.through.push(ref);
current = current.upper;
} while (current);
}
__globalCloseRef(ref) {
// let/const/class declarations should be resolved statically.
// others should be resolved dynamically.
if (this.__shouldStaticallyCloseForGlobal(ref)) {
this.__staticCloseRef(ref);
} else {
this.__dynamicCloseRef(ref);
}
}
__close(scopeManager) {
let closeRef;
if (this.__shouldStaticallyClose(scopeManager)) {
closeRef = this.__staticCloseRef;
} else if (this.type !== "global") {
closeRef = this.__dynamicCloseRef;
} else {
closeRef = this.__globalCloseRef;
}
// Try Resolving all references in this scope.
for (let i = 0, iz = this.__left.length; i < iz; ++i) {
const ref = this.__left[i];
closeRef.call(this, ref);
}
this.__left = null;
return this.upper;
}
// To override by function scopes.
// References in default parameters isn't resolved to variables which are in their function body.
__isValidResolution(ref, variable) { // eslint-disable-line class-methods-use-this, no-unused-vars
return true;
}
__resolve(ref) {
const name = ref.identifier.name;
if (!this.set.has(name)) {
return false;
}
const variable = this.set.get(name);
if (!this.__isValidResolution(ref, variable)) {
return false;
}
variable.references.push(ref);
variable.stack = variable.stack && ref.from.variableScope === this.variableScope;
if (ref.tainted) {
variable.tainted = true;
this.taints.set(variable.name, true);
}
ref.resolved = variable;
return true;
}
__delegateToUpperScope(ref) {
if (this.upper) {
this.upper.__left.push(ref);
}
this.through.push(ref);
}
__addDeclaredVariablesOfNode(variable, node) {
if (node === null || node === undefined) {
return;
}
let variables = this.__declaredVariables.get(node);
if (variables === null || variables === undefined) {
variables = [];
this.__declaredVariables.set(node, variables);
}
if (variables.indexOf(variable) === -1) {
variables.push(variable);
}
}
__defineGeneric(name, set, variables, node, def) {
let variable;
variable = set.get(name);
if (!variable) {
variable = new Variable(name, this);
set.set(name, variable);
variables.push(variable);
}
if (def) {
variable.defs.push(def);
this.__addDeclaredVariablesOfNode(variable, def.node);
this.__addDeclaredVariablesOfNode(variable, def.parent);
}
if (node) {
variable.identifiers.push(node);
}
}
__define(node, def) {
if (node && node.type === Syntax.Identifier) {
this.__defineGeneric(
node.name,
this.set,
this.variables,
node,
def
);
}
}
__referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) {
// because Array element may be null
if (!node || node.type !== Syntax.Identifier) {
return;
}
// Specially handle like `this`.
if (node.name === "super") {
return;
}
const ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init);
this.references.push(ref);
this.__left.push(ref);
}
__detectEval() {
let current = this;
this.directCallToEvalScope = true;
do {
current.dynamic = true;
current = current.upper;
} while (current);
}
__detectThis() {
this.thisFound = true;
}
__isClosed() {
return this.__left === null;
}
/**
* returns resolved {Reference}
* @function Scope#resolve
* @param {Espree.Identifier} ident identifier to be resolved.
* @returns {Reference} reference
*/
resolve(ident) {
let ref, i, iz;
assert(this.__isClosed(), "Scope should be closed.");
assert(ident.type === Syntax.Identifier, "Target should be identifier.");
for (i = 0, iz = this.references.length; i < iz; ++i) {
ref = this.references[i];
if (ref.identifier === ident) {
return ref;
}
}
return null;
}
/**
* returns this scope is static
* @function Scope#isStatic
* @returns {boolean} static
*/
isStatic() {
return !this.dynamic;
}
/**
* returns this scope has materialized arguments
* @function Scope#isArgumentsMaterialized
* @returns {boolean} arguemnts materialized
*/
isArgumentsMaterialized() { // eslint-disable-line class-methods-use-this
return true;
}
/**
* returns this scope has materialized `this` reference
* @function Scope#isThisMaterialized
* @returns {boolean} this materialized
*/
isThisMaterialized() { // eslint-disable-line class-methods-use-this
return true;
}
isUsedName(name) {
if (this.set.has(name)) {
return true;
}
for (let i = 0, iz = this.through.length; i < iz; ++i) {
if (this.through[i].identifier.name === name) {
return true;
}
}
return false;
}
}
class GlobalScope extends Scope {
constructor(scopeManager, block) {
super(scopeManager, "global", null, block, false);
this.implicit = {
set: new Map(),
variables: [],
/**
* List of {@link Reference}s that are left to be resolved (i.e. which
* need to be linked to the variable they refer to).
* @member {Reference[]} Scope#implicit#left
*/
left: []
};
}
__close(scopeManager) {
const implicit = [];
for (let i = 0, iz = this.__left.length; i < iz; ++i) {
const ref = this.__left[i];
if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) {
implicit.push(ref.__maybeImplicitGlobal);
}
}
// create an implicit global variable from assignment expression
for (let i = 0, iz = implicit.length; i < iz; ++i) {
const info = implicit[i];
this.__defineImplicit(info.pattern,
new Definition(
Variable.ImplicitGlobalVariable,
info.pattern,
info.node,
null,
null,
null
));
}
this.implicit.left = this.__left;
return super.__close(scopeManager);
}
__defineImplicit(node, def) {
if (node && node.type === Syntax.Identifier) {
this.__defineGeneric(
node.name,
this.implicit.set,
this.implicit.variables,
node,
def
);
}
}
}
class ModuleScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, "module", upperScope, block, false);
}
}
class FunctionExpressionNameScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, "function-expression-name", upperScope, block, false);
this.__define(block.id,
new Definition(
Variable.FunctionName,
block.id,
block,
null,
null,
null
));
this.functionExpressionScope = true;
}
}
class CatchScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, "catch", upperScope, block, false);
}
}
class WithScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, "with", upperScope, block, false);
}
__close(scopeManager) {
if (this.__shouldStaticallyClose(scopeManager)) {
return super.__close(scopeManager);
}
for (let i = 0, iz = this.__left.length; i < iz; ++i) {
const ref = this.__left[i];
ref.tainted = true;
this.__delegateToUpperScope(ref);
}
this.__left = null;
return this.upper;
}
}
class BlockScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, "block", upperScope, block, false);
}
}
class SwitchScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, "switch", upperScope, block, false);
}
}
class FunctionScope extends Scope {
constructor(scopeManager, upperScope, block, isMethodDefinition) {
super(scopeManager, "function", upperScope, block, isMethodDefinition);
// section 9.2.13, FunctionDeclarationInstantiation.
// NOTE Arrow functions never have an arguments objects.
if (this.block.type !== Syntax.ArrowFunctionExpression) {
this.__defineArguments();
}
}
isArgumentsMaterialized() {
// TODO(Constellation)
// We can more aggressive on this condition like this.
//
// function t() {
// // arguments of t is always hidden.
// function arguments() {
// }
// }
if (this.block.type === Syntax.ArrowFunctionExpression) {
return false;
}
if (!this.isStatic()) {
return true;
}
const variable = this.set.get("arguments");
assert(variable, "Always have arguments variable.");
return variable.tainted || variable.references.length !== 0;
}
isThisMaterialized() {
if (!this.isStatic()) {
return true;
}
return this.thisFound;
}
__defineArguments() {
this.__defineGeneric(
"arguments",
this.set,
this.variables,
null,
null
);
this.taints.set("arguments", true);
}
// References in default parameters isn't resolved to variables which are in their function body.
// const x = 1
// function f(a = x) { // This `x` is resolved to the `x` in the outer scope.
// const x = 2
// console.log(a)
// }
__isValidResolution(ref, variable) {
// If `options.nodejsScope` is true, `this.block` becomes a Program node.
if (this.block.type === "Program") {
return true;
}
const bodyStart = this.block.body.range[0];
// It's invalid resolution in the following case:
return !(
variable.scope === this &&
ref.identifier.range[0] < bodyStart && // the reference is in the parameter part.
variable.defs.every(d => d.name.range[0] >= bodyStart) // the variable is in the body.
);
}
}
class ForScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, "for", upperScope, block, false);
}
}
class ClassScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, "class", upperScope, block, false);
}
}
class ClassFieldInitializerScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, "class-field-initializer", upperScope, block, true);
}
}
class ClassStaticBlockScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, "class-static-block", upperScope, block, true);
}
}
export {
Scope,
GlobalScope,
ModuleScope,
FunctionExpressionNameScope,
CatchScope,
WithScope,
BlockScope,
SwitchScope,
FunctionScope,
ForScope,
ClassScope,
ClassFieldInitializerScope,
ClassStaticBlockScope
};
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@ -0,0 +1,87 @@
/*
Copyright (C) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.
*/
/**
* A Variable represents a locally scoped identifier. These include arguments to
* functions.
* @constructor Variable
*/
class Variable {
constructor(name, scope) {
/**
* The variable name, as given in the source code.
* @member {string} Variable#name
*/
this.name = name;
/**
* List of defining occurrences of this variable (like in 'var ...'
* statements or as parameter), as AST nodes.
* @member {espree.Identifier[]} Variable#identifiers
*/
this.identifiers = [];
/**
* List of {@link Reference|references} of this variable (excluding parameter entries)
* in its defining scope and all nested scopes. For defining
* occurrences only see {@link Variable#defs}.
* @member {Reference[]} Variable#references
*/
this.references = [];
/**
* List of defining occurrences of this variable (like in 'var ...'
* statements or as parameter), as custom objects.
* @member {Definition[]} Variable#defs
*/
this.defs = [];
this.tainted = false;
/**
* Whether this is a stack variable.
* @member {boolean} Variable#stack
*/
this.stack = true;
/**
* Reference to the enclosing Scope.
* @member {Scope} Variable#scope
*/
this.scope = scope;
}
}
Variable.CatchClause = "CatchClause";
Variable.Parameter = "Parameter";
Variable.FunctionName = "FunctionName";
Variable.ClassName = "ClassName";
Variable.Variable = "Variable";
Variable.ImportBinding = "ImportBinding";
Variable.ImplicitGlobalVariable = "ImplicitGlobalVariable";
export default Variable;
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@ -0,0 +1,3 @@
const version = "7.2.2";
export default version;

View File

@ -0,0 +1,63 @@
{
"name": "eslint-scope",
"description": "ECMAScript scope analyzer for ESLint",
"homepage": "http://github.com/eslint/eslint-scope",
"main": "./dist/eslint-scope.cjs",
"type": "module",
"exports": {
".": {
"import": "./lib/index.js",
"require": "./dist/eslint-scope.cjs"
},
"./package.json": "./package.json"
},
"version": "7.2.2",
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"repository": "eslint/eslint-scope",
"funding": "https://opencollective.com/eslint",
"bugs": {
"url": "https://github.com/eslint/eslint-scope/issues"
},
"license": "BSD-2-Clause",
"scripts": {
"build": "rollup -c",
"lint": "npm run build && node Makefile.js lint",
"update-version": "node tools/update-version.js",
"test": "npm run build && node Makefile.js test",
"prepublishOnly": "npm run update-version && npm run build",
"generate-release": "eslint-generate-release",
"generate-alpharelease": "eslint-generate-prerelease alpha",
"generate-betarelease": "eslint-generate-prerelease beta",
"generate-rcrelease": "eslint-generate-prerelease rc",
"publish-release": "eslint-publish-release"
},
"files": [
"LICENSE",
"README.md",
"lib",
"dist/eslint-scope.cjs"
],
"dependencies": {
"esrecurse": "^4.3.0",
"estraverse": "^5.2.0"
},
"devDependencies": {
"@typescript-eslint/parser": "^4.28.1",
"c8": "^7.7.3",
"chai": "^4.3.4",
"eslint": "^7.29.0",
"eslint-config-eslint": "^7.0.0",
"eslint-plugin-jsdoc": "^35.4.1",
"eslint-plugin-node": "^11.1.0",
"eslint-release": "^3.2.0",
"eslint-visitor-keys": "^3.3.0",
"espree": "^9.3.1",
"mocha": "^9.0.1",
"npm-license": "^0.3.3",
"rollup": "^2.52.7",
"shelljs": "^0.8.4",
"typescript": "^4.3.5"
}
}

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright contributors
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.

View File

@ -0,0 +1,105 @@
# eslint-visitor-keys
[![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys)
[![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys)
[![Build Status](https://github.com/eslint/eslint-visitor-keys/workflows/CI/badge.svg)](https://github.com/eslint/eslint-visitor-keys/actions)
Constants and utilities about visitor keys to traverse AST.
## 💿 Installation
Use [npm] to install.
```bash
$ npm install eslint-visitor-keys
```
### Requirements
- [Node.js] `^12.22.0`, `^14.17.0`, or `>=16.0.0`
## 📖 Usage
To use in an ESM file:
```js
import * as evk from "eslint-visitor-keys"
```
To use in a CommonJS file:
```js
const evk = require("eslint-visitor-keys")
```
### evk.KEYS
> type: `{ [type: string]: string[] | undefined }`
Visitor keys. This keys are frozen.
This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes.
For example:
```
console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"]
```
### evk.getKeys(node)
> type: `(node: object) => string[]`
Get the visitor keys of a given AST node.
This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`.
This will be used to traverse unknown nodes.
For example:
```js
const node = {
type: "AssignmentExpression",
left: { type: "Identifier", name: "foo" },
right: { type: "Literal", value: 0 }
}
console.log(evk.getKeys(node)) // → ["type", "left", "right"]
```
### evk.unionWith(additionalKeys)
> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }`
Make the union set with `evk.KEYS` and the given keys.
- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that.
- It removes duplicated keys as keeping the first one.
For example:
```js
console.log(evk.unionWith({
MethodDefinition: ["decorators"]
})) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... }
```
## 📰 Change log
See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases).
## 🍻 Contributing
Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/).
### Development commands
- `npm test` runs tests and measures code coverage.
- `npm run lint` checks source codes with ESLint.
- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser.
[npm]: https://www.npmjs.com/
[Node.js]: https://nodejs.org/
[ESTree]: https://github.com/estree/estree

View File

@ -0,0 +1,384 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
*/
/**
* @type {VisitorKeys}
*/
const KEYS = {
ArrayExpression: [
"elements"
],
ArrayPattern: [
"elements"
],
ArrowFunctionExpression: [
"params",
"body"
],
AssignmentExpression: [
"left",
"right"
],
AssignmentPattern: [
"left",
"right"
],
AwaitExpression: [
"argument"
],
BinaryExpression: [
"left",
"right"
],
BlockStatement: [
"body"
],
BreakStatement: [
"label"
],
CallExpression: [
"callee",
"arguments"
],
CatchClause: [
"param",
"body"
],
ChainExpression: [
"expression"
],
ClassBody: [
"body"
],
ClassDeclaration: [
"id",
"superClass",
"body"
],
ClassExpression: [
"id",
"superClass",
"body"
],
ConditionalExpression: [
"test",
"consequent",
"alternate"
],
ContinueStatement: [
"label"
],
DebuggerStatement: [],
DoWhileStatement: [
"body",
"test"
],
EmptyStatement: [],
ExperimentalRestProperty: [
"argument"
],
ExperimentalSpreadProperty: [
"argument"
],
ExportAllDeclaration: [
"exported",
"source"
],
ExportDefaultDeclaration: [
"declaration"
],
ExportNamedDeclaration: [
"declaration",
"specifiers",
"source"
],
ExportSpecifier: [
"exported",
"local"
],
ExpressionStatement: [
"expression"
],
ForInStatement: [
"left",
"right",
"body"
],
ForOfStatement: [
"left",
"right",
"body"
],
ForStatement: [
"init",
"test",
"update",
"body"
],
FunctionDeclaration: [
"id",
"params",
"body"
],
FunctionExpression: [
"id",
"params",
"body"
],
Identifier: [],
IfStatement: [
"test",
"consequent",
"alternate"
],
ImportDeclaration: [
"specifiers",
"source"
],
ImportDefaultSpecifier: [
"local"
],
ImportExpression: [
"source"
],
ImportNamespaceSpecifier: [
"local"
],
ImportSpecifier: [
"imported",
"local"
],
JSXAttribute: [
"name",
"value"
],
JSXClosingElement: [
"name"
],
JSXClosingFragment: [],
JSXElement: [
"openingElement",
"children",
"closingElement"
],
JSXEmptyExpression: [],
JSXExpressionContainer: [
"expression"
],
JSXFragment: [
"openingFragment",
"children",
"closingFragment"
],
JSXIdentifier: [],
JSXMemberExpression: [
"object",
"property"
],
JSXNamespacedName: [
"namespace",
"name"
],
JSXOpeningElement: [
"name",
"attributes"
],
JSXOpeningFragment: [],
JSXSpreadAttribute: [
"argument"
],
JSXSpreadChild: [
"expression"
],
JSXText: [],
LabeledStatement: [
"label",
"body"
],
Literal: [],
LogicalExpression: [
"left",
"right"
],
MemberExpression: [
"object",
"property"
],
MetaProperty: [
"meta",
"property"
],
MethodDefinition: [
"key",
"value"
],
NewExpression: [
"callee",
"arguments"
],
ObjectExpression: [
"properties"
],
ObjectPattern: [
"properties"
],
PrivateIdentifier: [],
Program: [
"body"
],
Property: [
"key",
"value"
],
PropertyDefinition: [
"key",
"value"
],
RestElement: [
"argument"
],
ReturnStatement: [
"argument"
],
SequenceExpression: [
"expressions"
],
SpreadElement: [
"argument"
],
StaticBlock: [
"body"
],
Super: [],
SwitchCase: [
"test",
"consequent"
],
SwitchStatement: [
"discriminant",
"cases"
],
TaggedTemplateExpression: [
"tag",
"quasi"
],
TemplateElement: [],
TemplateLiteral: [
"quasis",
"expressions"
],
ThisExpression: [],
ThrowStatement: [
"argument"
],
TryStatement: [
"block",
"handler",
"finalizer"
],
UnaryExpression: [
"argument"
],
UpdateExpression: [
"argument"
],
VariableDeclaration: [
"declarations"
],
VariableDeclarator: [
"id",
"init"
],
WhileStatement: [
"test",
"body"
],
WithStatement: [
"object",
"body"
],
YieldExpression: [
"argument"
]
};
// Types.
const NODE_TYPES = Object.keys(KEYS);
// Freeze the keys.
for (const type of NODE_TYPES) {
Object.freeze(KEYS[type]);
}
Object.freeze(KEYS);
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
/**
* @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
*/
// List to ignore keys.
const KEY_BLACKLIST = new Set([
"parent",
"leadingComments",
"trailingComments"
]);
/**
* Check whether a given key should be used or not.
* @param {string} key The key to check.
* @returns {boolean} `true` if the key should be used.
*/
function filterKey(key) {
return !KEY_BLACKLIST.has(key) && key[0] !== "_";
}
/**
* Get visitor keys of a given node.
* @param {object} node The AST node to get keys.
* @returns {readonly string[]} Visitor keys of the node.
*/
function getKeys(node) {
return Object.keys(node).filter(filterKey);
}
// Disable valid-jsdoc rule because it reports syntax error on the type of @returns.
// eslint-disable-next-line valid-jsdoc
/**
* Make the union set with `KEYS` and given keys.
* @param {VisitorKeys} additionalKeys The additional keys.
* @returns {VisitorKeys} The union set.
*/
function unionWith(additionalKeys) {
const retv = /** @type {{
[type: string]: ReadonlyArray<string>
}} */ (Object.assign({}, KEYS));
for (const type of Object.keys(additionalKeys)) {
if (Object.prototype.hasOwnProperty.call(retv, type)) {
const keys = new Set(additionalKeys[type]);
for (const key of retv[type]) {
keys.add(key);
}
retv[type] = Object.freeze(Array.from(keys));
} else {
retv[type] = Object.freeze(Array.from(additionalKeys[type]));
}
}
return Object.freeze(retv);
}
exports.KEYS = KEYS;
exports.getKeys = getKeys;
exports.unionWith = unionWith;

View File

@ -0,0 +1,27 @@
type VisitorKeys$1 = {
readonly [type: string]: readonly string[];
};
/**
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
*/
/**
* @type {VisitorKeys}
*/
declare const KEYS: VisitorKeys$1;
/**
* Get visitor keys of a given node.
* @param {object} node The AST node to get keys.
* @returns {readonly string[]} Visitor keys of the node.
*/
declare function getKeys(node: object): readonly string[];
/**
* Make the union set with `KEYS` and given keys.
* @param {VisitorKeys} additionalKeys The additional keys.
* @returns {VisitorKeys} The union set.
*/
declare function unionWith(additionalKeys: VisitorKeys): VisitorKeys;
type VisitorKeys = VisitorKeys$1;
export { KEYS, VisitorKeys, getKeys, unionWith };

View File

@ -0,0 +1,16 @@
/**
* Get visitor keys of a given node.
* @param {object} node The AST node to get keys.
* @returns {readonly string[]} Visitor keys of the node.
*/
export function getKeys(node: object): readonly string[];
/**
* Make the union set with `KEYS` and given keys.
* @param {VisitorKeys} additionalKeys The additional keys.
* @returns {VisitorKeys} The union set.
*/
export function unionWith(additionalKeys: VisitorKeys): VisitorKeys;
export { KEYS };
export type VisitorKeys = import('./visitor-keys.js').VisitorKeys;
import KEYS from "./visitor-keys.js";
//# sourceMappingURL=index.d.ts.map

View File

@ -0,0 +1,12 @@
export default KEYS;
export type VisitorKeys = {
readonly [type: string]: readonly string[];
};
/**
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
*/
/**
* @type {VisitorKeys}
*/
declare const KEYS: VisitorKeys;
//# sourceMappingURL=visitor-keys.d.ts.map

View File

@ -0,0 +1,65 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
import KEYS from "./visitor-keys.js";
/**
* @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
*/
// List to ignore keys.
const KEY_BLACKLIST = new Set([
"parent",
"leadingComments",
"trailingComments"
]);
/**
* Check whether a given key should be used or not.
* @param {string} key The key to check.
* @returns {boolean} `true` if the key should be used.
*/
function filterKey(key) {
return !KEY_BLACKLIST.has(key) && key[0] !== "_";
}
/**
* Get visitor keys of a given node.
* @param {object} node The AST node to get keys.
* @returns {readonly string[]} Visitor keys of the node.
*/
export function getKeys(node) {
return Object.keys(node).filter(filterKey);
}
// Disable valid-jsdoc rule because it reports syntax error on the type of @returns.
// eslint-disable-next-line valid-jsdoc
/**
* Make the union set with `KEYS` and given keys.
* @param {VisitorKeys} additionalKeys The additional keys.
* @returns {VisitorKeys} The union set.
*/
export function unionWith(additionalKeys) {
const retv = /** @type {{
[type: string]: ReadonlyArray<string>
}} */ (Object.assign({}, KEYS));
for (const type of Object.keys(additionalKeys)) {
if (Object.prototype.hasOwnProperty.call(retv, type)) {
const keys = new Set(additionalKeys[type]);
for (const key of retv[type]) {
keys.add(key);
}
retv[type] = Object.freeze(Array.from(keys));
} else {
retv[type] = Object.freeze(Array.from(additionalKeys[type]));
}
}
return Object.freeze(retv);
}
export { KEYS };

View File

@ -0,0 +1,315 @@
/**
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
*/
/**
* @type {VisitorKeys}
*/
const KEYS = {
ArrayExpression: [
"elements"
],
ArrayPattern: [
"elements"
],
ArrowFunctionExpression: [
"params",
"body"
],
AssignmentExpression: [
"left",
"right"
],
AssignmentPattern: [
"left",
"right"
],
AwaitExpression: [
"argument"
],
BinaryExpression: [
"left",
"right"
],
BlockStatement: [
"body"
],
BreakStatement: [
"label"
],
CallExpression: [
"callee",
"arguments"
],
CatchClause: [
"param",
"body"
],
ChainExpression: [
"expression"
],
ClassBody: [
"body"
],
ClassDeclaration: [
"id",
"superClass",
"body"
],
ClassExpression: [
"id",
"superClass",
"body"
],
ConditionalExpression: [
"test",
"consequent",
"alternate"
],
ContinueStatement: [
"label"
],
DebuggerStatement: [],
DoWhileStatement: [
"body",
"test"
],
EmptyStatement: [],
ExperimentalRestProperty: [
"argument"
],
ExperimentalSpreadProperty: [
"argument"
],
ExportAllDeclaration: [
"exported",
"source"
],
ExportDefaultDeclaration: [
"declaration"
],
ExportNamedDeclaration: [
"declaration",
"specifiers",
"source"
],
ExportSpecifier: [
"exported",
"local"
],
ExpressionStatement: [
"expression"
],
ForInStatement: [
"left",
"right",
"body"
],
ForOfStatement: [
"left",
"right",
"body"
],
ForStatement: [
"init",
"test",
"update",
"body"
],
FunctionDeclaration: [
"id",
"params",
"body"
],
FunctionExpression: [
"id",
"params",
"body"
],
Identifier: [],
IfStatement: [
"test",
"consequent",
"alternate"
],
ImportDeclaration: [
"specifiers",
"source"
],
ImportDefaultSpecifier: [
"local"
],
ImportExpression: [
"source"
],
ImportNamespaceSpecifier: [
"local"
],
ImportSpecifier: [
"imported",
"local"
],
JSXAttribute: [
"name",
"value"
],
JSXClosingElement: [
"name"
],
JSXClosingFragment: [],
JSXElement: [
"openingElement",
"children",
"closingElement"
],
JSXEmptyExpression: [],
JSXExpressionContainer: [
"expression"
],
JSXFragment: [
"openingFragment",
"children",
"closingFragment"
],
JSXIdentifier: [],
JSXMemberExpression: [
"object",
"property"
],
JSXNamespacedName: [
"namespace",
"name"
],
JSXOpeningElement: [
"name",
"attributes"
],
JSXOpeningFragment: [],
JSXSpreadAttribute: [
"argument"
],
JSXSpreadChild: [
"expression"
],
JSXText: [],
LabeledStatement: [
"label",
"body"
],
Literal: [],
LogicalExpression: [
"left",
"right"
],
MemberExpression: [
"object",
"property"
],
MetaProperty: [
"meta",
"property"
],
MethodDefinition: [
"key",
"value"
],
NewExpression: [
"callee",
"arguments"
],
ObjectExpression: [
"properties"
],
ObjectPattern: [
"properties"
],
PrivateIdentifier: [],
Program: [
"body"
],
Property: [
"key",
"value"
],
PropertyDefinition: [
"key",
"value"
],
RestElement: [
"argument"
],
ReturnStatement: [
"argument"
],
SequenceExpression: [
"expressions"
],
SpreadElement: [
"argument"
],
StaticBlock: [
"body"
],
Super: [],
SwitchCase: [
"test",
"consequent"
],
SwitchStatement: [
"discriminant",
"cases"
],
TaggedTemplateExpression: [
"tag",
"quasi"
],
TemplateElement: [],
TemplateLiteral: [
"quasis",
"expressions"
],
ThisExpression: [],
ThrowStatement: [
"argument"
],
TryStatement: [
"block",
"handler",
"finalizer"
],
UnaryExpression: [
"argument"
],
UpdateExpression: [
"argument"
],
VariableDeclaration: [
"declarations"
],
VariableDeclarator: [
"id",
"init"
],
WhileStatement: [
"test",
"body"
],
WithStatement: [
"object",
"body"
],
YieldExpression: [
"argument"
]
};
// Types.
const NODE_TYPES = Object.keys(KEYS);
// Freeze the keys.
for (const type of NODE_TYPES) {
Object.freeze(KEYS[type]);
}
Object.freeze(KEYS);
export default KEYS;

View File

@ -0,0 +1,74 @@
{
"name": "eslint-visitor-keys",
"version": "3.4.3",
"description": "Constants and utilities about visitor keys to traverse AST.",
"type": "module",
"main": "dist/eslint-visitor-keys.cjs",
"types": "./dist/index.d.ts",
"exports": {
".": [
{
"import": "./lib/index.js",
"require": "./dist/eslint-visitor-keys.cjs"
},
"./dist/eslint-visitor-keys.cjs"
],
"./package.json": "./package.json"
},
"files": [
"dist/index.d.ts",
"dist/visitor-keys.d.ts",
"dist/eslint-visitor-keys.cjs",
"dist/eslint-visitor-keys.d.cts",
"lib"
],
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"devDependencies": {
"@types/estree": "^0.0.51",
"@types/estree-jsx": "^0.0.1",
"@typescript-eslint/parser": "^5.14.0",
"c8": "^7.11.0",
"chai": "^4.3.6",
"eslint": "^7.29.0",
"eslint-config-eslint": "^7.0.0",
"eslint-plugin-jsdoc": "^35.4.0",
"eslint-plugin-node": "^11.1.0",
"eslint-release": "^3.2.0",
"esquery": "^1.4.0",
"json-diff": "^0.7.3",
"mocha": "^9.2.1",
"opener": "^1.5.2",
"rollup": "^2.70.0",
"rollup-plugin-dts": "^4.2.3",
"tsd": "^0.19.1",
"typescript": "^4.6.2"
},
"scripts": {
"build": "npm run build:cjs && npm run build:types",
"build:cjs": "rollup -c",
"build:debug": "npm run build:cjs -- -m && npm run build:types",
"build:keys": "node tools/build-keys-from-ts",
"build:types": "tsc",
"lint": "eslint .",
"prepare": "npm run build",
"release:generate:latest": "eslint-generate-release",
"release:generate:alpha": "eslint-generate-prerelease alpha",
"release:generate:beta": "eslint-generate-prerelease beta",
"release:generate:rc": "eslint-generate-prerelease rc",
"release:publish": "eslint-publish-release",
"test": "mocha tests/lib/**/*.cjs && c8 mocha tests/lib/**/*.js && npm run test:types",
"test:open-coverage": "c8 report --reporter lcov && opener coverage/lcov-report/index.html",
"test:types": "tsd"
},
"repository": "eslint/eslint-visitor-keys",
"funding": "https://opencollective.com/eslint",
"keywords": [],
"author": "Toru Nagashima (https://github.com/mysticatea)",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/eslint/eslint-visitor-keys/issues"
},
"homepage": "https://github.com/eslint/eslint-visitor-keys#readme"
}

View File

@ -0,0 +1,25 @@
BSD 2-Clause License
Copyright (c) Open JS Foundation
All rights reserved.
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.
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.

View File

@ -0,0 +1,244 @@
[![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree)
[![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree)
[![Build Status](https://github.com/eslint/espree/workflows/CI/badge.svg)](https://github.com/eslint/espree/actions)
[![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE)
# Espree
Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima.
## Usage
Install:
```
npm i espree
```
To use in an ESM file:
```js
import * as espree from "espree";
const ast = espree.parse(code);
```
To use in a Common JS file:
```js
const espree = require("espree");
const ast = espree.parse(code);
```
## API
### `parse()`
`parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters.
- `code` [string]() - the code which needs to be parsed.
- `options (Optional)` [Object]() - read more about this [here](#options).
```js
import * as espree from "espree";
const ast = espree.parse(code);
```
**Example :**
```js
const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 });
console.log(ast);
```
<details><summary>Output</summary>
<p>
```
Node {
type: 'Program',
start: 0,
end: 15,
body: [
Node {
type: 'VariableDeclaration',
start: 0,
end: 15,
declarations: [Array],
kind: 'let'
}
],
sourceType: 'script'
}
```
</p>
</details>
### `tokenize()`
`tokenize` returns the tokens of a given code. It takes two parameters.
- `code` [string]() - the code which needs to be parsed.
- `options (Optional)` [Object]() - read more about this [here](#options).
Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array
**Example :**
```js
import * as espree from "espree";
const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 });
console.log(tokens);
```
<details><summary>Output</summary>
<p>
```
Token { type: 'Keyword', value: 'let', start: 0, end: 3 },
Token { type: 'Identifier', value: 'foo', start: 4, end: 7 },
Token { type: 'Punctuator', value: '=', start: 8, end: 9 },
Token { type: 'String', value: '"bar"', start: 10, end: 15 }
```
</p>
</details>
### `version`
Returns the current `espree` version
### `VisitorKeys`
Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/eslint-visitor-keys)
### `latestEcmaVersion`
Returns the latest ECMAScript supported by `espree`
### `supportedEcmaVersions`
Returns an array of all supported ECMAScript versions
## Options
```js
const options = {
// attach range information to each node
range: false,
// attach line/column location information to each node
loc: false,
// create a top-level comments array containing all comments
comment: false,
// create a top-level tokens array containing all tokens
tokens: false,
// Set to 3, 5 (the default), 6, 7, 8, 9, 10, 11, 12, 13, 14 or 15 to specify the version of ECMAScript syntax you want to use.
// You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), 2021 (same as 12), 2022 (same as 13), 2023 (same as 14) or 2024 (same as 15) to use the year-based naming.
// You can also set "latest" to use the most recently supported version.
ecmaVersion: 3,
allowReserved: true, // only allowed when ecmaVersion is 3
// specify which type of script you're parsing ("script", "module", or "commonjs")
sourceType: "script",
// specify additional language features
ecmaFeatures: {
// enable JSX parsing
jsx: false,
// enable return in global scope (set to true automatically when sourceType is "commonjs")
globalReturn: false,
// enable implied strict mode (if ecmaVersion >= 5)
impliedStrict: false
}
}
```
## Esprima Compatibility Going Forward
The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same.
Espree may also deviate from Esprima in the interface it exposes.
## Contributing
Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues).
Espree is licensed under a permissive BSD 2-clause license.
## Security Policy
We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md).
## Build Commands
* `npm test` - run all linting and tests
* `npm run lint` - run all linting
## Differences from Espree 2.x
* The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics.
* Trailing whitespace no longer is counted as part of a node.
* `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`.
* The `esparse` and `esvalidate` binary scripts have been removed.
* There is no `tolerant` option. We will investigate adding this back in the future.
## Known Incompatibilities
In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change.
### Esprima 1.2.2
* Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs.
* Espree does not parse `let` and `const` declarations by default.
* Error messages returned for parsing errors are different.
* There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn.
### Esprima 2.x
* Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2.
## Frequently Asked Questions
### Why another parser
[ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration.
We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API.
With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima.
### Have you tried working with Esprima?
Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support.
### Why don't you just use Acorn?
Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint.
We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better.
### What ECMAScript features do you support?
Espree supports all ECMAScript 2023 features and partially supports ECMAScript 2024 features.
Because ECMAScript 2024 is still under development, we are implementing features as they are finalized. Currently, Espree supports:
* [RegExp v flag with set notation + properties of strings](https://github.com/tc39/proposal-regexp-v-flag)
See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized.
### How do you determine which experimental features to support?
In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features.

View File

@ -0,0 +1,883 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var acorn = require('acorn');
var jsx = require('acorn-jsx');
var visitorKeys = require('eslint-visitor-keys');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var acorn__namespace = /*#__PURE__*/_interopNamespace(acorn);
var jsx__default = /*#__PURE__*/_interopDefaultLegacy(jsx);
var visitorKeys__namespace = /*#__PURE__*/_interopNamespace(visitorKeys);
/**
* @fileoverview Translates tokens between Acorn format and Esprima format.
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// none!
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
// Esprima Token Types
const Token = {
Boolean: "Boolean",
EOF: "<end>",
Identifier: "Identifier",
PrivateIdentifier: "PrivateIdentifier",
Keyword: "Keyword",
Null: "Null",
Numeric: "Numeric",
Punctuator: "Punctuator",
String: "String",
RegularExpression: "RegularExpression",
Template: "Template",
JSXIdentifier: "JSXIdentifier",
JSXText: "JSXText"
};
/**
* Converts part of a template into an Esprima token.
* @param {AcornToken[]} tokens The Acorn tokens representing the template.
* @param {string} code The source code.
* @returns {EsprimaToken} The Esprima equivalent of the template token.
* @private
*/
function convertTemplatePart(tokens, code) {
const firstToken = tokens[0],
lastTemplateToken = tokens[tokens.length - 1];
const token = {
type: Token.Template,
value: code.slice(firstToken.start, lastTemplateToken.end)
};
if (firstToken.loc) {
token.loc = {
start: firstToken.loc.start,
end: lastTemplateToken.loc.end
};
}
if (firstToken.range) {
token.start = firstToken.range[0];
token.end = lastTemplateToken.range[1];
token.range = [token.start, token.end];
}
return token;
}
/**
* Contains logic to translate Acorn tokens into Esprima tokens.
* @param {Object} acornTokTypes The Acorn token types.
* @param {string} code The source code Acorn is parsing. This is necessary
* to correct the "value" property of some tokens.
* @constructor
*/
function TokenTranslator(acornTokTypes, code) {
// token types
this._acornTokTypes = acornTokTypes;
// token buffer for templates
this._tokens = [];
// track the last curly brace
this._curlyBrace = null;
// the source code
this._code = code;
}
TokenTranslator.prototype = {
constructor: TokenTranslator,
/**
* Translates a single Esprima token to a single Acorn token. This may be
* inaccurate due to how templates are handled differently in Esprima and
* Acorn, but should be accurate for all other tokens.
* @param {AcornToken} token The Acorn token to translate.
* @param {Object} extra Espree extra object.
* @returns {EsprimaToken} The Esprima version of the token.
*/
translate(token, extra) {
const type = token.type,
tt = this._acornTokTypes;
if (type === tt.name) {
token.type = Token.Identifier;
// TODO: See if this is an Acorn bug
if (token.value === "static") {
token.type = Token.Keyword;
}
if (extra.ecmaVersion > 5 && (token.value === "yield" || token.value === "let")) {
token.type = Token.Keyword;
}
} else if (type === tt.privateId) {
token.type = Token.PrivateIdentifier;
} else if (type === tt.semi || type === tt.comma ||
type === tt.parenL || type === tt.parenR ||
type === tt.braceL || type === tt.braceR ||
type === tt.dot || type === tt.bracketL ||
type === tt.colon || type === tt.question ||
type === tt.bracketR || type === tt.ellipsis ||
type === tt.arrow || type === tt.jsxTagStart ||
type === tt.incDec || type === tt.starstar ||
type === tt.jsxTagEnd || type === tt.prefix ||
type === tt.questionDot ||
(type.binop && !type.keyword) ||
type.isAssign) {
token.type = Token.Punctuator;
token.value = this._code.slice(token.start, token.end);
} else if (type === tt.jsxName) {
token.type = Token.JSXIdentifier;
} else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) {
token.type = Token.JSXText;
} else if (type.keyword) {
if (type.keyword === "true" || type.keyword === "false") {
token.type = Token.Boolean;
} else if (type.keyword === "null") {
token.type = Token.Null;
} else {
token.type = Token.Keyword;
}
} else if (type === tt.num) {
token.type = Token.Numeric;
token.value = this._code.slice(token.start, token.end);
} else if (type === tt.string) {
if (extra.jsxAttrValueToken) {
extra.jsxAttrValueToken = false;
token.type = Token.JSXText;
} else {
token.type = Token.String;
}
token.value = this._code.slice(token.start, token.end);
} else if (type === tt.regexp) {
token.type = Token.RegularExpression;
const value = token.value;
token.regex = {
flags: value.flags,
pattern: value.pattern
};
token.value = `/${value.pattern}/${value.flags}`;
}
return token;
},
/**
* Function to call during Acorn's onToken handler.
* @param {AcornToken} token The Acorn token.
* @param {Object} extra The Espree extra object.
* @returns {void}
*/
onToken(token, extra) {
const tt = this._acornTokTypes,
tokens = extra.tokens,
templateTokens = this._tokens;
/**
* Flushes the buffered template tokens and resets the template
* tracking.
* @returns {void}
* @private
*/
const translateTemplateTokens = () => {
tokens.push(convertTemplatePart(this._tokens, this._code));
this._tokens = [];
};
if (token.type === tt.eof) {
// might be one last curlyBrace
if (this._curlyBrace) {
tokens.push(this.translate(this._curlyBrace, extra));
}
return;
}
if (token.type === tt.backQuote) {
// if there's already a curly, it's not part of the template
if (this._curlyBrace) {
tokens.push(this.translate(this._curlyBrace, extra));
this._curlyBrace = null;
}
templateTokens.push(token);
// it's the end
if (templateTokens.length > 1) {
translateTemplateTokens();
}
return;
}
if (token.type === tt.dollarBraceL) {
templateTokens.push(token);
translateTemplateTokens();
return;
}
if (token.type === tt.braceR) {
// if there's already a curly, it's not part of the template
if (this._curlyBrace) {
tokens.push(this.translate(this._curlyBrace, extra));
}
// store new curly for later
this._curlyBrace = token;
return;
}
if (token.type === tt.template || token.type === tt.invalidTemplate) {
if (this._curlyBrace) {
templateTokens.push(this._curlyBrace);
this._curlyBrace = null;
}
templateTokens.push(token);
return;
}
if (this._curlyBrace) {
tokens.push(this.translate(this._curlyBrace, extra));
this._curlyBrace = null;
}
tokens.push(this.translate(token, extra));
}
};
/**
* @fileoverview A collection of methods for processing Espree's options.
* @author Kai Cataldo
*/
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const SUPPORTED_VERSIONS = [
3,
5,
6, // 2015
7, // 2016
8, // 2017
9, // 2018
10, // 2019
11, // 2020
12, // 2021
13, // 2022
14, // 2023
15 // 2024
];
/**
* Get the latest ECMAScript version supported by Espree.
* @returns {number} The latest ECMAScript version.
*/
function getLatestEcmaVersion() {
return SUPPORTED_VERSIONS[SUPPORTED_VERSIONS.length - 1];
}
/**
* Get the list of ECMAScript versions supported by Espree.
* @returns {number[]} An array containing the supported ECMAScript versions.
*/
function getSupportedEcmaVersions() {
return [...SUPPORTED_VERSIONS];
}
/**
* Normalize ECMAScript version from the initial config
* @param {(number|"latest")} ecmaVersion ECMAScript version from the initial config
* @throws {Error} throws an error if the ecmaVersion is invalid.
* @returns {number} normalized ECMAScript version
*/
function normalizeEcmaVersion(ecmaVersion = 5) {
let version = ecmaVersion === "latest" ? getLatestEcmaVersion() : ecmaVersion;
if (typeof version !== "number") {
throw new Error(`ecmaVersion must be a number or "latest". Received value of type ${typeof ecmaVersion} instead.`);
}
// Calculate ECMAScript edition number from official year version starting with
// ES2015, which corresponds with ES6 (or a difference of 2009).
if (version >= 2015) {
version -= 2009;
}
if (!SUPPORTED_VERSIONS.includes(version)) {
throw new Error("Invalid ecmaVersion.");
}
return version;
}
/**
* Normalize sourceType from the initial config
* @param {string} sourceType to normalize
* @throws {Error} throw an error if sourceType is invalid
* @returns {string} normalized sourceType
*/
function normalizeSourceType(sourceType = "script") {
if (sourceType === "script" || sourceType === "module") {
return sourceType;
}
if (sourceType === "commonjs") {
return "script";
}
throw new Error("Invalid sourceType.");
}
/**
* Normalize parserOptions
* @param {Object} options the parser options to normalize
* @throws {Error} throw an error if found invalid option.
* @returns {Object} normalized options
*/
function normalizeOptions(options) {
const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion);
const sourceType = normalizeSourceType(options.sourceType);
const ranges = options.range === true;
const locations = options.loc === true;
if (ecmaVersion !== 3 && options.allowReserved) {
// a value of `false` is intentionally allowed here, so a shared config can overwrite it when needed
throw new Error("`allowReserved` is only supported when ecmaVersion is 3");
}
if (typeof options.allowReserved !== "undefined" && typeof options.allowReserved !== "boolean") {
throw new Error("`allowReserved`, when present, must be `true` or `false`");
}
const allowReserved = ecmaVersion === 3 ? (options.allowReserved || "never") : false;
const ecmaFeatures = options.ecmaFeatures || {};
const allowReturnOutsideFunction = options.sourceType === "commonjs" ||
Boolean(ecmaFeatures.globalReturn);
if (sourceType === "module" && ecmaVersion < 6) {
throw new Error("sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding `{ ecmaVersion: 2015 }` to the parser options.");
}
return Object.assign({}, options, {
ecmaVersion,
sourceType,
ranges,
locations,
allowReserved,
allowReturnOutsideFunction
});
}
/* eslint no-param-reassign: 0 -- stylistic choice */
const STATE = Symbol("espree's internal state");
const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode");
/**
* Converts an Acorn comment to a Esprima comment.
* @param {boolean} block True if it's a block comment, false if not.
* @param {string} text The text of the comment.
* @param {int} start The index at which the comment starts.
* @param {int} end The index at which the comment ends.
* @param {Location} startLoc The location at which the comment starts.
* @param {Location} endLoc The location at which the comment ends.
* @param {string} code The source code being parsed.
* @returns {Object} The comment object.
* @private
*/
function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code) {
let type;
if (block) {
type = "Block";
} else if (code.slice(start, start + 2) === "#!") {
type = "Hashbang";
} else {
type = "Line";
}
const comment = {
type,
value: text
};
if (typeof start === "number") {
comment.start = start;
comment.end = end;
comment.range = [start, end];
}
if (typeof startLoc === "object") {
comment.loc = {
start: startLoc,
end: endLoc
};
}
return comment;
}
var espree = () => Parser => {
const tokTypes = Object.assign({}, Parser.acorn.tokTypes);
if (Parser.acornJsx) {
Object.assign(tokTypes, Parser.acornJsx.tokTypes);
}
return class Espree extends Parser {
constructor(opts, code) {
if (typeof opts !== "object" || opts === null) {
opts = {};
}
if (typeof code !== "string" && !(code instanceof String)) {
code = String(code);
}
// save original source type in case of commonjs
const originalSourceType = opts.sourceType;
const options = normalizeOptions(opts);
const ecmaFeatures = options.ecmaFeatures || {};
const tokenTranslator =
options.tokens === true
? new TokenTranslator(tokTypes, code)
: null;
/*
* Data that is unique to Espree and is not represented internally
* in Acorn.
*
* For ES2023 hashbangs, Espree will call `onComment()` during the
* constructor, so we must define state before having access to
* `this`.
*/
const state = {
originalSourceType: originalSourceType || options.sourceType,
tokens: tokenTranslator ? [] : null,
comments: options.comment === true ? [] : null,
impliedStrict: ecmaFeatures.impliedStrict === true && options.ecmaVersion >= 5,
ecmaVersion: options.ecmaVersion,
jsxAttrValueToken: false,
lastToken: null,
templateElements: []
};
// Initialize acorn parser.
super({
// do not use spread, because we don't want to pass any unknown options to acorn
ecmaVersion: options.ecmaVersion,
sourceType: options.sourceType,
ranges: options.ranges,
locations: options.locations,
allowReserved: options.allowReserved,
// Truthy value is true for backward compatibility.
allowReturnOutsideFunction: options.allowReturnOutsideFunction,
// Collect tokens
onToken(token) {
if (tokenTranslator) {
// Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state.
tokenTranslator.onToken(token, state);
}
if (token.type !== tokTypes.eof) {
state.lastToken = token;
}
},
// Collect comments
onComment(block, text, start, end, startLoc, endLoc) {
if (state.comments) {
const comment = convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code);
state.comments.push(comment);
}
}
}, code);
/*
* We put all of this data into a symbol property as a way to avoid
* potential naming conflicts with future versions of Acorn.
*/
this[STATE] = state;
}
tokenize() {
do {
this.next();
} while (this.type !== tokTypes.eof);
// Consume the final eof token
this.next();
const extra = this[STATE];
const tokens = extra.tokens;
if (extra.comments) {
tokens.comments = extra.comments;
}
return tokens;
}
finishNode(...args) {
const result = super.finishNode(...args);
return this[ESPRIMA_FINISH_NODE](result);
}
finishNodeAt(...args) {
const result = super.finishNodeAt(...args);
return this[ESPRIMA_FINISH_NODE](result);
}
parse() {
const extra = this[STATE];
const program = super.parse();
program.sourceType = extra.originalSourceType;
if (extra.comments) {
program.comments = extra.comments;
}
if (extra.tokens) {
program.tokens = extra.tokens;
}
/*
* Adjust opening and closing position of program to match Esprima.
* Acorn always starts programs at range 0 whereas Esprima starts at the
* first AST node's start (the only real difference is when there's leading
* whitespace or leading comments). Acorn also counts trailing whitespace
* as part of the program whereas Esprima only counts up to the last token.
*/
if (program.body.length) {
const [firstNode] = program.body;
if (program.range) {
program.range[0] = firstNode.range[0];
}
if (program.loc) {
program.loc.start = firstNode.loc.start;
}
program.start = firstNode.start;
}
if (extra.lastToken) {
if (program.range) {
program.range[1] = extra.lastToken.range[1];
}
if (program.loc) {
program.loc.end = extra.lastToken.loc.end;
}
program.end = extra.lastToken.end;
}
/*
* https://github.com/eslint/espree/issues/349
* Ensure that template elements have correct range information.
* This is one location where Acorn produces a different value
* for its start and end properties vs. the values present in the
* range property. In order to avoid confusion, we set the start
* and end properties to the values that are present in range.
* This is done here, instead of in finishNode(), because Acorn
* uses the values of start and end internally while parsing, making
* it dangerous to change those values while parsing is ongoing.
* By waiting until the end of parsing, we can safely change these
* values without affect any other part of the process.
*/
this[STATE].templateElements.forEach(templateElement => {
const startOffset = -1;
const endOffset = templateElement.tail ? 1 : 2;
templateElement.start += startOffset;
templateElement.end += endOffset;
if (templateElement.range) {
templateElement.range[0] += startOffset;
templateElement.range[1] += endOffset;
}
if (templateElement.loc) {
templateElement.loc.start.column += startOffset;
templateElement.loc.end.column += endOffset;
}
});
return program;
}
parseTopLevel(node) {
if (this[STATE].impliedStrict) {
this.strict = true;
}
return super.parseTopLevel(node);
}
/**
* Overwrites the default raise method to throw Esprima-style errors.
* @param {int} pos The position of the error.
* @param {string} message The error message.
* @throws {SyntaxError} A syntax error.
* @returns {void}
*/
raise(pos, message) {
const loc = Parser.acorn.getLineInfo(this.input, pos);
const err = new SyntaxError(message);
err.index = pos;
err.lineNumber = loc.line;
err.column = loc.column + 1; // acorn uses 0-based columns
throw err;
}
/**
* Overwrites the default raise method to throw Esprima-style errors.
* @param {int} pos The position of the error.
* @param {string} message The error message.
* @throws {SyntaxError} A syntax error.
* @returns {void}
*/
raiseRecoverable(pos, message) {
this.raise(pos, message);
}
/**
* Overwrites the default unexpected method to throw Esprima-style errors.
* @param {int} pos The position of the error.
* @throws {SyntaxError} A syntax error.
* @returns {void}
*/
unexpected(pos) {
let message = "Unexpected token";
if (pos !== null && pos !== void 0) {
this.pos = pos;
if (this.options.locations) {
while (this.pos < this.lineStart) {
this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1;
--this.curLine;
}
}
this.nextToken();
}
if (this.end > this.start) {
message += ` ${this.input.slice(this.start, this.end)}`;
}
this.raise(this.start, message);
}
/*
* Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX
* uses regular tt.string without any distinction between this and regular JS
* strings. As such, we intercept an attempt to read a JSX string and set a flag
* on extra so that when tokens are converted, the next token will be switched
* to JSXText via onToken.
*/
jsx_readString(quote) { // eslint-disable-line camelcase -- required by API
const result = super.jsx_readString(quote);
if (this.type === tokTypes.string) {
this[STATE].jsxAttrValueToken = true;
}
return result;
}
/**
* Performs last-minute Esprima-specific compatibility checks and fixes.
* @param {ASTNode} result The node to check.
* @returns {ASTNode} The finished node.
*/
[ESPRIMA_FINISH_NODE](result) {
// Acorn doesn't count the opening and closing backticks as part of templates
// so we have to adjust ranges/locations appropriately.
if (result.type === "TemplateElement") {
// save template element references to fix start/end later
this[STATE].templateElements.push(result);
}
if (result.type.includes("Function") && !result.generator) {
result.generator = false;
}
return result;
}
};
};
const version$1 = "9.6.1";
/* eslint-disable jsdoc/no-multi-asterisks -- needed to preserve original formatting of licences */
// To initialize lazily.
const parsers = {
_regular: null,
_jsx: null,
get regular() {
if (this._regular === null) {
this._regular = acorn__namespace.Parser.extend(espree());
}
return this._regular;
},
get jsx() {
if (this._jsx === null) {
this._jsx = acorn__namespace.Parser.extend(jsx__default["default"](), espree());
}
return this._jsx;
},
get(options) {
const useJsx = Boolean(
options &&
options.ecmaFeatures &&
options.ecmaFeatures.jsx
);
return useJsx ? this.jsx : this.regular;
}
};
//------------------------------------------------------------------------------
// Tokenizer
//------------------------------------------------------------------------------
/**
* Tokenizes the given code.
* @param {string} code The code to tokenize.
* @param {Object} options Options defining how to tokenize.
* @returns {Token[]} An array of tokens.
* @throws {SyntaxError} If the input code is invalid.
* @private
*/
function tokenize(code, options) {
const Parser = parsers.get(options);
// Ensure to collect tokens.
if (!options || options.tokens !== true) {
options = Object.assign({}, options, { tokens: true }); // eslint-disable-line no-param-reassign -- stylistic choice
}
return new Parser(options, code).tokenize();
}
//------------------------------------------------------------------------------
// Parser
//------------------------------------------------------------------------------
/**
* Parses the given code.
* @param {string} code The code to tokenize.
* @param {Object} options Options defining how to tokenize.
* @returns {ASTNode} The "Program" AST node.
* @throws {SyntaxError} If the input code is invalid.
*/
function parse(code, options) {
const Parser = parsers.get(options);
return new Parser(options, code).parse();
}
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
const version = version$1;
const name = "espree";
/* istanbul ignore next */
const VisitorKeys = (function() {
return visitorKeys__namespace.KEYS;
}());
// Derive node types from VisitorKeys
/* istanbul ignore next */
const Syntax = (function() {
let key,
types = {};
if (typeof Object.create === "function") {
types = Object.create(null);
}
for (key in VisitorKeys) {
if (Object.hasOwnProperty.call(VisitorKeys, key)) {
types[key] = key;
}
}
if (typeof Object.freeze === "function") {
Object.freeze(types);
}
return types;
}());
const latestEcmaVersion = getLatestEcmaVersion();
const supportedEcmaVersions = getSupportedEcmaVersions();
exports.Syntax = Syntax;
exports.VisitorKeys = VisitorKeys;
exports.latestEcmaVersion = latestEcmaVersion;
exports.name = name;
exports.parse = parse;
exports.supportedEcmaVersions = supportedEcmaVersions;
exports.tokenize = tokenize;
exports.version = version;

View File

@ -0,0 +1,177 @@
/* eslint-disable jsdoc/no-multi-asterisks -- needed to preserve original formatting of licences */
/**
* @fileoverview Main Espree file that converts Acorn into Esprima output.
*
* This file contains code from the following MIT-licensed projects:
* 1. Acorn
* 2. Babylon
* 3. Babel-ESLint
*
* This file also contains code from Esprima, which is BSD licensed.
*
* Acorn is Copyright 2012-2015 Acorn Contributors (https://github.com/marijnh/acorn/blob/master/AUTHORS)
* Babylon is Copyright 2014-2015 various contributors (https://github.com/babel/babel/blob/master/packages/babylon/AUTHORS)
* Babel-ESLint is Copyright 2014-2015 Sebastian McKenzie <sebmck@gmail.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
*
* 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 <COPYRIGHT HOLDER> 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.
*
* Esprima is Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
*
* 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 <COPYRIGHT HOLDER> 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.
*/
/* eslint-enable jsdoc/no-multi-asterisks -- needed to preserve original formatting of licences */
import * as acorn from "acorn";
import jsx from "acorn-jsx";
import espree from "./lib/espree.js";
import espreeVersion from "./lib/version.js";
import * as visitorKeys from "eslint-visitor-keys";
import { getLatestEcmaVersion, getSupportedEcmaVersions } from "./lib/options.js";
// To initialize lazily.
const parsers = {
_regular: null,
_jsx: null,
get regular() {
if (this._regular === null) {
this._regular = acorn.Parser.extend(espree());
}
return this._regular;
},
get jsx() {
if (this._jsx === null) {
this._jsx = acorn.Parser.extend(jsx(), espree());
}
return this._jsx;
},
get(options) {
const useJsx = Boolean(
options &&
options.ecmaFeatures &&
options.ecmaFeatures.jsx
);
return useJsx ? this.jsx : this.regular;
}
};
//------------------------------------------------------------------------------
// Tokenizer
//------------------------------------------------------------------------------
/**
* Tokenizes the given code.
* @param {string} code The code to tokenize.
* @param {Object} options Options defining how to tokenize.
* @returns {Token[]} An array of tokens.
* @throws {SyntaxError} If the input code is invalid.
* @private
*/
export function tokenize(code, options) {
const Parser = parsers.get(options);
// Ensure to collect tokens.
if (!options || options.tokens !== true) {
options = Object.assign({}, options, { tokens: true }); // eslint-disable-line no-param-reassign -- stylistic choice
}
return new Parser(options, code).tokenize();
}
//------------------------------------------------------------------------------
// Parser
//------------------------------------------------------------------------------
/**
* Parses the given code.
* @param {string} code The code to tokenize.
* @param {Object} options Options defining how to tokenize.
* @returns {ASTNode} The "Program" AST node.
* @throws {SyntaxError} If the input code is invalid.
*/
export function parse(code, options) {
const Parser = parsers.get(options);
return new Parser(options, code).parse();
}
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
export const version = espreeVersion;
export const name = "espree";
/* istanbul ignore next */
export const VisitorKeys = (function() {
return visitorKeys.KEYS;
}());
// Derive node types from VisitorKeys
/* istanbul ignore next */
export const Syntax = (function() {
let key,
types = {};
if (typeof Object.create === "function") {
types = Object.create(null);
}
for (key in VisitorKeys) {
if (Object.hasOwnProperty.call(VisitorKeys, key)) {
types[key] = key;
}
}
if (typeof Object.freeze === "function") {
Object.freeze(types);
}
return types;
}());
export const latestEcmaVersion = getLatestEcmaVersion();
export const supportedEcmaVersions = getSupportedEcmaVersions();

View File

@ -0,0 +1,349 @@
/* eslint no-param-reassign: 0 -- stylistic choice */
import TokenTranslator from "./token-translator.js";
import { normalizeOptions } from "./options.js";
const STATE = Symbol("espree's internal state");
const ESPRIMA_FINISH_NODE = Symbol("espree's esprimaFinishNode");
/**
* Converts an Acorn comment to a Esprima comment.
* @param {boolean} block True if it's a block comment, false if not.
* @param {string} text The text of the comment.
* @param {int} start The index at which the comment starts.
* @param {int} end The index at which the comment ends.
* @param {Location} startLoc The location at which the comment starts.
* @param {Location} endLoc The location at which the comment ends.
* @param {string} code The source code being parsed.
* @returns {Object} The comment object.
* @private
*/
function convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code) {
let type;
if (block) {
type = "Block";
} else if (code.slice(start, start + 2) === "#!") {
type = "Hashbang";
} else {
type = "Line";
}
const comment = {
type,
value: text
};
if (typeof start === "number") {
comment.start = start;
comment.end = end;
comment.range = [start, end];
}
if (typeof startLoc === "object") {
comment.loc = {
start: startLoc,
end: endLoc
};
}
return comment;
}
export default () => Parser => {
const tokTypes = Object.assign({}, Parser.acorn.tokTypes);
if (Parser.acornJsx) {
Object.assign(tokTypes, Parser.acornJsx.tokTypes);
}
return class Espree extends Parser {
constructor(opts, code) {
if (typeof opts !== "object" || opts === null) {
opts = {};
}
if (typeof code !== "string" && !(code instanceof String)) {
code = String(code);
}
// save original source type in case of commonjs
const originalSourceType = opts.sourceType;
const options = normalizeOptions(opts);
const ecmaFeatures = options.ecmaFeatures || {};
const tokenTranslator =
options.tokens === true
? new TokenTranslator(tokTypes, code)
: null;
/*
* Data that is unique to Espree and is not represented internally
* in Acorn.
*
* For ES2023 hashbangs, Espree will call `onComment()` during the
* constructor, so we must define state before having access to
* `this`.
*/
const state = {
originalSourceType: originalSourceType || options.sourceType,
tokens: tokenTranslator ? [] : null,
comments: options.comment === true ? [] : null,
impliedStrict: ecmaFeatures.impliedStrict === true && options.ecmaVersion >= 5,
ecmaVersion: options.ecmaVersion,
jsxAttrValueToken: false,
lastToken: null,
templateElements: []
};
// Initialize acorn parser.
super({
// do not use spread, because we don't want to pass any unknown options to acorn
ecmaVersion: options.ecmaVersion,
sourceType: options.sourceType,
ranges: options.ranges,
locations: options.locations,
allowReserved: options.allowReserved,
// Truthy value is true for backward compatibility.
allowReturnOutsideFunction: options.allowReturnOutsideFunction,
// Collect tokens
onToken(token) {
if (tokenTranslator) {
// Use `tokens`, `ecmaVersion`, and `jsxAttrValueToken` in the state.
tokenTranslator.onToken(token, state);
}
if (token.type !== tokTypes.eof) {
state.lastToken = token;
}
},
// Collect comments
onComment(block, text, start, end, startLoc, endLoc) {
if (state.comments) {
const comment = convertAcornCommentToEsprimaComment(block, text, start, end, startLoc, endLoc, code);
state.comments.push(comment);
}
}
}, code);
/*
* We put all of this data into a symbol property as a way to avoid
* potential naming conflicts with future versions of Acorn.
*/
this[STATE] = state;
}
tokenize() {
do {
this.next();
} while (this.type !== tokTypes.eof);
// Consume the final eof token
this.next();
const extra = this[STATE];
const tokens = extra.tokens;
if (extra.comments) {
tokens.comments = extra.comments;
}
return tokens;
}
finishNode(...args) {
const result = super.finishNode(...args);
return this[ESPRIMA_FINISH_NODE](result);
}
finishNodeAt(...args) {
const result = super.finishNodeAt(...args);
return this[ESPRIMA_FINISH_NODE](result);
}
parse() {
const extra = this[STATE];
const program = super.parse();
program.sourceType = extra.originalSourceType;
if (extra.comments) {
program.comments = extra.comments;
}
if (extra.tokens) {
program.tokens = extra.tokens;
}
/*
* Adjust opening and closing position of program to match Esprima.
* Acorn always starts programs at range 0 whereas Esprima starts at the
* first AST node's start (the only real difference is when there's leading
* whitespace or leading comments). Acorn also counts trailing whitespace
* as part of the program whereas Esprima only counts up to the last token.
*/
if (program.body.length) {
const [firstNode] = program.body;
if (program.range) {
program.range[0] = firstNode.range[0];
}
if (program.loc) {
program.loc.start = firstNode.loc.start;
}
program.start = firstNode.start;
}
if (extra.lastToken) {
if (program.range) {
program.range[1] = extra.lastToken.range[1];
}
if (program.loc) {
program.loc.end = extra.lastToken.loc.end;
}
program.end = extra.lastToken.end;
}
/*
* https://github.com/eslint/espree/issues/349
* Ensure that template elements have correct range information.
* This is one location where Acorn produces a different value
* for its start and end properties vs. the values present in the
* range property. In order to avoid confusion, we set the start
* and end properties to the values that are present in range.
* This is done here, instead of in finishNode(), because Acorn
* uses the values of start and end internally while parsing, making
* it dangerous to change those values while parsing is ongoing.
* By waiting until the end of parsing, we can safely change these
* values without affect any other part of the process.
*/
this[STATE].templateElements.forEach(templateElement => {
const startOffset = -1;
const endOffset = templateElement.tail ? 1 : 2;
templateElement.start += startOffset;
templateElement.end += endOffset;
if (templateElement.range) {
templateElement.range[0] += startOffset;
templateElement.range[1] += endOffset;
}
if (templateElement.loc) {
templateElement.loc.start.column += startOffset;
templateElement.loc.end.column += endOffset;
}
});
return program;
}
parseTopLevel(node) {
if (this[STATE].impliedStrict) {
this.strict = true;
}
return super.parseTopLevel(node);
}
/**
* Overwrites the default raise method to throw Esprima-style errors.
* @param {int} pos The position of the error.
* @param {string} message The error message.
* @throws {SyntaxError} A syntax error.
* @returns {void}
*/
raise(pos, message) {
const loc = Parser.acorn.getLineInfo(this.input, pos);
const err = new SyntaxError(message);
err.index = pos;
err.lineNumber = loc.line;
err.column = loc.column + 1; // acorn uses 0-based columns
throw err;
}
/**
* Overwrites the default raise method to throw Esprima-style errors.
* @param {int} pos The position of the error.
* @param {string} message The error message.
* @throws {SyntaxError} A syntax error.
* @returns {void}
*/
raiseRecoverable(pos, message) {
this.raise(pos, message);
}
/**
* Overwrites the default unexpected method to throw Esprima-style errors.
* @param {int} pos The position of the error.
* @throws {SyntaxError} A syntax error.
* @returns {void}
*/
unexpected(pos) {
let message = "Unexpected token";
if (pos !== null && pos !== void 0) {
this.pos = pos;
if (this.options.locations) {
while (this.pos < this.lineStart) {
this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1;
--this.curLine;
}
}
this.nextToken();
}
if (this.end > this.start) {
message += ` ${this.input.slice(this.start, this.end)}`;
}
this.raise(this.start, message);
}
/*
* Esprima-FB represents JSX strings as tokens called "JSXText", but Acorn-JSX
* uses regular tt.string without any distinction between this and regular JS
* strings. As such, we intercept an attempt to read a JSX string and set a flag
* on extra so that when tokens are converted, the next token will be switched
* to JSXText via onToken.
*/
jsx_readString(quote) { // eslint-disable-line camelcase -- required by API
const result = super.jsx_readString(quote);
if (this.type === tokTypes.string) {
this[STATE].jsxAttrValueToken = true;
}
return result;
}
/**
* Performs last-minute Esprima-specific compatibility checks and fixes.
* @param {ASTNode} result The node to check.
* @returns {ASTNode} The finished node.
*/
[ESPRIMA_FINISH_NODE](result) {
// Acorn doesn't count the opening and closing backticks as part of templates
// so we have to adjust ranges/locations appropriately.
if (result.type === "TemplateElement") {
// save template element references to fix start/end later
this[STATE].templateElements.push(result);
}
if (result.type.includes("Function") && !result.generator) {
result.generator = false;
}
return result;
}
};
};

View File

@ -0,0 +1,27 @@
/**
* @fileoverview The list of feature flags supported by the parser and their default
* settings.
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// None!
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
export default {
// React JSX parsing
jsx: false,
// allow return statement in global scope
globalReturn: false,
// allow implied strict mode
impliedStrict: false
};

View File

@ -0,0 +1,123 @@
/**
* @fileoverview A collection of methods for processing Espree's options.
* @author Kai Cataldo
*/
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const SUPPORTED_VERSIONS = [
3,
5,
6, // 2015
7, // 2016
8, // 2017
9, // 2018
10, // 2019
11, // 2020
12, // 2021
13, // 2022
14, // 2023
15 // 2024
];
/**
* Get the latest ECMAScript version supported by Espree.
* @returns {number} The latest ECMAScript version.
*/
export function getLatestEcmaVersion() {
return SUPPORTED_VERSIONS[SUPPORTED_VERSIONS.length - 1];
}
/**
* Get the list of ECMAScript versions supported by Espree.
* @returns {number[]} An array containing the supported ECMAScript versions.
*/
export function getSupportedEcmaVersions() {
return [...SUPPORTED_VERSIONS];
}
/**
* Normalize ECMAScript version from the initial config
* @param {(number|"latest")} ecmaVersion ECMAScript version from the initial config
* @throws {Error} throws an error if the ecmaVersion is invalid.
* @returns {number} normalized ECMAScript version
*/
function normalizeEcmaVersion(ecmaVersion = 5) {
let version = ecmaVersion === "latest" ? getLatestEcmaVersion() : ecmaVersion;
if (typeof version !== "number") {
throw new Error(`ecmaVersion must be a number or "latest". Received value of type ${typeof ecmaVersion} instead.`);
}
// Calculate ECMAScript edition number from official year version starting with
// ES2015, which corresponds with ES6 (or a difference of 2009).
if (version >= 2015) {
version -= 2009;
}
if (!SUPPORTED_VERSIONS.includes(version)) {
throw new Error("Invalid ecmaVersion.");
}
return version;
}
/**
* Normalize sourceType from the initial config
* @param {string} sourceType to normalize
* @throws {Error} throw an error if sourceType is invalid
* @returns {string} normalized sourceType
*/
function normalizeSourceType(sourceType = "script") {
if (sourceType === "script" || sourceType === "module") {
return sourceType;
}
if (sourceType === "commonjs") {
return "script";
}
throw new Error("Invalid sourceType.");
}
/**
* Normalize parserOptions
* @param {Object} options the parser options to normalize
* @throws {Error} throw an error if found invalid option.
* @returns {Object} normalized options
*/
export function normalizeOptions(options) {
const ecmaVersion = normalizeEcmaVersion(options.ecmaVersion);
const sourceType = normalizeSourceType(options.sourceType);
const ranges = options.range === true;
const locations = options.loc === true;
if (ecmaVersion !== 3 && options.allowReserved) {
// a value of `false` is intentionally allowed here, so a shared config can overwrite it when needed
throw new Error("`allowReserved` is only supported when ecmaVersion is 3");
}
if (typeof options.allowReserved !== "undefined" && typeof options.allowReserved !== "boolean") {
throw new Error("`allowReserved`, when present, must be `true` or `false`");
}
const allowReserved = ecmaVersion === 3 ? (options.allowReserved || "never") : false;
const ecmaFeatures = options.ecmaFeatures || {};
const allowReturnOutsideFunction = options.sourceType === "commonjs" ||
Boolean(ecmaFeatures.globalReturn);
if (sourceType === "module" && ecmaVersion < 6) {
throw new Error("sourceType 'module' is not supported when ecmaVersion < 2015. Consider adding `{ ecmaVersion: 2015 }` to the parser options.");
}
return Object.assign({}, options, {
ecmaVersion,
sourceType,
ranges,
locations,
allowReserved,
allowReturnOutsideFunction
});
}

View File

@ -0,0 +1,263 @@
/**
* @fileoverview Translates tokens between Acorn format and Esprima format.
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
// none!
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
// Esprima Token Types
const Token = {
Boolean: "Boolean",
EOF: "<end>",
Identifier: "Identifier",
PrivateIdentifier: "PrivateIdentifier",
Keyword: "Keyword",
Null: "Null",
Numeric: "Numeric",
Punctuator: "Punctuator",
String: "String",
RegularExpression: "RegularExpression",
Template: "Template",
JSXIdentifier: "JSXIdentifier",
JSXText: "JSXText"
};
/**
* Converts part of a template into an Esprima token.
* @param {AcornToken[]} tokens The Acorn tokens representing the template.
* @param {string} code The source code.
* @returns {EsprimaToken} The Esprima equivalent of the template token.
* @private
*/
function convertTemplatePart(tokens, code) {
const firstToken = tokens[0],
lastTemplateToken = tokens[tokens.length - 1];
const token = {
type: Token.Template,
value: code.slice(firstToken.start, lastTemplateToken.end)
};
if (firstToken.loc) {
token.loc = {
start: firstToken.loc.start,
end: lastTemplateToken.loc.end
};
}
if (firstToken.range) {
token.start = firstToken.range[0];
token.end = lastTemplateToken.range[1];
token.range = [token.start, token.end];
}
return token;
}
/**
* Contains logic to translate Acorn tokens into Esprima tokens.
* @param {Object} acornTokTypes The Acorn token types.
* @param {string} code The source code Acorn is parsing. This is necessary
* to correct the "value" property of some tokens.
* @constructor
*/
function TokenTranslator(acornTokTypes, code) {
// token types
this._acornTokTypes = acornTokTypes;
// token buffer for templates
this._tokens = [];
// track the last curly brace
this._curlyBrace = null;
// the source code
this._code = code;
}
TokenTranslator.prototype = {
constructor: TokenTranslator,
/**
* Translates a single Esprima token to a single Acorn token. This may be
* inaccurate due to how templates are handled differently in Esprima and
* Acorn, but should be accurate for all other tokens.
* @param {AcornToken} token The Acorn token to translate.
* @param {Object} extra Espree extra object.
* @returns {EsprimaToken} The Esprima version of the token.
*/
translate(token, extra) {
const type = token.type,
tt = this._acornTokTypes;
if (type === tt.name) {
token.type = Token.Identifier;
// TODO: See if this is an Acorn bug
if (token.value === "static") {
token.type = Token.Keyword;
}
if (extra.ecmaVersion > 5 && (token.value === "yield" || token.value === "let")) {
token.type = Token.Keyword;
}
} else if (type === tt.privateId) {
token.type = Token.PrivateIdentifier;
} else if (type === tt.semi || type === tt.comma ||
type === tt.parenL || type === tt.parenR ||
type === tt.braceL || type === tt.braceR ||
type === tt.dot || type === tt.bracketL ||
type === tt.colon || type === tt.question ||
type === tt.bracketR || type === tt.ellipsis ||
type === tt.arrow || type === tt.jsxTagStart ||
type === tt.incDec || type === tt.starstar ||
type === tt.jsxTagEnd || type === tt.prefix ||
type === tt.questionDot ||
(type.binop && !type.keyword) ||
type.isAssign) {
token.type = Token.Punctuator;
token.value = this._code.slice(token.start, token.end);
} else if (type === tt.jsxName) {
token.type = Token.JSXIdentifier;
} else if (type.label === "jsxText" || type === tt.jsxAttrValueToken) {
token.type = Token.JSXText;
} else if (type.keyword) {
if (type.keyword === "true" || type.keyword === "false") {
token.type = Token.Boolean;
} else if (type.keyword === "null") {
token.type = Token.Null;
} else {
token.type = Token.Keyword;
}
} else if (type === tt.num) {
token.type = Token.Numeric;
token.value = this._code.slice(token.start, token.end);
} else if (type === tt.string) {
if (extra.jsxAttrValueToken) {
extra.jsxAttrValueToken = false;
token.type = Token.JSXText;
} else {
token.type = Token.String;
}
token.value = this._code.slice(token.start, token.end);
} else if (type === tt.regexp) {
token.type = Token.RegularExpression;
const value = token.value;
token.regex = {
flags: value.flags,
pattern: value.pattern
};
token.value = `/${value.pattern}/${value.flags}`;
}
return token;
},
/**
* Function to call during Acorn's onToken handler.
* @param {AcornToken} token The Acorn token.
* @param {Object} extra The Espree extra object.
* @returns {void}
*/
onToken(token, extra) {
const tt = this._acornTokTypes,
tokens = extra.tokens,
templateTokens = this._tokens;
/**
* Flushes the buffered template tokens and resets the template
* tracking.
* @returns {void}
* @private
*/
const translateTemplateTokens = () => {
tokens.push(convertTemplatePart(this._tokens, this._code));
this._tokens = [];
};
if (token.type === tt.eof) {
// might be one last curlyBrace
if (this._curlyBrace) {
tokens.push(this.translate(this._curlyBrace, extra));
}
return;
}
if (token.type === tt.backQuote) {
// if there's already a curly, it's not part of the template
if (this._curlyBrace) {
tokens.push(this.translate(this._curlyBrace, extra));
this._curlyBrace = null;
}
templateTokens.push(token);
// it's the end
if (templateTokens.length > 1) {
translateTemplateTokens();
}
return;
}
if (token.type === tt.dollarBraceL) {
templateTokens.push(token);
translateTemplateTokens();
return;
}
if (token.type === tt.braceR) {
// if there's already a curly, it's not part of the template
if (this._curlyBrace) {
tokens.push(this.translate(this._curlyBrace, extra));
}
// store new curly for later
this._curlyBrace = token;
return;
}
if (token.type === tt.template || token.type === tt.invalidTemplate) {
if (this._curlyBrace) {
templateTokens.push(this._curlyBrace);
this._curlyBrace = null;
}
templateTokens.push(token);
return;
}
if (this._curlyBrace) {
tokens.push(this.translate(this._curlyBrace, extra));
this._curlyBrace = null;
}
tokens.push(this.translate(token, extra));
}
};
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
export default TokenTranslator;

View File

@ -0,0 +1,3 @@
const version = "9.6.1";
export default version;

View File

@ -0,0 +1,88 @@
{
"name": "espree",
"description": "An Esprima-compatible JavaScript parser built on Acorn",
"author": "Nicholas C. Zakas <nicholas+npm@nczconsulting.com>",
"homepage": "https://github.com/eslint/espree",
"main": "dist/espree.cjs",
"type": "module",
"exports": {
".": [
{
"import": "./espree.js",
"require": "./dist/espree.cjs",
"default": "./dist/espree.cjs"
},
"./dist/espree.cjs"
],
"./package.json": "./package.json"
},
"version": "9.6.1",
"files": [
"lib",
"dist/espree.cjs",
"espree.js"
],
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"repository": "eslint/espree",
"bugs": {
"url": "https://github.com/eslint/espree/issues"
},
"funding": "https://opencollective.com/eslint",
"license": "BSD-2-Clause",
"dependencies": {
"acorn": "^8.9.0",
"acorn-jsx": "^5.3.2",
"eslint-visitor-keys": "^3.4.1"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^17.1.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^11.2.0",
"c8": "^7.11.0",
"chai": "^4.3.6",
"eslint": "^8.44.0",
"eslint-config-eslint": "^8.0.0",
"eslint-plugin-n": "^16.0.0",
"eslint-release": "^3.2.0",
"esprima-fb": "^8001.2001.0-dev-harmony-fb",
"globals": "^13.20.0",
"lint-staged": "^13.2.0",
"mocha": "^9.2.2",
"npm-run-all": "^4.1.5",
"rollup": "^2.41.2",
"shelljs": "^0.3.0",
"yorkie": "^2.0.0"
},
"keywords": [
"ast",
"ecmascript",
"javascript",
"parser",
"syntax",
"acorn"
],
"gitHooks": {
"pre-commit": "lint-staged"
},
"scripts": {
"unit": "npm-run-all -s unit:*",
"unit:esm": "c8 mocha --color --reporter progress --timeout 30000 'tests/lib/**/*.js'",
"unit:cjs": "mocha --color --reporter progress --timeout 30000 tests/lib/commonjs.cjs",
"test": "npm-run-all -p unit lint",
"lint": "eslint . --report-unused-disable-directives",
"fixlint": "npm run lint -- --fix",
"build": "rollup -c rollup.config.js",
"build:debug": "npm run build -- -m",
"update-version": "node tools/update-version.js",
"pretest": "npm run build",
"prepublishOnly": "npm run update-version && npm run build",
"sync-docs": "node sync-docs.js",
"generate-release": "eslint-generate-release",
"generate-alpharelease": "eslint-generate-prerelease alpha",
"generate-betarelease": "eslint-generate-prerelease beta",
"generate-rcrelease": "eslint-generate-prerelease rc",
"publish-release": "eslint-publish-release"
}
}

View File

@ -0,0 +1,16 @@
{
"curly": true,
"eqeqeq": true,
"immed": true,
"eqnull": true,
"latedef": true,
"noarg": true,
"noempty": true,
"quotmark": "single",
"undef": true,
"unused": true,
"strict": true,
"trailing": true,
"node": true
}

View File

@ -0,0 +1,19 @@
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.

View File

@ -0,0 +1,153 @@
### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse)
Estraverse ([estraverse](http://github.com/estools/estraverse)) is
[ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
traversal functions from [esmangle project](http://github.com/estools/esmangle).
### Documentation
You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage).
### Example Usage
The following code will output all variables declared at the root of a file.
```javascript
estraverse.traverse(ast, {
enter: function (node, parent) {
if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration')
return estraverse.VisitorOption.Skip;
},
leave: function (node, parent) {
if (node.type == 'VariableDeclarator')
console.log(node.id.name);
}
});
```
We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break.
```javascript
estraverse.traverse(ast, {
enter: function (node) {
this.break();
}
});
```
And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it.
```javascript
result = estraverse.replace(tree, {
enter: function (node) {
// Replace it with replaced.
if (node.type === 'Literal')
return replaced;
}
});
```
By passing `visitor.keys` mapping, we can extend estraverse traversing functionality.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Extending the existing traversing rules.
keys: {
// TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ]
TestExpression: ['argument']
}
});
```
By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Iterating the child **nodes** of unknown nodes.
fallback: 'iteration'
});
```
When `visitor.fallback` is a function, we can determine which keys to visit on each node.
```javascript
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Skip the `argument` property of each node
fallback: function(node) {
return Object.keys(node).filter(function(key) {
return key !== 'argument';
});
}
});
```
### License
Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation)
(twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.

View File

@ -0,0 +1,805 @@
/*
Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.
*/
/*jslint vars:false, bitwise:true*/
/*jshint indent:4*/
/*global exports:true*/
(function clone(exports) {
'use strict';
var Syntax,
VisitorOption,
VisitorKeys,
BREAK,
SKIP,
REMOVE;
function deepCopy(obj) {
var ret = {}, key, val;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
val = obj[key];
if (typeof val === 'object' && val !== null) {
ret[key] = deepCopy(val);
} else {
ret[key] = val;
}
}
}
return ret;
}
// based on LLVM libc++ upper_bound / lower_bound
// MIT License
function upperBound(array, func) {
var diff, len, i, current;
len = array.length;
i = 0;
while (len) {
diff = len >>> 1;
current = i + diff;
if (func(array[current])) {
len = diff;
} else {
i = current + 1;
len -= diff + 1;
}
}
return i;
}
Syntax = {
AssignmentExpression: 'AssignmentExpression',
AssignmentPattern: 'AssignmentPattern',
ArrayExpression: 'ArrayExpression',
ArrayPattern: 'ArrayPattern',
ArrowFunctionExpression: 'ArrowFunctionExpression',
AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.
BlockStatement: 'BlockStatement',
BinaryExpression: 'BinaryExpression',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ChainExpression: 'ChainExpression',
ClassBody: 'ClassBody',
ClassDeclaration: 'ClassDeclaration',
ClassExpression: 'ClassExpression',
ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.
ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DebuggerStatement: 'DebuggerStatement',
DirectiveStatement: 'DirectiveStatement',
DoWhileStatement: 'DoWhileStatement',
EmptyStatement: 'EmptyStatement',
ExportAllDeclaration: 'ExportAllDeclaration',
ExportDefaultDeclaration: 'ExportDefaultDeclaration',
ExportNamedDeclaration: 'ExportNamedDeclaration',
ExportSpecifier: 'ExportSpecifier',
ExpressionStatement: 'ExpressionStatement',
ForStatement: 'ForStatement',
ForInStatement: 'ForInStatement',
ForOfStatement: 'ForOfStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.
Identifier: 'Identifier',
IfStatement: 'IfStatement',
ImportExpression: 'ImportExpression',
ImportDeclaration: 'ImportDeclaration',
ImportDefaultSpecifier: 'ImportDefaultSpecifier',
ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
ImportSpecifier: 'ImportSpecifier',
Literal: 'Literal',
LabeledStatement: 'LabeledStatement',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
MetaProperty: 'MetaProperty',
MethodDefinition: 'MethodDefinition',
ModuleSpecifier: 'ModuleSpecifier',
NewExpression: 'NewExpression',
ObjectExpression: 'ObjectExpression',
ObjectPattern: 'ObjectPattern',
PrivateIdentifier: 'PrivateIdentifier',
Program: 'Program',
Property: 'Property',
PropertyDefinition: 'PropertyDefinition',
RestElement: 'RestElement',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SpreadElement: 'SpreadElement',
Super: 'Super',
SwitchStatement: 'SwitchStatement',
SwitchCase: 'SwitchCase',
TaggedTemplateExpression: 'TaggedTemplateExpression',
TemplateElement: 'TemplateElement',
TemplateLiteral: 'TemplateLiteral',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TryStatement: 'TryStatement',
UnaryExpression: 'UnaryExpression',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement',
YieldExpression: 'YieldExpression'
};
VisitorKeys = {
AssignmentExpression: ['left', 'right'],
AssignmentPattern: ['left', 'right'],
ArrayExpression: ['elements'],
ArrayPattern: ['elements'],
ArrowFunctionExpression: ['params', 'body'],
AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.
BlockStatement: ['body'],
BinaryExpression: ['left', 'right'],
BreakStatement: ['label'],
CallExpression: ['callee', 'arguments'],
CatchClause: ['param', 'body'],
ChainExpression: ['expression'],
ClassBody: ['body'],
ClassDeclaration: ['id', 'superClass', 'body'],
ClassExpression: ['id', 'superClass', 'body'],
ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.
ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
ConditionalExpression: ['test', 'consequent', 'alternate'],
ContinueStatement: ['label'],
DebuggerStatement: [],
DirectiveStatement: [],
DoWhileStatement: ['body', 'test'],
EmptyStatement: [],
ExportAllDeclaration: ['source'],
ExportDefaultDeclaration: ['declaration'],
ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
ExportSpecifier: ['exported', 'local'],
ExpressionStatement: ['expression'],
ForStatement: ['init', 'test', 'update', 'body'],
ForInStatement: ['left', 'right', 'body'],
ForOfStatement: ['left', 'right', 'body'],
FunctionDeclaration: ['id', 'params', 'body'],
FunctionExpression: ['id', 'params', 'body'],
GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
Identifier: [],
IfStatement: ['test', 'consequent', 'alternate'],
ImportExpression: ['source'],
ImportDeclaration: ['specifiers', 'source'],
ImportDefaultSpecifier: ['local'],
ImportNamespaceSpecifier: ['local'],
ImportSpecifier: ['imported', 'local'],
Literal: [],
LabeledStatement: ['label', 'body'],
LogicalExpression: ['left', 'right'],
MemberExpression: ['object', 'property'],
MetaProperty: ['meta', 'property'],
MethodDefinition: ['key', 'value'],
ModuleSpecifier: [],
NewExpression: ['callee', 'arguments'],
ObjectExpression: ['properties'],
ObjectPattern: ['properties'],
PrivateIdentifier: [],
Program: ['body'],
Property: ['key', 'value'],
PropertyDefinition: ['key', 'value'],
RestElement: [ 'argument' ],
ReturnStatement: ['argument'],
SequenceExpression: ['expressions'],
SpreadElement: ['argument'],
Super: [],
SwitchStatement: ['discriminant', 'cases'],
SwitchCase: ['test', 'consequent'],
TaggedTemplateExpression: ['tag', 'quasi'],
TemplateElement: [],
TemplateLiteral: ['quasis', 'expressions'],
ThisExpression: [],
ThrowStatement: ['argument'],
TryStatement: ['block', 'handler', 'finalizer'],
UnaryExpression: ['argument'],
UpdateExpression: ['argument'],
VariableDeclaration: ['declarations'],
VariableDeclarator: ['id', 'init'],
WhileStatement: ['test', 'body'],
WithStatement: ['object', 'body'],
YieldExpression: ['argument']
};
// unique id
BREAK = {};
SKIP = {};
REMOVE = {};
VisitorOption = {
Break: BREAK,
Skip: SKIP,
Remove: REMOVE
};
function Reference(parent, key) {
this.parent = parent;
this.key = key;
}
Reference.prototype.replace = function replace(node) {
this.parent[this.key] = node;
};
Reference.prototype.remove = function remove() {
if (Array.isArray(this.parent)) {
this.parent.splice(this.key, 1);
return true;
} else {
this.replace(null);
return false;
}
};
function Element(node, path, wrap, ref) {
this.node = node;
this.path = path;
this.wrap = wrap;
this.ref = ref;
}
function Controller() { }
// API:
// return property path array from root to current node
Controller.prototype.path = function path() {
var i, iz, j, jz, result, element;
function addToPath(result, path) {
if (Array.isArray(path)) {
for (j = 0, jz = path.length; j < jz; ++j) {
result.push(path[j]);
}
} else {
result.push(path);
}
}
// root node
if (!this.__current.path) {
return null;
}
// first node is sentinel, second node is root element
result = [];
for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
element = this.__leavelist[i];
addToPath(result, element.path);
}
addToPath(result, this.__current.path);
return result;
};
// API:
// return type of current node
Controller.prototype.type = function () {
var node = this.current();
return node.type || this.__current.wrap;
};
// API:
// return array of parent elements
Controller.prototype.parents = function parents() {
var i, iz, result;
// first node is sentinel
result = [];
for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
result.push(this.__leavelist[i].node);
}
return result;
};
// API:
// return current node
Controller.prototype.current = function current() {
return this.__current.node;
};
Controller.prototype.__execute = function __execute(callback, element) {
var previous, result;
result = undefined;
previous = this.__current;
this.__current = element;
this.__state = null;
if (callback) {
result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
}
this.__current = previous;
return result;
};
// API:
// notify control skip / break
Controller.prototype.notify = function notify(flag) {
this.__state = flag;
};
// API:
// skip child nodes of current node
Controller.prototype.skip = function () {
this.notify(SKIP);
};
// API:
// break traversals
Controller.prototype['break'] = function () {
this.notify(BREAK);
};
// API:
// remove node
Controller.prototype.remove = function () {
this.notify(REMOVE);
};
Controller.prototype.__initialize = function(root, visitor) {
this.visitor = visitor;
this.root = root;
this.__worklist = [];
this.__leavelist = [];
this.__current = null;
this.__state = null;
this.__fallback = null;
if (visitor.fallback === 'iteration') {
this.__fallback = Object.keys;
} else if (typeof visitor.fallback === 'function') {
this.__fallback = visitor.fallback;
}
this.__keys = VisitorKeys;
if (visitor.keys) {
this.__keys = Object.assign(Object.create(this.__keys), visitor.keys);
}
};
function isNode(node) {
if (node == null) {
return false;
}
return typeof node === 'object' && typeof node.type === 'string';
}
function isProperty(nodeType, key) {
return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
}
function candidateExistsInLeaveList(leavelist, candidate) {
for (var i = leavelist.length - 1; i >= 0; --i) {
if (leavelist[i].node === candidate) {
return true;
}
}
return false;
}
Controller.prototype.traverse = function traverse(root, visitor) {
var worklist,
leavelist,
element,
node,
nodeType,
ret,
key,
current,
current2,
candidates,
candidate,
sentinel;
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
// initialize
worklist.push(new Element(root, null, null, null));
leavelist.push(new Element(null, null, null, null));
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
ret = this.__execute(visitor.leave, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
continue;
}
if (element.node) {
ret = this.__execute(visitor.enter, element);
if (this.__state === BREAK || ret === BREAK) {
return;
}
worklist.push(sentinel);
leavelist.push(element);
if (this.__state === SKIP || ret === SKIP) {
continue;
}
node = element.node;
nodeType = node.type || element.wrap;
candidates = this.__keys[nodeType];
if (!candidates) {
if (this.__fallback) {
candidates = this.__fallback(node);
} else {
throw new Error('Unknown node type ' + nodeType + '.');
}
}
current = candidates.length;
while ((current -= 1) >= 0) {
key = candidates[current];
candidate = node[key];
if (!candidate) {
continue;
}
if (Array.isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {
continue;
}
if (candidateExistsInLeaveList(leavelist, candidate[current2])) {
continue;
}
if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', null);
} else if (isNode(candidate[current2])) {
element = new Element(candidate[current2], [key, current2], null, null);
} else {
continue;
}
worklist.push(element);
}
} else if (isNode(candidate)) {
if (candidateExistsInLeaveList(leavelist, candidate)) {
continue;
}
worklist.push(new Element(candidate, key, null, null));
}
}
}
}
};
Controller.prototype.replace = function replace(root, visitor) {
var worklist,
leavelist,
node,
nodeType,
target,
element,
current,
current2,
candidates,
candidate,
sentinel,
outer,
key;
function removeElem(element) {
var i,
key,
nextElem,
parent;
if (element.ref.remove()) {
// When the reference is an element of an array.
key = element.ref.key;
parent = element.ref.parent;
// If removed from array, then decrease following items' keys.
i = worklist.length;
while (i--) {
nextElem = worklist[i];
if (nextElem.ref && nextElem.ref.parent === parent) {
if (nextElem.ref.key < key) {
break;
}
--nextElem.ref.key;
}
}
}
}
this.__initialize(root, visitor);
sentinel = {};
// reference
worklist = this.__worklist;
leavelist = this.__leavelist;
// initialize
outer = {
root: root
};
element = new Element(root, null, null, new Reference(outer, 'root'));
worklist.push(element);
leavelist.push(element);
while (worklist.length) {
element = worklist.pop();
if (element === sentinel) {
element = leavelist.pop();
target = this.__execute(visitor.leave, element);
// node may be replaced with null,
// so distinguish between undefined and null in this place
if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
// replace
element.ref.replace(target);
}
if (this.__state === REMOVE || target === REMOVE) {
removeElem(element);
}
if (this.__state === BREAK || target === BREAK) {
return outer.root;
}
continue;
}
target = this.__execute(visitor.enter, element);
// node may be replaced with null,
// so distinguish between undefined and null in this place
if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
// replace
element.ref.replace(target);
element.node = target;
}
if (this.__state === REMOVE || target === REMOVE) {
removeElem(element);
element.node = null;
}
if (this.__state === BREAK || target === BREAK) {
return outer.root;
}
// node may be null
node = element.node;
if (!node) {
continue;
}
worklist.push(sentinel);
leavelist.push(element);
if (this.__state === SKIP || target === SKIP) {
continue;
}
nodeType = node.type || element.wrap;
candidates = this.__keys[nodeType];
if (!candidates) {
if (this.__fallback) {
candidates = this.__fallback(node);
} else {
throw new Error('Unknown node type ' + nodeType + '.');
}
}
current = candidates.length;
while ((current -= 1) >= 0) {
key = candidates[current];
candidate = node[key];
if (!candidate) {
continue;
}
if (Array.isArray(candidate)) {
current2 = candidate.length;
while ((current2 -= 1) >= 0) {
if (!candidate[current2]) {
continue;
}
if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
} else if (isNode(candidate[current2])) {
element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
} else {
continue;
}
worklist.push(element);
}
} else if (isNode(candidate)) {
worklist.push(new Element(candidate, key, null, new Reference(node, key)));
}
}
}
return outer.root;
};
function traverse(root, visitor) {
var controller = new Controller();
return controller.traverse(root, visitor);
}
function replace(root, visitor) {
var controller = new Controller();
return controller.replace(root, visitor);
}
function extendCommentRange(comment, tokens) {
var target;
target = upperBound(tokens, function search(token) {
return token.range[0] > comment.range[0];
});
comment.extendedRange = [comment.range[0], comment.range[1]];
if (target !== tokens.length) {
comment.extendedRange[1] = tokens[target].range[0];
}
target -= 1;
if (target >= 0) {
comment.extendedRange[0] = tokens[target].range[1];
}
return comment;
}
function attachComments(tree, providedComments, tokens) {
// At first, we should calculate extended comment ranges.
var comments = [], comment, len, i, cursor;
if (!tree.range) {
throw new Error('attachComments needs range information');
}
// tokens array is empty, we attach comments to tree as 'leadingComments'
if (!tokens.length) {
if (providedComments.length) {
for (i = 0, len = providedComments.length; i < len; i += 1) {
comment = deepCopy(providedComments[i]);
comment.extendedRange = [0, tree.range[0]];
comments.push(comment);
}
tree.leadingComments = comments;
}
return tree;
}
for (i = 0, len = providedComments.length; i < len; i += 1) {
comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
}
// This is based on John Freeman's implementation.
cursor = 0;
traverse(tree, {
enter: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (comment.extendedRange[1] > node.range[0]) {
break;
}
if (comment.extendedRange[1] === node.range[0]) {
if (!node.leadingComments) {
node.leadingComments = [];
}
node.leadingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
cursor = 0;
traverse(tree, {
leave: function (node) {
var comment;
while (cursor < comments.length) {
comment = comments[cursor];
if (node.range[1] < comment.extendedRange[0]) {
break;
}
if (node.range[1] === comment.extendedRange[0]) {
if (!node.trailingComments) {
node.trailingComments = [];
}
node.trailingComments.push(comment);
comments.splice(cursor, 1);
} else {
cursor += 1;
}
}
// already out of owned node
if (cursor === comments.length) {
return VisitorOption.Break;
}
if (comments[cursor].extendedRange[0] > node.range[1]) {
return VisitorOption.Skip;
}
}
});
return tree;
}
exports.Syntax = Syntax;
exports.traverse = traverse;
exports.replace = replace;
exports.attachComments = attachComments;
exports.VisitorKeys = VisitorKeys;
exports.VisitorOption = VisitorOption;
exports.Controller = Controller;
exports.cloneEnvironment = function () { return clone({}); };
return exports;
}(exports));
/* vim: set sw=4 ts=4 et tw=80 : */

View File

@ -0,0 +1,70 @@
/*
Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
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 <COPYRIGHT HOLDER> 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.
*/
'use strict';
var gulp = require('gulp'),
git = require('gulp-git'),
bump = require('gulp-bump'),
filter = require('gulp-filter'),
tagVersion = require('gulp-tag-version');
var TEST = [ 'test/*.js' ];
var POWERED = [ 'powered-test/*.js' ];
var SOURCE = [ 'src/**/*.js' ];
/**
* Bumping version number and tagging the repository with it.
* Please read http://semver.org/
*
* You can use the commands
*
* gulp patch # makes v0.1.0 -> v0.1.1
* gulp feature # makes v0.1.1 -> v0.2.0
* gulp release # makes v0.2.1 -> v1.0.0
*
* To bump the version numbers accordingly after you did a patch,
* introduced a feature or made a backwards-incompatible release.
*/
function inc(importance) {
// get all the files to bump version in
return gulp.src(['./package.json'])
// bump the version number in those files
.pipe(bump({type: importance}))
// save it back to filesystem
.pipe(gulp.dest('./'))
// commit the changed version number
.pipe(git.commit('Bumps package version'))
// read only one file to get the version number
.pipe(filter('package.json'))
// **tag it in the repository**
.pipe(tagVersion({
prefix: ''
}));
}
gulp.task('patch', [ ], function () { return inc('patch'); })
gulp.task('minor', [ ], function () { return inc('minor'); })
gulp.task('major', [ ], function () { return inc('major'); })

View File

@ -0,0 +1,40 @@
{
"name": "estraverse",
"description": "ECMAScript JS AST traversal functions",
"homepage": "https://github.com/estools/estraverse",
"main": "estraverse.js",
"version": "5.3.0",
"engines": {
"node": ">=4.0"
},
"maintainers": [
{
"name": "Yusuke Suzuki",
"email": "utatane.tea@gmail.com",
"web": "http://github.com/Constellation"
}
],
"repository": {
"type": "git",
"url": "http://github.com/estools/estraverse.git"
},
"devDependencies": {
"babel-preset-env": "^1.6.1",
"babel-register": "^6.3.13",
"chai": "^2.1.1",
"espree": "^1.11.0",
"gulp": "^3.8.10",
"gulp-bump": "^0.2.2",
"gulp-filter": "^2.0.0",
"gulp-git": "^1.0.1",
"gulp-tag-version": "^1.3.0",
"jshint": "^2.5.6",
"mocha": "^2.1.0"
},
"license": "BSD-2-Clause",
"scripts": {
"test": "npm run-script lint && npm run-script unit-test",
"lint": "jshint estraverse.js",
"unit-test": "mocha --compilers js:babel-register"
}
}

View File

@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@ -0,0 +1,664 @@
semver(1) -- The semantic versioner for npm
===========================================
## Install
```bash
npm install semver
````
## Usage
As a node module:
```js
const semver = require('semver')
semver.valid('1.2.3') // '1.2.3'
semver.valid('a.b.c') // null
semver.clean(' =v1.2.3 ') // '1.2.3'
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
semver.gt('1.2.3', '9.8.7') // false
semver.lt('1.2.3', '9.8.7') // true
semver.minVersion('>=1.0.0') // '1.0.0'
semver.valid(semver.coerce('v2')) // '2.0.0'
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
```
You can also just load the module for the function that you care about if
you'd like to minimize your footprint.
```js
// load the whole API at once in a single object
const semver = require('semver')
// or just load the bits you need
// all of them listed here, just pick and choose what you want
// classes
const SemVer = require('semver/classes/semver')
const Comparator = require('semver/classes/comparator')
const Range = require('semver/classes/range')
// functions for working with versions
const semverParse = require('semver/functions/parse')
const semverValid = require('semver/functions/valid')
const semverClean = require('semver/functions/clean')
const semverInc = require('semver/functions/inc')
const semverDiff = require('semver/functions/diff')
const semverMajor = require('semver/functions/major')
const semverMinor = require('semver/functions/minor')
const semverPatch = require('semver/functions/patch')
const semverPrerelease = require('semver/functions/prerelease')
const semverCompare = require('semver/functions/compare')
const semverRcompare = require('semver/functions/rcompare')
const semverCompareLoose = require('semver/functions/compare-loose')
const semverCompareBuild = require('semver/functions/compare-build')
const semverSort = require('semver/functions/sort')
const semverRsort = require('semver/functions/rsort')
// low-level comparators between versions
const semverGt = require('semver/functions/gt')
const semverLt = require('semver/functions/lt')
const semverEq = require('semver/functions/eq')
const semverNeq = require('semver/functions/neq')
const semverGte = require('semver/functions/gte')
const semverLte = require('semver/functions/lte')
const semverCmp = require('semver/functions/cmp')
const semverCoerce = require('semver/functions/coerce')
// working with ranges
const semverSatisfies = require('semver/functions/satisfies')
const semverMaxSatisfying = require('semver/ranges/max-satisfying')
const semverMinSatisfying = require('semver/ranges/min-satisfying')
const semverToComparators = require('semver/ranges/to-comparators')
const semverMinVersion = require('semver/ranges/min-version')
const semverValidRange = require('semver/ranges/valid')
const semverOutside = require('semver/ranges/outside')
const semverGtr = require('semver/ranges/gtr')
const semverLtr = require('semver/ranges/ltr')
const semverIntersects = require('semver/ranges/intersects')
const semverSimplifyRange = require('semver/ranges/simplify')
const semverRangeSubset = require('semver/ranges/subset')
```
As a command-line utility:
```
$ semver -h
A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter
Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence
Options:
-r --range <range>
Print versions that match the specified range.
-i --increment [<level>]
Increment a version by the specified level. Level can
be one of: major, minor, patch, premajor, preminor,
prepatch, prerelease, or release. Default level is 'patch'.
Only one version may be specified.
--preid <identifier>
Identifier to be used to prefix premajor, preminor,
prepatch or prerelease version increments.
-l --loose
Interpret versions and ranges loosely
-n <0|1>
This is the base to be used for the prerelease identifier.
-p --include-prerelease
Always include prerelease versions in range matching
-c --coerce
Coerce a string into SemVer if possible
(does not imply --loose)
--rtl
Coerce version strings right to left
--ltr
Coerce version strings left to right (default)
Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.
```
## Versions
A "version" is described by the `v2.0.0` specification found at
<https://semver.org/>.
A leading `"="` or `"v"` character is stripped off and ignored.
Support for stripping a leading "v" is kept for compatibility with `v1.0.0` of the SemVer
specification but should not be used anymore.
## Ranges
A `version range` is a set of `comparators` that specify versions
that satisfy the range.
A `comparator` is composed of an `operator` and a `version`. The set
of primitive `operators` is:
* `<` Less than
* `<=` Less than or equal to
* `>` Greater than
* `>=` Greater than or equal to
* `=` Equal. If no operator is specified, then equality is assumed,
so this operator is optional but MAY be included.
For example, the comparator `>=1.2.7` would match the versions
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and
would match the versions `2.0.0` and `3.1.0`, but not the versions
`1.0.1` or `1.1.0`.
Comparators can be joined by whitespace to form a `comparator set`,
which is satisfied by the **intersection** of all of the comparators
it includes.
A range is composed of one or more comparator sets, joined by `||`. A
version matches a range if and only if every comparator in at least
one of the `||`-separated comparator sets is satisfied by the version.
For example, the range `>=1.2.7 <1.3.0` would match the versions
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
or `1.1.0`.
The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.
### Prerelease Tags
If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
it will only be allowed to satisfy comparator sets if at least one
comparator with the same `[major, minor, patch]` tuple also has a
prerelease tag.
For example, the range `>1.2.3-alpha.3` would be allowed to match the
version `1.2.3-alpha.7`, but it would *not* be satisfied by
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
than" `1.2.3-alpha.3` according to the SemVer sort rules. The version
range only accepts prerelease tags on the `1.2.3` version.
Version `3.4.5` *would* satisfy the range because it does not have a
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.
The purpose of this behavior is twofold. First, prerelease versions
frequently are updated very quickly, and contain many breaking changes
that are (by the author's design) not yet fit for public consumption.
Therefore, by default, they are excluded from range-matching
semantics.
Second, a user who has opted into using a prerelease version has
indicated the intent to use *that specific* set of
alpha/beta/rc versions. By including a prerelease tag in the range,
the user is indicating that they are aware of the risk. However, it
is still not appropriate to assume that they have opted into taking a
similar risk on the *next* set of prerelease versions.
Note that this behavior can be suppressed (treating all prerelease
versions as if they were normal versions, for range-matching)
by setting the `includePrerelease` flag on the options
object to any
[functions](https://github.com/npm/node-semver#functions) that do
range matching.
#### Prerelease Identifiers
The method `.inc` takes an additional `identifier` string argument that
will append the value of the string as a prerelease identifier:
```javascript
semver.inc('1.2.3', 'prerelease', 'beta')
// '1.2.4-beta.0'
```
command-line example:
```bash
$ semver 1.2.3 -i prerelease --preid beta
1.2.4-beta.0
```
Which then can be used to increment further:
```bash
$ semver 1.2.4-beta.0 -i prerelease
1.2.4-beta.1
```
To get out of the prerelease phase, use the `release` option:
```bash
$ semver 1.2.4-beta.1 -i release
1.2.4
```
#### Prerelease Identifier Base
The method `.inc` takes an optional parameter 'identifierBase' string
that will let you let your prerelease number as zero-based or one-based.
Set to `false` to omit the prerelease number altogether.
If you do not specify this parameter, it will default to zero-based.
```javascript
semver.inc('1.2.3', 'prerelease', 'beta', '1')
// '1.2.4-beta.1'
```
```javascript
semver.inc('1.2.3', 'prerelease', 'beta', false)
// '1.2.4-beta'
```
command-line example:
```bash
$ semver 1.2.3 -i prerelease --preid beta -n 1
1.2.4-beta.1
```
```bash
$ semver 1.2.3 -i prerelease --preid beta -n false
1.2.4-beta
```
### Advanced Range Syntax
Advanced range syntax desugars to primitive comparators in
deterministic ways.
Advanced ranges may be combined in the same way as primitive
comparators using white space or `||`.
#### Hyphen Ranges `X.Y.Z - A.B.C`
Specifies an inclusive set.
* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`
If a partial version is provided as the first version in the inclusive
range, then the missing pieces are replaced with zeroes.
* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`
If a partial version is provided as the second version in the
inclusive range, then all versions that start with the supplied parts
of the tuple are accepted, but nothing that would be greater than the
provided tuple parts.
* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0`
* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0`
#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`
Any of `X`, `x`, or `*` may be used to "stand in" for one of the
numeric values in the `[major, minor, patch]` tuple.
* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless
`includePrerelease` is specified, in which case any version at all
satisfies)
* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version)
* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions)
A partial version range is treated as an X-Range, so the special
character is in fact optional.
* `""` (empty string) := `*` := `>=0.0.0`
* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0`
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0`
#### Tilde Ranges `~1.2.3` `~1.2` `~1`
Allows patch-level changes if a minor version is specified on the
comparator. Allows minor-level changes if not.
* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0`
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0`
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`
Allows changes that do not modify the left-most non-zero element in the
`[major, minor, patch]` tuple. In other words, this allows patch and
minor updates for versions `1.0.0` and above, patch updates for
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.
Many authors treat a `0.x` version as if the `x` were the major
"breaking-change" indicator.
Caret ranges are ideal when an author may make breaking changes
between `0.2.4` and `0.3.0` releases, which is a common practice.
However, it presumes that there will *not* be breaking changes between
`0.2.4` and `0.2.5`. It allows for changes that are presumed to be
additive (but non-breaking), according to commonly observed practices.
* `^1.2.3` := `>=1.2.3 <2.0.0-0`
* `^0.2.3` := `>=0.2.3 <0.3.0-0`
* `^0.0.3` := `>=0.0.3 <0.0.4-0`
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the
`0.0.3` version *only* will be allowed, if they are greater than or
equal to `beta`. So, `0.0.3-pr.2` would be allowed.
When parsing caret ranges, a missing `patch` value desugars to the
number `0`, but will allow flexibility within that value, even if the
major and minor versions are both `0`.
* `^1.2.x` := `>=1.2.0 <2.0.0-0`
* `^0.0.x` := `>=0.0.0 <0.1.0-0`
* `^0.0` := `>=0.0.0 <0.1.0-0`
A missing `minor` and `patch` values will desugar to zero, but also
allow flexibility within those values, even if the major version is
zero.
* `^1.x` := `>=1.0.0 <2.0.0-0`
* `^0.x` := `>=0.0.0 <1.0.0-0`
### Range Grammar
Putting all this together, here is a Backus-Naur grammar for ranges,
for the benefit of parser authors:
```bnf
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= parts
build ::= parts
parts ::= part ( '.' part ) *
part ::= nr | [-0-9A-Za-z]+
```
## Functions
All methods and classes take a final `options` object argument. All
options in this object are `false` by default. The options supported
are:
- `loose`: Be more forgiving about not-quite-valid semver strings.
(Any resulting output will always be 100% strict compliant, of
course.) For backwards compatibility reasons, if the `options`
argument is a boolean value instead of an object, it is interpreted
to be the `loose` param.
- `includePrerelease`: Set to suppress the [default
behavior](https://github.com/npm/node-semver#prerelease-tags) of
excluding prerelease tagged versions from ranges unless they are
explicitly opted into.
Strict-mode Comparators and Ranges will be strict about the SemVer
strings that they parse.
* `valid(v)`: Return the parsed version, or null if it's not valid.
* `inc(v, releaseType, options, identifier, identifierBase)`:
Return the version incremented by the release
type (`major`, `premajor`, `minor`, `preminor`, `patch`,
`prepatch`, `prerelease`, or `release`), or null if it's not valid
* `premajor` in one call will bump the version up to the next major
version and down to a prerelease of that major version.
`preminor`, and `prepatch` work the same way.
* If called from a non-prerelease version, `prerelease` will work the
same as `prepatch`. It increments the patch version and then makes a
prerelease. If the input version is already a prerelease it simply
increments it.
* `release` will remove any prerelease part of the version.
* `identifier` can be used to prefix `premajor`, `preminor`,
`prepatch`, or `prerelease` version increments. `identifierBase`
is the base to be used for the `prerelease` identifier.
* `prerelease(v)`: Returns an array of prerelease components, or null
if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]`
* `major(v)`: Return the major version number.
* `minor(v)`: Return the minor version number.
* `patch(v)`: Return the patch version number.
* `intersects(r1, r2, loose)`: Return true if the two supplied ranges
or comparators intersect.
* `parse(v)`: Attempt to parse a string as a semantic version, returning either
a `SemVer` object or `null`.
### Comparison
* `gt(v1, v2)`: `v1 > v2`
* `gte(v1, v2)`: `v1 >= v2`
* `lt(v1, v2)`: `v1 < v2`
* `lte(v1, v2)`: `v1 <= v2`
* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent,
even if they're not the same string. You already know how to
compare strings.
* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`.
* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call
the corresponding function above. `"==="` and `"!=="` do simple
string comparison, but are included for completeness. Throws if an
invalid comparison string is provided.
* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
* `rcompare(v1, v2)`: The reverse of `compare`. Sorts an array of versions
in descending order when passed to `Array.sort()`.
* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions
are equal. Sorts in ascending order if passed to `Array.sort()`.
* `compareLoose(v1, v2)`: Short for `compare(v1, v2, { loose: true })`.
* `diff(v1, v2)`: Returns the difference between two versions by the release type
(`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
or null if the versions are the same.
### Sorting
* `sort(versions)`: Returns a sorted array of versions based on the `compareBuild`
function.
* `rsort(versions)`: The reverse of `sort`. Returns an array of versions based on
the `compareBuild` function in descending order.
### Comparators
* `intersects(comparator)`: Return true if the comparators intersect
### Ranges
* `validRange(range)`: Return the valid range or null if it's not valid.
* `satisfies(version, range)`: Return true if the version satisfies the
range.
* `maxSatisfying(versions, range)`: Return the highest version in the list
that satisfies the range, or `null` if none of them do.
* `minSatisfying(versions, range)`: Return the lowest version in the list
that satisfies the range, or `null` if none of them do.
* `minVersion(range)`: Return the lowest version that can match
the given range.
* `gtr(version, range)`: Return `true` if the version is greater than all the
versions possible in the range.
* `ltr(version, range)`: Return `true` if the version is less than all the
versions possible in the range.
* `outside(version, range, hilo)`: Return true if the version is outside
the bounds of the range in either the high or low direction. The
`hilo` argument must be either the string `'>'` or `'<'`. (This is
the function called by `gtr` and `ltr`.)
* `intersects(range)`: Return true if any of the range comparators intersect.
* `simplifyRange(versions, range)`: Return a "simplified" range that
matches the same items in the `versions` list as the range specified. Note
that it does *not* guarantee that it would match the same versions in all
cases, only for the set of versions provided. This is useful when
generating ranges by joining together multiple versions with `||`
programmatically, to provide the user with something a bit more
ergonomic. If the provided range is shorter in string-length than the
generated range, then that is returned.
* `subset(subRange, superRange)`: Return `true` if the `subRange` range is
entirely contained by the `superRange` range.
Note that, since ranges may be non-contiguous, a version might not be
greater than a range, less than a range, *or* satisfy a range! For
example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`
until `2.0.0`, so version `1.2.10` would not be greater than the
range (because `2.0.1` satisfies, which is higher), nor less than the
range (since `1.2.8` satisfies, which is lower), and it also does not
satisfy the range.
If you want to know if a version satisfies or does not satisfy a
range, use the `satisfies(version, range)` function.
### Coercion
* `coerce(version, options)`: Coerces a string to semver if possible
This aims to provide a very forgiving translation of a non-semver string to
semver. It looks for the first digit in a string and consumes all
remaining characters which satisfy at least a partial semver (e.g., `1`,
`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer
versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All
surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
`3.4.0`). Only text which lacks digits will fail coercion (`version one`
is not valid). The maximum length for any semver component considered for
coercion is 16 characters; longer components will be ignored
(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any
semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
components are invalid (`9999999999999999.4.7.4` is likely invalid).
If the `options.rtl` flag is set, then `coerce` will return the right-most
coercible tuple that does not share an ending index with a longer coercible
tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not
`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of
any other overlapping SemVer tuple.
If the `options.includePrerelease` flag is set, then the `coerce` result will contain
prerelease and build parts of a version. For example, `1.2.3.4-rc.1+rev.2`
will preserve prerelease `rc.1` and build `rev.2` in the result.
### Clean
* `clean(version)`: Clean a string to be a valid semver if possible
This will return a cleaned and trimmed semver version. If the provided
version is not valid a null will be returned. This does not work for
ranges.
ex.
* `s.clean(' = v 2.1.5foo')`: `null`
* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean(' = v 2.1.5-foo')`: `null`
* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean('=v2.1.5')`: `'2.1.5'`
* `s.clean(' =v2.1.5')`: `'2.1.5'`
* `s.clean(' 2.1.5 ')`: `'2.1.5'`
* `s.clean('~1.0.0')`: `null`
## Constants
As a convenience, helper constants are exported to provide information about what `node-semver` supports:
### `RELEASE_TYPES`
- major
- premajor
- minor
- preminor
- patch
- prepatch
- prerelease
```
const semver = require('semver');
if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) {
console.log('This is a valid release type!');
} else {
console.warn('This is NOT a valid release type!');
}
```
### `SEMVER_SPEC_VERSION`
2.0.0
```
const semver = require('semver');
console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION);
```
## Exported Modules
<!--
TODO: Make sure that all of these items are documented (classes aren't,
eg), and then pull the module name into the documentation for that specific
thing.
-->
You may pull in just the part of this semver utility that you need if you
are sensitive to packing and tree-shaking concerns. The main
`require('semver')` export uses getter functions to lazily load the parts
of the API that are used.
The following modules are available:
* `require('semver')`
* `require('semver/classes')`
* `require('semver/classes/comparator')`
* `require('semver/classes/range')`
* `require('semver/classes/semver')`
* `require('semver/functions/clean')`
* `require('semver/functions/cmp')`
* `require('semver/functions/coerce')`
* `require('semver/functions/compare')`
* `require('semver/functions/compare-build')`
* `require('semver/functions/compare-loose')`
* `require('semver/functions/diff')`
* `require('semver/functions/eq')`
* `require('semver/functions/gt')`
* `require('semver/functions/gte')`
* `require('semver/functions/inc')`
* `require('semver/functions/lt')`
* `require('semver/functions/lte')`
* `require('semver/functions/major')`
* `require('semver/functions/minor')`
* `require('semver/functions/neq')`
* `require('semver/functions/parse')`
* `require('semver/functions/patch')`
* `require('semver/functions/prerelease')`
* `require('semver/functions/rcompare')`
* `require('semver/functions/rsort')`
* `require('semver/functions/satisfies')`
* `require('semver/functions/sort')`
* `require('semver/functions/valid')`
* `require('semver/ranges/gtr')`
* `require('semver/ranges/intersects')`
* `require('semver/ranges/ltr')`
* `require('semver/ranges/max-satisfying')`
* `require('semver/ranges/min-satisfying')`
* `require('semver/ranges/min-version')`
* `require('semver/ranges/outside')`
* `require('semver/ranges/simplify')`
* `require('semver/ranges/subset')`
* `require('semver/ranges/to-comparators')`
* `require('semver/ranges/valid')`

View File

@ -0,0 +1,191 @@
#!/usr/bin/env node
// Standalone semver comparison program.
// Exits successfully and prints matching version(s) if
// any supplied version is valid and passes all tests.
'use strict'
const argv = process.argv.slice(2)
let versions = []
const range = []
let inc = null
const version = require('../package.json').version
let loose = false
let includePrerelease = false
let coerce = false
let rtl = false
let identifier
let identifierBase
const semver = require('../')
const parseOptions = require('../internal/parse-options')
let reverse = false
let options = {}
const main = () => {
if (!argv.length) {
return help()
}
while (argv.length) {
let a = argv.shift()
const indexOfEqualSign = a.indexOf('=')
if (indexOfEqualSign !== -1) {
const value = a.slice(indexOfEqualSign + 1)
a = a.slice(0, indexOfEqualSign)
argv.unshift(value)
}
switch (a) {
case '-rv': case '-rev': case '--rev': case '--reverse':
reverse = true
break
case '-l': case '--loose':
loose = true
break
case '-p': case '--include-prerelease':
includePrerelease = true
break
case '-v': case '--version':
versions.push(argv.shift())
break
case '-i': case '--inc': case '--increment':
switch (argv[0]) {
case 'major': case 'minor': case 'patch': case 'prerelease':
case 'premajor': case 'preminor': case 'prepatch':
case 'release':
inc = argv.shift()
break
default:
inc = 'patch'
break
}
break
case '--preid':
identifier = argv.shift()
break
case '-r': case '--range':
range.push(argv.shift())
break
case '-n':
identifierBase = argv.shift()
if (identifierBase === 'false') {
identifierBase = false
}
break
case '-c': case '--coerce':
coerce = true
break
case '--rtl':
rtl = true
break
case '--ltr':
rtl = false
break
case '-h': case '--help': case '-?':
return help()
default:
versions.push(a)
break
}
}
options = parseOptions({ loose, includePrerelease, rtl })
versions = versions.map((v) => {
return coerce ? (semver.coerce(v, options) || { version: v }).version : v
}).filter((v) => {
return semver.valid(v)
})
if (!versions.length) {
return fail()
}
if (inc && (versions.length !== 1 || range.length)) {
return failInc()
}
for (let i = 0, l = range.length; i < l; i++) {
versions = versions.filter((v) => {
return semver.satisfies(v, range[i], options)
})
if (!versions.length) {
return fail()
}
}
versions
.sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options))
.map(v => semver.clean(v, options))
.map(v => inc ? semver.inc(v, inc, options, identifier, identifierBase) : v)
.forEach(v => console.log(v))
}
const failInc = () => {
console.error('--inc can only be used on a single version with no range')
fail()
}
const fail = () => process.exit(1)
const help = () => console.log(
`SemVer ${version}
A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter
Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence
Options:
-r --range <range>
Print versions that match the specified range.
-i --increment [<level>]
Increment a version by the specified level. Level can
be one of: major, minor, patch, premajor, preminor,
prepatch, prerelease, or release. Default level is 'patch'.
Only one version may be specified.
--preid <identifier>
Identifier to be used to prefix premajor, preminor,
prepatch or prerelease version increments.
-l --loose
Interpret versions and ranges loosely
-p --include-prerelease
Always include prerelease versions in range matching
-c --coerce
Coerce a string into SemVer if possible
(does not imply --loose)
--rtl
Coerce version strings right to left
--ltr
Coerce version strings left to right (default)
-n <base>
Base number to be used for the prerelease identifier.
Can be either 0 or 1, or false to omit the number altogether.
Defaults to 0.
Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.`)
main()

View File

@ -0,0 +1,143 @@
'use strict'
const ANY = Symbol('SemVer ANY')
// hoisted class for cyclic dependency
class Comparator {
static get ANY () {
return ANY
}
constructor (comp, options) {
options = parseOptions(options)
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp
} else {
comp = comp.value
}
}
comp = comp.trim().split(/\s+/).join(' ')
debug('comparator', comp, options)
this.options = options
this.loose = !!options.loose
this.parse(comp)
if (this.semver === ANY) {
this.value = ''
} else {
this.value = this.operator + this.semver.version
}
debug('comp', this)
}
parse (comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
const m = comp.match(r)
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`)
}
this.operator = m[1] !== undefined ? m[1] : ''
if (this.operator === '=') {
this.operator = ''
}
// if it literally is just '>' or '' then allow anything.
if (!m[2]) {
this.semver = ANY
} else {
this.semver = new SemVer(m[2], this.options.loose)
}
}
toString () {
return this.value
}
test (version) {
debug('Comparator.test', version, this.options.loose)
if (this.semver === ANY || version === ANY) {
return true
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
return cmp(version, this.operator, this.semver, this.options)
}
intersects (comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required')
}
if (this.operator === '') {
if (this.value === '') {
return true
}
return new Range(comp.value, options).test(this.value)
} else if (comp.operator === '') {
if (comp.value === '') {
return true
}
return new Range(this.value, options).test(comp.semver)
}
options = parseOptions(options)
// Special cases where nothing can possibly be lower
if (options.includePrerelease &&
(this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
return false
}
if (!options.includePrerelease &&
(this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
return false
}
// Same direction increasing (> or >=)
if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
return true
}
// Same direction decreasing (< or <=)
if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
return true
}
// same SemVer and both sides are inclusive (<= or >=)
if (
(this.semver.version === comp.semver.version) &&
this.operator.includes('=') && comp.operator.includes('=')) {
return true
}
// opposite directions less than
if (cmp(this.semver, '<', comp.semver, options) &&
this.operator.startsWith('>') && comp.operator.startsWith('<')) {
return true
}
// opposite directions greater than
if (cmp(this.semver, '>', comp.semver, options) &&
this.operator.startsWith('<') && comp.operator.startsWith('>')) {
return true
}
return false
}
}
module.exports = Comparator
const parseOptions = require('../internal/parse-options')
const { safeRe: re, t } = require('../internal/re')
const cmp = require('../functions/cmp')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const Range = require('./range')

View File

@ -0,0 +1,7 @@
'use strict'
module.exports = {
SemVer: require('./semver.js'),
Range: require('./range.js'),
Comparator: require('./comparator.js'),
}

View File

@ -0,0 +1,556 @@
'use strict'
const SPACE_CHARACTERS = /\s+/g
// hoisted class for cyclic dependency
class Range {
constructor (range, options) {
options = parseOptions(options)
if (range instanceof Range) {
if (
range.loose === !!options.loose &&
range.includePrerelease === !!options.includePrerelease
) {
return range
} else {
return new Range(range.raw, options)
}
}
if (range instanceof Comparator) {
// just put it in the set and return
this.raw = range.value
this.set = [[range]]
this.formatted = undefined
return this
}
this.options = options
this.loose = !!options.loose
this.includePrerelease = !!options.includePrerelease
// First reduce all whitespace as much as possible so we do not have to rely
// on potentially slow regexes like \s*. This is then stored and used for
// future error messages as well.
this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')
// First, split on ||
this.set = this.raw
.split('||')
// map the range to a 2d array of comparators
.map(r => this.parseRange(r.trim()))
// throw out any comparator lists that are empty
// this generally means that it was not a valid range, which is allowed
// in loose mode, but will still throw if the WHOLE range is invalid.
.filter(c => c.length)
if (!this.set.length) {
throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
}
// if we have any that are not the null set, throw out null sets.
if (this.set.length > 1) {
// keep the first one, in case they're all null sets
const first = this.set[0]
this.set = this.set.filter(c => !isNullSet(c[0]))
if (this.set.length === 0) {
this.set = [first]
} else if (this.set.length > 1) {
// if we have any that are *, then the range is just *
for (const c of this.set) {
if (c.length === 1 && isAny(c[0])) {
this.set = [c]
break
}
}
}
}
this.formatted = undefined
}
get range () {
if (this.formatted === undefined) {
this.formatted = ''
for (let i = 0; i < this.set.length; i++) {
if (i > 0) {
this.formatted += '||'
}
const comps = this.set[i]
for (let k = 0; k < comps.length; k++) {
if (k > 0) {
this.formatted += ' '
}
this.formatted += comps[k].toString().trim()
}
}
}
return this.formatted
}
format () {
return this.range
}
toString () {
return this.range
}
parseRange (range) {
// memoize range parsing for performance.
// this is a very hot path, and fully deterministic.
const memoOpts =
(this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
(this.options.loose && FLAG_LOOSE)
const memoKey = memoOpts + ':' + range
const cached = cache.get(memoKey)
if (cached) {
return cached
}
const loose = this.options.loose
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
debug('hyphen replace', range)
// `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
debug('comparator trim', range)
// `~ 1.2.3` => `~1.2.3`
range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
debug('tilde trim', range)
// `^ 1.2.3` => `^1.2.3`
range = range.replace(re[t.CARETTRIM], caretTrimReplace)
debug('caret trim', range)
// At this point, the range is completely trimmed and
// ready to be split into comparators.
let rangeList = range
.split(' ')
.map(comp => parseComparator(comp, this.options))
.join(' ')
.split(/\s+/)
// >=0.0.0 is equivalent to *
.map(comp => replaceGTE0(comp, this.options))
if (loose) {
// in loose mode, throw out any that are not valid comparators
rangeList = rangeList.filter(comp => {
debug('loose invalid filter', comp, this.options)
return !!comp.match(re[t.COMPARATORLOOSE])
})
}
debug('range list', rangeList)
// if any comparators are the null set, then replace with JUST null set
// if more than one comparator, remove any * comparators
// also, don't include the same comparator more than once
const rangeMap = new Map()
const comparators = rangeList.map(comp => new Comparator(comp, this.options))
for (const comp of comparators) {
if (isNullSet(comp)) {
return [comp]
}
rangeMap.set(comp.value, comp)
}
if (rangeMap.size > 1 && rangeMap.has('')) {
rangeMap.delete('')
}
const result = [...rangeMap.values()]
cache.set(memoKey, result)
return result
}
intersects (range, options) {
if (!(range instanceof Range)) {
throw new TypeError('a Range is required')
}
return this.set.some((thisComparators) => {
return (
isSatisfiable(thisComparators, options) &&
range.set.some((rangeComparators) => {
return (
isSatisfiable(rangeComparators, options) &&
thisComparators.every((thisComparator) => {
return rangeComparators.every((rangeComparator) => {
return thisComparator.intersects(rangeComparator, options)
})
})
)
})
)
})
}
// if ANY of the sets match ALL of its comparators, then pass
test (version) {
if (!version) {
return false
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
for (let i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true
}
}
return false
}
}
module.exports = Range
const LRU = require('../internal/lrucache')
const cache = new LRU()
const parseOptions = require('../internal/parse-options')
const Comparator = require('./comparator')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const {
safeRe: re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace,
} = require('../internal/re')
const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')
const isNullSet = c => c.value === '<0.0.0-0'
const isAny = c => c.value === ''
// take a set of comparators and determine whether there
// exists a version which can satisfy it
const isSatisfiable = (comparators, options) => {
let result = true
const remainingComparators = comparators.slice()
let testComparator = remainingComparators.pop()
while (result && remainingComparators.length) {
result = remainingComparators.every((otherComparator) => {
return testComparator.intersects(otherComparator, options)
})
testComparator = remainingComparators.pop()
}
return result
}
// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
const parseComparator = (comp, options) => {
debug('comp', comp, options)
comp = replaceCarets(comp, options)
debug('caret', comp)
comp = replaceTildes(comp, options)
debug('tildes', comp)
comp = replaceXRanges(comp, options)
debug('xrange', comp)
comp = replaceStars(comp, options)
debug('stars', comp)
return comp
}
const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
// ~0.0.1 --> >=0.0.1 <0.1.0-0
const replaceTildes = (comp, options) => {
return comp
.trim()
.split(/\s+/)
.map((c) => replaceTilde(c, options))
.join(' ')
}
const replaceTilde = (comp, options) => {
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
return comp.replace(r, (_, M, m, p, pr) => {
debug('tilde', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
} else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0-0
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
} else if (pr) {
debug('replaceTilde pr', pr)
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
} else {
// ~1.2.3 == >=1.2.3 <1.3.0-0
ret = `>=${M}.${m}.${p
} <${M}.${+m + 1}.0-0`
}
debug('tilde return', ret)
return ret
})
}
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
// ^0.0.1 --> >=0.0.1 <0.0.2-0
// ^0.1.0 --> >=0.1.0 <0.2.0-0
const replaceCarets = (comp, options) => {
return comp
.trim()
.split(/\s+/)
.map((c) => replaceCaret(c, options))
.join(' ')
}
const replaceCaret = (comp, options) => {
debug('caret', comp, options)
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
const z = options.includePrerelease ? '-0' : ''
return comp.replace(r, (_, M, m, p, pr) => {
debug('caret', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
} else if (isX(p)) {
if (M === '0') {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
} else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
}
} else if (pr) {
debug('replaceCaret pr', pr)
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${+M + 1}.0.0-0`
}
} else {
debug('no pr')
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p
}${z} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p
}${z} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p
} <${+M + 1}.0.0-0`
}
}
debug('caret return', ret)
return ret
})
}
const replaceXRanges = (comp, options) => {
debug('replaceXRanges', comp, options)
return comp
.split(/\s+/)
.map((c) => replaceXRange(c, options))
.join(' ')
}
const replaceXRange = (comp, options) => {
comp = comp.trim()
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
debug('xRange', comp, ret, gtlt, M, m, p, pr)
const xM = isX(M)
const xm = xM || isX(m)
const xp = xm || isX(p)
const anyX = xp
if (gtlt === '=' && anyX) {
gtlt = ''
}
// if we're including prereleases in the match, then we need
// to fix this to -0, the lowest possible prerelease value
pr = options.includePrerelease ? '-0' : ''
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0-0'
} else {
// nothing is forbidden
ret = '*'
}
} else if (gtlt && anyX) {
// we know patch is an x, because we have any x at all.
// replace X with 0
if (xm) {
m = 0
}
p = 0
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
gtlt = '>='
if (xm) {
M = +M + 1
m = 0
p = 0
} else {
m = +m + 1
p = 0
}
} else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<'
if (xm) {
M = +M + 1
} else {
m = +m + 1
}
}
if (gtlt === '<') {
pr = '-0'
}
ret = `${gtlt + M}.${m}.${p}${pr}`
} else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
} else if (xp) {
ret = `>=${M}.${m}.0${pr
} <${M}.${+m + 1}.0-0`
}
debug('xRange return', ret)
return ret
})
}
// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
const replaceStars = (comp, options) => {
debug('replaceStars', comp, options)
// Looseness is ignored here. star is always as loose as it gets!
return comp
.trim()
.replace(re[t.STAR], '')
}
const replaceGTE0 = (comp, options) => {
debug('replaceGTE0', comp, options)
return comp
.trim()
.replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
}
// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
// TODO build?
const hyphenReplace = incPr => ($0,
from, fM, fm, fp, fpr, fb,
to, tM, tm, tp, tpr) => {
if (isX(fM)) {
from = ''
} else if (isX(fm)) {
from = `>=${fM}.0.0${incPr ? '-0' : ''}`
} else if (isX(fp)) {
from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
} else if (fpr) {
from = `>=${from}`
} else {
from = `>=${from}${incPr ? '-0' : ''}`
}
if (isX(tM)) {
to = ''
} else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`
} else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`
} else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`
} else if (incPr) {
to = `<${tM}.${tm}.${+tp + 1}-0`
} else {
to = `<=${to}`
}
return `${from} ${to}`.trim()
}
const testSet = (set, version, options) => {
for (let i = 0; i < set.length; i++) {
if (!set[i].test(version)) {
return false
}
}
if (version.prerelease.length && !options.includePrerelease) {
// Find the set of versions that are allowed to have prereleases
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
// That should allow `1.2.3-pr.2` to pass.
// However, `1.2.4-alpha.notready` should NOT be allowed,
// even though it's within the range set by the comparators.
for (let i = 0; i < set.length; i++) {
debug(set[i].semver)
if (set[i].semver === Comparator.ANY) {
continue
}
if (set[i].semver.prerelease.length > 0) {
const allowed = set[i].semver
if (allowed.major === version.major &&
allowed.minor === version.minor &&
allowed.patch === version.patch) {
return true
}
}
}
// Version has a -pre, but it's not one of the ones we like.
return false
}
return true
}

View File

@ -0,0 +1,319 @@
'use strict'
const debug = require('../internal/debug')
const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')
const { safeRe: re, t } = require('../internal/re')
const parseOptions = require('../internal/parse-options')
const { compareIdentifiers } = require('../internal/identifiers')
class SemVer {
constructor (version, options) {
options = parseOptions(options)
if (version instanceof SemVer) {
if (version.loose === !!options.loose &&
version.includePrerelease === !!options.includePrerelease) {
return version
} else {
version = version.version
}
} else if (typeof version !== 'string') {
throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
}
if (version.length > MAX_LENGTH) {
throw new TypeError(
`version is longer than ${MAX_LENGTH} characters`
)
}
debug('SemVer', version, options)
this.options = options
this.loose = !!options.loose
// this isn't actually relevant for versions, but keep it so that we
// don't run into trouble passing this.options around.
this.includePrerelease = !!options.includePrerelease
const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
if (!m) {
throw new TypeError(`Invalid Version: ${version}`)
}
this.raw = version
// these are actually numbers
this.major = +m[1]
this.minor = +m[2]
this.patch = +m[3]
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
throw new TypeError('Invalid major version')
}
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
throw new TypeError('Invalid minor version')
}
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
throw new TypeError('Invalid patch version')
}
// numberify any prerelease numeric ids
if (!m[4]) {
this.prerelease = []
} else {
this.prerelease = m[4].split('.').map((id) => {
if (/^[0-9]+$/.test(id)) {
const num = +id
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num
}
}
return id
})
}
this.build = m[5] ? m[5].split('.') : []
this.format()
}
format () {
this.version = `${this.major}.${this.minor}.${this.patch}`
if (this.prerelease.length) {
this.version += `-${this.prerelease.join('.')}`
}
return this.version
}
toString () {
return this.version
}
compare (other) {
debug('SemVer.compare', this.version, this.options, other)
if (!(other instanceof SemVer)) {
if (typeof other === 'string' && other === this.version) {
return 0
}
other = new SemVer(other, this.options)
}
if (other.version === this.version) {
return 0
}
return this.compareMain(other) || this.comparePre(other)
}
compareMain (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
return (
compareIdentifiers(this.major, other.major) ||
compareIdentifiers(this.minor, other.minor) ||
compareIdentifiers(this.patch, other.patch)
)
}
comparePre (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
// NOT having a prerelease is > having one
if (this.prerelease.length && !other.prerelease.length) {
return -1
} else if (!this.prerelease.length && other.prerelease.length) {
return 1
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0
}
let i = 0
do {
const a = this.prerelease[i]
const b = other.prerelease[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
compareBuild (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
let i = 0
do {
const a = this.build[i]
const b = other.build[i]
debug('build compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
inc (release, identifier, identifierBase) {
if (release.startsWith('pre')) {
if (!identifier && identifierBase === false) {
throw new Error('invalid increment argument: identifier is empty')
}
// Avoid an invalid semver results
if (identifier) {
const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])
if (!match || match[1] !== identifier) {
throw new Error(`invalid identifier: ${identifier}`)
}
}
}
switch (release) {
case 'premajor':
this.prerelease.length = 0
this.patch = 0
this.minor = 0
this.major++
this.inc('pre', identifier, identifierBase)
break
case 'preminor':
this.prerelease.length = 0
this.patch = 0
this.minor++
this.inc('pre', identifier, identifierBase)
break
case 'prepatch':
// If this is already a prerelease, it will bump to the next version
// drop any prereleases that might already exist, since they are not
// relevant at this point.
this.prerelease.length = 0
this.inc('patch', identifier, identifierBase)
this.inc('pre', identifier, identifierBase)
break
// If the input is a non-prerelease version, this acts the same as
// prepatch.
case 'prerelease':
if (this.prerelease.length === 0) {
this.inc('patch', identifier, identifierBase)
}
this.inc('pre', identifier, identifierBase)
break
case 'release':
if (this.prerelease.length === 0) {
throw new Error(`version ${this.raw} is not a prerelease`)
}
this.prerelease.length = 0
break
case 'major':
// If this is a pre-major version, bump up to the same major version.
// Otherwise increment major.
// 1.0.0-5 bumps to 1.0.0
// 1.1.0 bumps to 2.0.0
if (
this.minor !== 0 ||
this.patch !== 0 ||
this.prerelease.length === 0
) {
this.major++
}
this.minor = 0
this.patch = 0
this.prerelease = []
break
case 'minor':
// If this is a pre-minor version, bump up to the same minor version.
// Otherwise increment minor.
// 1.2.0-5 bumps to 1.2.0
// 1.2.1 bumps to 1.3.0
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++
}
this.patch = 0
this.prerelease = []
break
case 'patch':
// If this is not a pre-release version, it will increment the patch.
// If it is a pre-release it will bump up to the same patch version.
// 1.2.0-5 patches to 1.2.0
// 1.2.0 patches to 1.2.1
if (this.prerelease.length === 0) {
this.patch++
}
this.prerelease = []
break
// This probably shouldn't be used publicly.
// 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
case 'pre': {
const base = Number(identifierBase) ? 1 : 0
if (this.prerelease.length === 0) {
this.prerelease = [base]
} else {
let i = this.prerelease.length
while (--i >= 0) {
if (typeof this.prerelease[i] === 'number') {
this.prerelease[i]++
i = -2
}
}
if (i === -1) {
// didn't increment anything
if (identifier === this.prerelease.join('.') && identifierBase === false) {
throw new Error('invalid increment argument: identifier already exists')
}
this.prerelease.push(base)
}
}
if (identifier) {
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
let prerelease = [identifier, base]
if (identifierBase === false) {
prerelease = [identifier]
}
if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
if (isNaN(this.prerelease[1])) {
this.prerelease = prerelease
}
} else {
this.prerelease = prerelease
}
}
break
}
default:
throw new Error(`invalid increment argument: ${release}`)
}
this.raw = this.format()
if (this.build.length) {
this.raw += `+${this.build.join('.')}`
}
return this
}
}
module.exports = SemVer

View File

@ -0,0 +1,8 @@
'use strict'
const parse = require('./parse')
const clean = (version, options) => {
const s = parse(version.trim().replace(/^[=v]+/, ''), options)
return s ? s.version : null
}
module.exports = clean

View File

@ -0,0 +1,54 @@
'use strict'
const eq = require('./eq')
const neq = require('./neq')
const gt = require('./gt')
const gte = require('./gte')
const lt = require('./lt')
const lte = require('./lte')
const cmp = (a, op, b, loose) => {
switch (op) {
case '===':
if (typeof a === 'object') {
a = a.version
}
if (typeof b === 'object') {
b = b.version
}
return a === b
case '!==':
if (typeof a === 'object') {
a = a.version
}
if (typeof b === 'object') {
b = b.version
}
return a !== b
case '':
case '=':
case '==':
return eq(a, b, loose)
case '!=':
return neq(a, b, loose)
case '>':
return gt(a, b, loose)
case '>=':
return gte(a, b, loose)
case '<':
return lt(a, b, loose)
case '<=':
return lte(a, b, loose)
default:
throw new TypeError(`Invalid operator: ${op}`)
}
}
module.exports = cmp

View File

@ -0,0 +1,62 @@
'use strict'
const SemVer = require('../classes/semver')
const parse = require('./parse')
const { safeRe: re, t } = require('../internal/re')
const coerce = (version, options) => {
if (version instanceof SemVer) {
return version
}
if (typeof version === 'number') {
version = String(version)
}
if (typeof version !== 'string') {
return null
}
options = options || {}
let match = null
if (!options.rtl) {
match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])
} else {
// Find the right-most coercible string that does not share
// a terminus with a more left-ward coercible string.
// Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
// With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
//
// Walk through the string checking with a /g regexp
// Manually set the index so as to pick up overlapping matches.
// Stop when we get a match that ends at the string end, since no
// coercible string can be more right-ward without the same terminus.
const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]
let next
while ((next = coerceRtlRegex.exec(version)) &&
(!match || match.index + match[0].length !== version.length)
) {
if (!match ||
next.index + next[0].length !== match.index + match[0].length) {
match = next
}
coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length
}
// leave it in a clean state
coerceRtlRegex.lastIndex = -1
}
if (match === null) {
return null
}
const major = match[2]
const minor = match[3] || '0'
const patch = match[4] || '0'
const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''
const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''
return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
}
module.exports = coerce

View File

@ -0,0 +1,9 @@
'use strict'
const SemVer = require('../classes/semver')
const compareBuild = (a, b, loose) => {
const versionA = new SemVer(a, loose)
const versionB = new SemVer(b, loose)
return versionA.compare(versionB) || versionA.compareBuild(versionB)
}
module.exports = compareBuild

View File

@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const compareLoose = (a, b) => compare(a, b, true)
module.exports = compareLoose

View File

@ -0,0 +1,7 @@
'use strict'
const SemVer = require('../classes/semver')
const compare = (a, b, loose) =>
new SemVer(a, loose).compare(new SemVer(b, loose))
module.exports = compare

View File

@ -0,0 +1,60 @@
'use strict'
const parse = require('./parse.js')
const diff = (version1, version2) => {
const v1 = parse(version1, null, true)
const v2 = parse(version2, null, true)
const comparison = v1.compare(v2)
if (comparison === 0) {
return null
}
const v1Higher = comparison > 0
const highVersion = v1Higher ? v1 : v2
const lowVersion = v1Higher ? v2 : v1
const highHasPre = !!highVersion.prerelease.length
const lowHasPre = !!lowVersion.prerelease.length
if (lowHasPre && !highHasPre) {
// Going from prerelease -> no prerelease requires some special casing
// If the low version has only a major, then it will always be a major
// Some examples:
// 1.0.0-1 -> 1.0.0
// 1.0.0-1 -> 1.1.1
// 1.0.0-1 -> 2.0.0
if (!lowVersion.patch && !lowVersion.minor) {
return 'major'
}
// If the main part has no difference
if (lowVersion.compareMain(highVersion) === 0) {
if (lowVersion.minor && !lowVersion.patch) {
return 'minor'
}
return 'patch'
}
}
// add the `pre` prefix if we are going to a prerelease version
const prefix = highHasPre ? 'pre' : ''
if (v1.major !== v2.major) {
return prefix + 'major'
}
if (v1.minor !== v2.minor) {
return prefix + 'minor'
}
if (v1.patch !== v2.patch) {
return prefix + 'patch'
}
// high and low are preleases
return 'prerelease'
}
module.exports = diff

View File

@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const eq = (a, b, loose) => compare(a, b, loose) === 0
module.exports = eq

View File

@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const gt = (a, b, loose) => compare(a, b, loose) > 0
module.exports = gt

View File

@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const gte = (a, b, loose) => compare(a, b, loose) >= 0
module.exports = gte

View File

@ -0,0 +1,21 @@
'use strict'
const SemVer = require('../classes/semver')
const inc = (version, release, options, identifier, identifierBase) => {
if (typeof (options) === 'string') {
identifierBase = identifier
identifier = options
options = undefined
}
try {
return new SemVer(
version instanceof SemVer ? version.version : version,
options
).inc(release, identifier, identifierBase).version
} catch (er) {
return null
}
}
module.exports = inc

View File

@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const lt = (a, b, loose) => compare(a, b, loose) < 0
module.exports = lt

View File

@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const lte = (a, b, loose) => compare(a, b, loose) <= 0
module.exports = lte

View File

@ -0,0 +1,5 @@
'use strict'
const SemVer = require('../classes/semver')
const major = (a, loose) => new SemVer(a, loose).major
module.exports = major

View File

@ -0,0 +1,5 @@
'use strict'
const SemVer = require('../classes/semver')
const minor = (a, loose) => new SemVer(a, loose).minor
module.exports = minor

View File

@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const neq = (a, b, loose) => compare(a, b, loose) !== 0
module.exports = neq

View File

@ -0,0 +1,18 @@
'use strict'
const SemVer = require('../classes/semver')
const parse = (version, options, throwErrors = false) => {
if (version instanceof SemVer) {
return version
}
try {
return new SemVer(version, options)
} catch (er) {
if (!throwErrors) {
return null
}
throw er
}
}
module.exports = parse

View File

@ -0,0 +1,5 @@
'use strict'
const SemVer = require('../classes/semver')
const patch = (a, loose) => new SemVer(a, loose).patch
module.exports = patch

View File

@ -0,0 +1,8 @@
'use strict'
const parse = require('./parse')
const prerelease = (version, options) => {
const parsed = parse(version, options)
return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
module.exports = prerelease

View File

@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const rcompare = (a, b, loose) => compare(b, a, loose)
module.exports = rcompare

View File

@ -0,0 +1,5 @@
'use strict'
const compareBuild = require('./compare-build')
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
module.exports = rsort

View File

@ -0,0 +1,12 @@
'use strict'
const Range = require('../classes/range')
const satisfies = (version, range, options) => {
try {
range = new Range(range, options)
} catch (er) {
return false
}
return range.test(version)
}
module.exports = satisfies

View File

@ -0,0 +1,5 @@
'use strict'
const compareBuild = require('./compare-build')
const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
module.exports = sort

View File

@ -0,0 +1,8 @@
'use strict'
const parse = require('./parse')
const valid = (version, options) => {
const v = parse(version, options)
return v ? v.version : null
}
module.exports = valid

View File

@ -0,0 +1,91 @@
'use strict'
// just pre-load all the stuff that index.js lazily exports
const internalRe = require('./internal/re')
const constants = require('./internal/constants')
const SemVer = require('./classes/semver')
const identifiers = require('./internal/identifiers')
const parse = require('./functions/parse')
const valid = require('./functions/valid')
const clean = require('./functions/clean')
const inc = require('./functions/inc')
const diff = require('./functions/diff')
const major = require('./functions/major')
const minor = require('./functions/minor')
const patch = require('./functions/patch')
const prerelease = require('./functions/prerelease')
const compare = require('./functions/compare')
const rcompare = require('./functions/rcompare')
const compareLoose = require('./functions/compare-loose')
const compareBuild = require('./functions/compare-build')
const sort = require('./functions/sort')
const rsort = require('./functions/rsort')
const gt = require('./functions/gt')
const lt = require('./functions/lt')
const eq = require('./functions/eq')
const neq = require('./functions/neq')
const gte = require('./functions/gte')
const lte = require('./functions/lte')
const cmp = require('./functions/cmp')
const coerce = require('./functions/coerce')
const Comparator = require('./classes/comparator')
const Range = require('./classes/range')
const satisfies = require('./functions/satisfies')
const toComparators = require('./ranges/to-comparators')
const maxSatisfying = require('./ranges/max-satisfying')
const minSatisfying = require('./ranges/min-satisfying')
const minVersion = require('./ranges/min-version')
const validRange = require('./ranges/valid')
const outside = require('./ranges/outside')
const gtr = require('./ranges/gtr')
const ltr = require('./ranges/ltr')
const intersects = require('./ranges/intersects')
const simplifyRange = require('./ranges/simplify')
const subset = require('./ranges/subset')
module.exports = {
parse,
valid,
clean,
inc,
diff,
major,
minor,
patch,
prerelease,
compare,
rcompare,
compareLoose,
compareBuild,
sort,
rsort,
gt,
lt,
eq,
neq,
gte,
lte,
cmp,
coerce,
Comparator,
Range,
satisfies,
toComparators,
maxSatisfying,
minSatisfying,
minVersion,
validRange,
outside,
gtr,
ltr,
intersects,
simplifyRange,
subset,
SemVer,
re: internalRe.re,
src: internalRe.src,
tokens: internalRe.t,
SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
RELEASE_TYPES: constants.RELEASE_TYPES,
compareIdentifiers: identifiers.compareIdentifiers,
rcompareIdentifiers: identifiers.rcompareIdentifiers,
}

View File

@ -0,0 +1,37 @@
'use strict'
// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
const SEMVER_SPEC_VERSION = '2.0.0'
const MAX_LENGTH = 256
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
/* istanbul ignore next */ 9007199254740991
// Max safe segment length for coercion.
const MAX_SAFE_COMPONENT_LENGTH = 16
// Max safe length for a build identifier. The max length minus 6 characters for
// the shortest version with a build 0.0.0+BUILD.
const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6
const RELEASE_TYPES = [
'major',
'premajor',
'minor',
'preminor',
'patch',
'prepatch',
'prerelease',
]
module.exports = {
MAX_LENGTH,
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_SAFE_INTEGER,
RELEASE_TYPES,
SEMVER_SPEC_VERSION,
FLAG_INCLUDE_PRERELEASE: 0b001,
FLAG_LOOSE: 0b010,
}

View File

@ -0,0 +1,11 @@
'use strict'
const debug = (
typeof process === 'object' &&
process.env &&
process.env.NODE_DEBUG &&
/\bsemver\b/i.test(process.env.NODE_DEBUG)
) ? (...args) => console.error('SEMVER', ...args)
: () => {}
module.exports = debug

View File

@ -0,0 +1,25 @@
'use strict'
const numeric = /^[0-9]+$/
const compareIdentifiers = (a, b) => {
const anum = numeric.test(a)
const bnum = numeric.test(b)
if (anum && bnum) {
a = +a
b = +b
}
return a === b ? 0
: (anum && !bnum) ? -1
: (bnum && !anum) ? 1
: a < b ? -1
: 1
}
const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
module.exports = {
compareIdentifiers,
rcompareIdentifiers,
}

View File

@ -0,0 +1,42 @@
'use strict'
class LRUCache {
constructor () {
this.max = 1000
this.map = new Map()
}
get (key) {
const value = this.map.get(key)
if (value === undefined) {
return undefined
} else {
// Remove the key from the map and add it to the end
this.map.delete(key)
this.map.set(key, value)
return value
}
}
delete (key) {
return this.map.delete(key)
}
set (key, value) {
const deleted = this.delete(key)
if (!deleted && value !== undefined) {
// If cache is full, delete the least recently used item
if (this.map.size >= this.max) {
const firstKey = this.map.keys().next().value
this.delete(firstKey)
}
this.map.set(key, value)
}
return this
}
}
module.exports = LRUCache

View File

@ -0,0 +1,17 @@
'use strict'
// parse out just the options we care about
const looseOption = Object.freeze({ loose: true })
const emptyOpts = Object.freeze({ })
const parseOptions = options => {
if (!options) {
return emptyOpts
}
if (typeof options !== 'object') {
return looseOption
}
return options
}
module.exports = parseOptions

View File

@ -0,0 +1,223 @@
'use strict'
const {
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_LENGTH,
} = require('./constants')
const debug = require('./debug')
exports = module.exports = {}
// The actual regexps go on exports.re
const re = exports.re = []
const safeRe = exports.safeRe = []
const src = exports.src = []
const safeSrc = exports.safeSrc = []
const t = exports.t = {}
let R = 0
const LETTERDASHNUMBER = '[a-zA-Z0-9-]'
// Replace some greedy regex tokens to prevent regex dos issues. These regex are
// used internally via the safeRe object since all inputs in this library get
// normalized first to trim and collapse all extra whitespace. The original
// regexes are exported for userland consumption and lower level usage. A
// future breaking change could export the safer regex only with a note that
// all input should have extra whitespace removed.
const safeRegexReplacements = [
['\\s', 1],
['\\d', MAX_LENGTH],
[LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
]
const makeSafeRegex = (value) => {
for (const [token, max] of safeRegexReplacements) {
value = value
.split(`${token}*`).join(`${token}{0,${max}}`)
.split(`${token}+`).join(`${token}{1,${max}}`)
}
return value
}
const createToken = (name, value, isGlobal) => {
const safe = makeSafeRegex(value)
const index = R++
debug(name, index, value)
t[name] = index
src[index] = value
safeSrc[index] = safe
re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)
}
// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
createToken('NUMERICIDENTIFIERLOOSE', '\\d+')
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)
// ## Main Version
// Three dot-separated numeric identifiers.
createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})`)
createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})`)
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
// Non-numberic identifiers include numberic identifiers but can be longer.
// Therefore non-numberic identifiers must go first.
createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]
}|${src[t.NUMERICIDENTIFIER]})`)
createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]
}|${src[t.NUMERICIDENTIFIERLOOSE]})`)
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups. The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
}${src[t.PRERELEASE]}?${
src[t.BUILD]}?`)
createToken('FULL', `^${src[t.FULLPLAIN]}$`)
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
}${src[t.PRERELEASELOOSE]}?${
src[t.BUILD]}?`)
createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
createToken('GTLT', '((?:<|>)?=?)')
// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:${src[t.PRERELEASE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:${src[t.PRERELEASELOOSE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
// Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCEPLAIN', `${'(^|[^\\d])' +
'(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)
createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`)
createToken('COERCEFULL', src[t.COERCEPLAIN] +
`(?:${src[t.PRERELEASE]})?` +
`(?:${src[t.BUILD]})?` +
`(?:$|[^\\d])`)
createToken('COERCERTL', src[t.COERCE], true)
createToken('COERCERTLFULL', src[t.COERCEFULL], true)
// Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)')
createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
exports.tildeTrimReplace = '$1~'
createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
// Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)')
createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
exports.caretTrimReplace = '$1^'
createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
// A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
exports.comparatorTrimReplace = '$1$2$3'
// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAIN]})` +
`\\s*$`)
createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAINLOOSE]})` +
`\\s*$`)
// Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*')
// >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')

View File

@ -0,0 +1,78 @@
{
"name": "semver",
"version": "7.7.2",
"description": "The semantic version parser used by npm.",
"main": "index.js",
"scripts": {
"test": "tap",
"snap": "tap",
"lint": "npm run eslint",
"postlint": "template-oss-check",
"lintfix": "npm run eslint -- --fix",
"posttest": "npm run lint",
"template-oss-apply": "template-oss-apply --force",
"eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
},
"devDependencies": {
"@npmcli/eslint-config": "^5.0.0",
"@npmcli/template-oss": "4.24.3",
"benchmark": "^2.1.4",
"tap": "^16.0.0"
},
"license": "ISC",
"repository": {
"type": "git",
"url": "git+https://github.com/npm/node-semver.git"
},
"bin": {
"semver": "bin/semver.js"
},
"files": [
"bin/",
"lib/",
"classes/",
"functions/",
"internal/",
"ranges/",
"index.js",
"preload.js",
"range.bnf"
],
"tap": {
"timeout": 30,
"coverage-map": "map.js",
"nyc-arg": [
"--exclude",
"tap-snapshots/**"
]
},
"engines": {
"node": ">=10"
},
"author": "GitHub Inc.",
"templateOSS": {
"//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
"version": "4.24.3",
"engines": ">=10",
"distPaths": [
"classes/",
"functions/",
"internal/",
"ranges/",
"index.js",
"preload.js",
"range.bnf"
],
"allowPaths": [
"/classes/",
"/functions/",
"/internal/",
"/ranges/",
"/index.js",
"/preload.js",
"/range.bnf",
"/benchmarks"
],
"publish": "true"
}
}

View File

@ -0,0 +1,4 @@
'use strict'
// XXX remove in v8 or beyond
module.exports = require('./index.js')

View File

@ -0,0 +1,16 @@
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | [1-9] ( [0-9] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= parts
build ::= parts
parts ::= part ( '.' part ) *
part ::= nr | [-0-9A-Za-z]+

View File

@ -0,0 +1,6 @@
'use strict'
// Determine if version is greater than all the versions possible in the range.
const outside = require('./outside')
const gtr = (version, range, options) => outside(version, range, '>', options)
module.exports = gtr

View File

@ -0,0 +1,9 @@
'use strict'
const Range = require('../classes/range')
const intersects = (r1, r2, options) => {
r1 = new Range(r1, options)
r2 = new Range(r2, options)
return r1.intersects(r2, options)
}
module.exports = intersects

View File

@ -0,0 +1,6 @@
'use strict'
const outside = require('./outside')
// Determine if version is less than all the versions possible in the range
const ltr = (version, range, options) => outside(version, range, '<', options)
module.exports = ltr

View File

@ -0,0 +1,27 @@
'use strict'
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const maxSatisfying = (versions, range, options) => {
let max = null
let maxSV = null
let rangeObj = null
try {
rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!max || maxSV.compare(v) === -1) {
// compare(max, v, true)
max = v
maxSV = new SemVer(max, options)
}
}
})
return max
}
module.exports = maxSatisfying

View File

@ -0,0 +1,26 @@
'use strict'
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const minSatisfying = (versions, range, options) => {
let min = null
let minSV = null
let rangeObj = null
try {
rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!min || minSV.compare(v) === 1) {
// compare(min, v, true)
min = v
minSV = new SemVer(min, options)
}
}
})
return min
}
module.exports = minSatisfying

View File

@ -0,0 +1,63 @@
'use strict'
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const gt = require('../functions/gt')
const minVersion = (range, loose) => {
range = new Range(range, loose)
let minver = new SemVer('0.0.0')
if (range.test(minver)) {
return minver
}
minver = new SemVer('0.0.0-0')
if (range.test(minver)) {
return minver
}
minver = null
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i]
let setMin = null
comparators.forEach((comparator) => {
// Clone to avoid manipulating the comparator's semver object.
const compver = new SemVer(comparator.semver.version)
switch (comparator.operator) {
case '>':
if (compver.prerelease.length === 0) {
compver.patch++
} else {
compver.prerelease.push(0)
}
compver.raw = compver.format()
/* fallthrough */
case '':
case '>=':
if (!setMin || gt(compver, setMin)) {
setMin = compver
}
break
case '<':
case '<=':
/* Ignore maximum versions */
break
/* istanbul ignore next */
default:
throw new Error(`Unexpected operation: ${comparator.operator}`)
}
})
if (setMin && (!minver || gt(minver, setMin))) {
minver = setMin
}
}
if (minver && range.test(minver)) {
return minver
}
return null
}
module.exports = minVersion

View File

@ -0,0 +1,82 @@
'use strict'
const SemVer = require('../classes/semver')
const Comparator = require('../classes/comparator')
const { ANY } = Comparator
const Range = require('../classes/range')
const satisfies = require('../functions/satisfies')
const gt = require('../functions/gt')
const lt = require('../functions/lt')
const lte = require('../functions/lte')
const gte = require('../functions/gte')
const outside = (version, range, hilo, options) => {
version = new SemVer(version, options)
range = new Range(range, options)
let gtfn, ltefn, ltfn, comp, ecomp
switch (hilo) {
case '>':
gtfn = gt
ltefn = lte
ltfn = lt
comp = '>'
ecomp = '>='
break
case '<':
gtfn = lt
ltefn = gte
ltfn = gt
comp = '<'
ecomp = '<='
break
default:
throw new TypeError('Must provide a hilo val of "<" or ">"')
}
// If it satisfies the range it is not outside
if (satisfies(version, range, options)) {
return false
}
// From now on, variable terms are as if we're in "gtr" mode.
// but note that everything is flipped for the "ltr" function.
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i]
let high = null
let low = null
comparators.forEach((comparator) => {
if (comparator.semver === ANY) {
comparator = new Comparator('>=0.0.0')
}
high = high || comparator
low = low || comparator
if (gtfn(comparator.semver, high.semver, options)) {
high = comparator
} else if (ltfn(comparator.semver, low.semver, options)) {
low = comparator
}
})
// If the edge version comparator has a operator then our version
// isn't outside it
if (high.operator === comp || high.operator === ecomp) {
return false
}
// If the lowest version comparator has an operator and our version
// is less than it then it isn't higher than the range
if ((!low.operator || low.operator === comp) &&
ltefn(version, low.semver)) {
return false
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
return false
}
}
return true
}
module.exports = outside

View File

@ -0,0 +1,49 @@
'use strict'
// given a set of versions and a range, create a "simplified" range
// that includes the same versions that the original range does
// If the original range is shorter than the simplified one, return that.
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')
module.exports = (versions, range, options) => {
const set = []
let first = null
let prev = null
const v = versions.sort((a, b) => compare(a, b, options))
for (const version of v) {
const included = satisfies(version, range, options)
if (included) {
prev = version
if (!first) {
first = version
}
} else {
if (prev) {
set.push([first, prev])
}
prev = null
first = null
}
}
if (first) {
set.push([first, null])
}
const ranges = []
for (const [min, max] of set) {
if (min === max) {
ranges.push(min)
} else if (!max && min === v[0]) {
ranges.push('*')
} else if (!max) {
ranges.push(`>=${min}`)
} else if (min === v[0]) {
ranges.push(`<=${max}`)
} else {
ranges.push(`${min} - ${max}`)
}
}
const simplified = ranges.join(' || ')
const original = typeof range.raw === 'string' ? range.raw : String(range)
return simplified.length < original.length ? simplified : range
}

View File

@ -0,0 +1,249 @@
'use strict'
const Range = require('../classes/range.js')
const Comparator = require('../classes/comparator.js')
const { ANY } = Comparator
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')
// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
// - Every simple range `r1, r2, ...` is a null set, OR
// - Every simple range `r1, r2, ...` which is not a null set is a subset of
// some `R1, R2, ...`
//
// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
// - If c is only the ANY comparator
// - If C is only the ANY comparator, return true
// - Else if in prerelease mode, return false
// - else replace c with `[>=0.0.0]`
// - If C is only the ANY comparator
// - if in prerelease mode, return true
// - else replace C with `[>=0.0.0]`
// - Let EQ be the set of = comparators in c
// - If EQ is more than one, return true (null set)
// - Let GT be the highest > or >= comparator in c
// - Let LT be the lowest < or <= comparator in c
// - If GT and LT, and GT.semver > LT.semver, return true (null set)
// - If any C is a = range, and GT or LT are set, return false
// - If EQ
// - If GT, and EQ does not satisfy GT, return true (null set)
// - If LT, and EQ does not satisfy LT, return true (null set)
// - If EQ satisfies every C, return true
// - Else return false
// - If GT
// - If GT.semver is lower than any > or >= comp in C, return false
// - If GT is >=, and GT.semver does not satisfy every C, return false
// - If GT.semver has a prerelease, and not in prerelease mode
// - If no C has a prerelease and the GT.semver tuple, return false
// - If LT
// - If LT.semver is greater than any < or <= comp in C, return false
// - If LT is <=, and LT.semver does not satisfy every C, return false
// - If GT.semver has a prerelease, and not in prerelease mode
// - If no C has a prerelease and the LT.semver tuple, return false
// - Else return true
const subset = (sub, dom, options = {}) => {
if (sub === dom) {
return true
}
sub = new Range(sub, options)
dom = new Range(dom, options)
let sawNonNull = false
OUTER: for (const simpleSub of sub.set) {
for (const simpleDom of dom.set) {
const isSub = simpleSubset(simpleSub, simpleDom, options)
sawNonNull = sawNonNull || isSub !== null
if (isSub) {
continue OUTER
}
}
// the null set is a subset of everything, but null simple ranges in
// a complex range should be ignored. so if we saw a non-null range,
// then we know this isn't a subset, but if EVERY simple range was null,
// then it is a subset.
if (sawNonNull) {
return false
}
}
return true
}
const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]
const minimumVersion = [new Comparator('>=0.0.0')]
const simpleSubset = (sub, dom, options) => {
if (sub === dom) {
return true
}
if (sub.length === 1 && sub[0].semver === ANY) {
if (dom.length === 1 && dom[0].semver === ANY) {
return true
} else if (options.includePrerelease) {
sub = minimumVersionWithPreRelease
} else {
sub = minimumVersion
}
}
if (dom.length === 1 && dom[0].semver === ANY) {
if (options.includePrerelease) {
return true
} else {
dom = minimumVersion
}
}
const eqSet = new Set()
let gt, lt
for (const c of sub) {
if (c.operator === '>' || c.operator === '>=') {
gt = higherGT(gt, c, options)
} else if (c.operator === '<' || c.operator === '<=') {
lt = lowerLT(lt, c, options)
} else {
eqSet.add(c.semver)
}
}
if (eqSet.size > 1) {
return null
}
let gtltComp
if (gt && lt) {
gtltComp = compare(gt.semver, lt.semver, options)
if (gtltComp > 0) {
return null
} else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
return null
}
}
// will iterate one or zero times
for (const eq of eqSet) {
if (gt && !satisfies(eq, String(gt), options)) {
return null
}
if (lt && !satisfies(eq, String(lt), options)) {
return null
}
for (const c of dom) {
if (!satisfies(eq, String(c), options)) {
return false
}
}
return true
}
let higher, lower
let hasDomLT, hasDomGT
// if the subset has a prerelease, we need a comparator in the superset
// with the same tuple and a prerelease, or it's not a subset
let needDomLTPre = lt &&
!options.includePrerelease &&
lt.semver.prerelease.length ? lt.semver : false
let needDomGTPre = gt &&
!options.includePrerelease &&
gt.semver.prerelease.length ? gt.semver : false
// exception: <1.2.3-0 is the same as <1.2.3
if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
needDomLTPre = false
}
for (const c of dom) {
hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
if (gt) {
if (needDomGTPre) {
if (c.semver.prerelease && c.semver.prerelease.length &&
c.semver.major === needDomGTPre.major &&
c.semver.minor === needDomGTPre.minor &&
c.semver.patch === needDomGTPre.patch) {
needDomGTPre = false
}
}
if (c.operator === '>' || c.operator === '>=') {
higher = higherGT(gt, c, options)
if (higher === c && higher !== gt) {
return false
}
} else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
return false
}
}
if (lt) {
if (needDomLTPre) {
if (c.semver.prerelease && c.semver.prerelease.length &&
c.semver.major === needDomLTPre.major &&
c.semver.minor === needDomLTPre.minor &&
c.semver.patch === needDomLTPre.patch) {
needDomLTPre = false
}
}
if (c.operator === '<' || c.operator === '<=') {
lower = lowerLT(lt, c, options)
if (lower === c && lower !== lt) {
return false
}
} else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
return false
}
}
if (!c.operator && (lt || gt) && gtltComp !== 0) {
return false
}
}
// if there was a < or >, and nothing in the dom, then must be false
// UNLESS it was limited by another range in the other direction.
// Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
if (gt && hasDomLT && !lt && gtltComp !== 0) {
return false
}
if (lt && hasDomGT && !gt && gtltComp !== 0) {
return false
}
// we needed a prerelease range in a specific tuple, but didn't get one
// then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,
// because it includes prereleases in the 1.2.3 tuple
if (needDomGTPre || needDomLTPre) {
return false
}
return true
}
// >=1.2.3 is lower than >1.2.3
const higherGT = (a, b, options) => {
if (!a) {
return b
}
const comp = compare(a.semver, b.semver, options)
return comp > 0 ? a
: comp < 0 ? b
: b.operator === '>' && a.operator === '>=' ? b
: a
}
// <=1.2.3 is higher than <1.2.3
const lowerLT = (a, b, options) => {
if (!a) {
return b
}
const comp = compare(a.semver, b.semver, options)
return comp < 0 ? a
: comp > 0 ? b
: b.operator === '<' && a.operator === '<=' ? b
: a
}
module.exports = subset

View File

@ -0,0 +1,10 @@
'use strict'
const Range = require('../classes/range')
// Mostly just for testing and legacy API reasons
const toComparators = (range, options) =>
new Range(range, options).set
.map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
module.exports = toComparators

View File

@ -0,0 +1,13 @@
'use strict'
const Range = require('../classes/range')
const validRange = (range, options) => {
try {
// Return '*' instead of '' so that truthiness works.
// This will throw if it's invalid anyway
return new Range(range, options).range || '*'
} catch (er) {
return null
}
}
module.exports = validRange

102
app_vue/node_modules/vue-eslint-parser/package.json generated vendored Normal file
View File

@ -0,0 +1,102 @@
{
"name": "vue-eslint-parser",
"version": "8.3.0",
"description": "The ESLint custom parser for `.vue` files.",
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"main": "index.js",
"files": [
"index.*"
],
"peerDependencies": {
"eslint": ">=6.0.0"
},
"dependencies": {
"debug": "^4.3.2",
"eslint-scope": "^7.0.0",
"eslint-visitor-keys": "^3.1.0",
"espree": "^9.0.0",
"esquery": "^1.4.0",
"lodash": "^4.17.21",
"semver": "^7.3.5"
},
"devDependencies": {
"@babel/core": "^7.16.0",
"@babel/eslint-parser": "^7.16.3",
"@babel/plugin-syntax-decorators": "^7.16.0",
"@babel/plugin-syntax-pipeline-operator": "^7.16.0",
"@babel/plugin-syntax-typescript": "^7.16.0",
"@types/debug": "^4.1.7",
"@types/eslint": "^7.29.0",
"@types/estree": "^0.0.50",
"@types/lodash": "^4.14.177",
"@types/mocha": "^9.0.0",
"@types/node": "^16.11.7",
"@types/semver": "^7.3.9",
"@typescript-eslint/eslint-plugin": "^5.4.0",
"@typescript-eslint/parser": "^5.4.0",
"chokidar": "^3.5.2",
"codecov": "^3.8.3",
"cross-spawn": "^7.0.3",
"dts-bundle": "^0.7.3",
"eslint": "^8.2.0",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-jsonc": "^2.0.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-node-dependencies": "^0.6.0",
"eslint-plugin-prettier": "^4.0.0",
"fs-extra": "^10.0.0",
"jsonc-eslint-parser": "^2.0.3",
"mocha": "^9.1.3",
"npm-run-all": "^4.1.5",
"nyc": "^15.1.0",
"opener": "^1.5.2",
"prettier": "^2.4.1",
"rimraf": "^3.0.2",
"rollup": "^2.60.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-sourcemaps": "^0.6.3",
"ts-node": "^10.4.0",
"typescript": "~4.4.4",
"wait-on": "^6.0.0",
"warun": "^1.0.0"
},
"scripts": {
"prebuild": "npm run -s clean",
"build": "tsc --module es2015 && rollup -c -o index.js && dts-bundle --name vue-eslint-parser --main .temp/index.d.ts --out ../index.d.ts",
"clean": "rimraf .nyc_output .temp coverage index.*",
"codecov": "codecov",
"coverage": "opener ./coverage/lcov-report/index.html",
"lint": "eslint src test package.json --ext .js,.ts",
"setup": "git submodule update --init && cd test/fixtures/eslint && npm install",
"pretest": "run-s build lint",
"test": "npm run -s test:mocha",
"test:mocha": "nyc mocha \"test/*.js\" --reporter dot --timeout 60000",
"test:debug": "mocha --require ts-node/register/transpile-only \"test/*.js\" --reporter dot --timeout 60000",
"preupdate-fixtures": "npm run -s build",
"update-fixtures": "node scripts/update-fixtures-ast.js && node scripts/update-fixtures-document-fragment.js",
"preversion": "npm test",
"version": "npm run -s build",
"postversion": "git push && git push --tags",
"prewatch": "npm run -s clean",
"watch": "run-p watch:*",
"watch:tsc": "tsc --module es2015 --watch",
"watch:rollup": "wait-on .temp/index.js && rollup -c -o index.js --watch",
"watch:test": "wait-on index.js && warun index.js \"test/*.js\" \"test/fixtures/ast/*/*.json\" \"test/fixtures/*\" --debounce 1000 --no-initial -- nyc mocha \"test/*.js\" --reporter dot --timeout 10000",
"watch:update-ast": "wait-on index.js && warun index.js \"test/fixtures/ast/*/*.vue\" -- node scripts/update-fixtures-ast.js",
"watch:coverage-report": "wait-on coverage/lcov-report/index.html && opener coverage/lcov-report/index.html"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/vue-eslint-parser.git"
},
"keywords": [],
"author": "Toru Nagashima",
"license": "MIT",
"bugs": {
"url": "https://github.com/vuejs/vue-eslint-parser/issues"
},
"homepage": "https://github.com/vuejs/vue-eslint-parser#readme",
"funding": "https://github.com/sponsors/mysticatea"
}