[MIG] document_page_reference: Migration to 18.0

This commit is contained in:
Anusha 2025-05-09 07:38:43 +02:00
parent 2735ec9612
commit 55bee4bbcb
5825 changed files with 542633 additions and 163 deletions

View File

@ -5,18 +5,18 @@
"name": "Document Page Reference",
"summary": """
Include references on document pages""",
"version": "16.0.1.0.1",
"version": "18.0.1.0.0",
"license": "AGPL-3",
"author": "Creu Blanca,Odoo Community Association (OCA)",
"website": "https://github.com/OCA/knowledge",
"depends": ["document_page", "web_editor"],
"depends": ["document_page"],
"data": [
"views/document_page.xml",
"views/report_document_page.xml",
],
"assets": {
"web.assets_backend": [
"document_page_reference/static/src/js/**/*",
"document_page_reference/static/src/js/editor.js",
],
},
"maintainers": ["etobella"],

View File

@ -2,57 +2,27 @@
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
import re
from odoo import _, api, fields, models, tools
from jinja2.sandbox import SandboxedEnvironment
from markupsafe import Markup
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
from odoo.tools.misc import html_escape
from odoo.addons.http_routing.models.ir_http import slugify
from odoo.tools import html_escape
_logger = logging.getLogger(__name__)
try:
import re
from jinja2 import Undefined
from jinja2.lexer import name_re as old_name_re
from jinja2.sandbox import SandboxedEnvironment
name_re = re.compile("^%s$" % old_name_re.pattern)
class Context(SandboxedEnvironment.context_class):
def resolve(self, key):
res = super().resolve(key)
if not isinstance(res, Undefined):
return res
return self.parent["ref"](key)
class Environment(SandboxedEnvironment):
context_class = Context
mako_template_env = Environment(
block_start_string="<%",
block_end_string="%>",
variable_start_string="${",
variable_end_string="}",
comment_start_string="<%doc>",
comment_end_string="</%doc>",
line_statement_prefix="%",
line_comment_prefix="##",
trim_blocks=True, # do not output newline after blocks
autoescape=False,
)
except Exception:
_logger.error("Jinja2 is not available")
env = SandboxedEnvironment(autoescape=False)
class DocumentPage(models.Model):
_inherit = "document.page"
_description = "Document Page"
reference = fields.Char(
help="Used to find the document, it can contain letters, numbers and _"
reference = fields.Char(required=True)
content_parsed = fields.Html(
"Parsed Content", compute="_compute_content_parsed", sanitize=False, store=True
)
content_parsed = fields.Html(compute="_compute_content_parsed")
def get_formview_action(self, access_uid=None):
res = super().get_formview_action(access_uid)
@ -60,90 +30,71 @@ class DocumentPage(models.Model):
res["views"] = [(view_id, "form")]
return res
@api.depends("history_head")
@api.depends("content")
def _compute_content_parsed(self):
for record in self:
content = record.get_content()
if content == "<p>" and self.content != "<p>":
_logger.error(
"Template from page with id = %s cannot be processed correctly"
% self.id
)
content = self.content
record.content_parsed = content
try:
raw = record.content or ""
converted = re.sub(r"\$\{([\w_]+)\}", r"{{ resolve('\1') }}", raw)
template = env.from_string(converted)
rendered = template.render(resolve=record._resolve_reference)
record.content_parsed = rendered
except Exception as e:
_logger.warning("Render failed for %s: %s", record.id, e)
record.content_parsed = record.content or ""
@api.constrains("reference")
def _check_reference(self):
for record in self:
if not record.reference:
def _check_reference_validity(self):
for rec in self:
if not rec.reference:
continue
record._validate_reference(record=record)
@api.model
def _validate_reference(self, record=None, reference=None):
if not reference:
reference = self.reference
if not name_re.match(reference):
raise ValidationError(_("Reference is not valid"))
uniq_domain = [("reference", "=", reference)]
if record:
uniq_domain += [("id", "!=", record.id)]
if self.search(uniq_domain):
raise ValidationError(_("Reference must be unique"))
regex = r"^[a-zA-Z_][a-zA-Z0-9_]*$"
if not re.match(regex, rec.reference):
raise ValidationError(_("Reference is not valid"))
domain = [("reference", "=", rec.reference), ("id", "!=", rec.id)]
if self.search(domain):
raise ValidationError(_("Reference must be unique"))
def _get_document(self, code):
# Hook created in order to add check on other models
document = self.search([("reference", "=", code)])
if document:
return document
else:
return self.env[self._name]
def get_reference(self, code):
element = self._get_document(code)
if self.env.context.get("raw_reference", False):
return html_escape(element.display_name)
text = """<a href="#" class="oe_direct_line"
data-oe-model="%s" data-oe-id="%s" name="%s">%s</a>
"""
if not element:
text = "<i>%s</i>" % text
res = text % (
element._name,
element and element.id or "",
code,
html_escape(element.display_name or code),
)
return res
def _get_template_variables(self):
return {"ref": self.get_reference}
return self.search([("reference", "=", code)], limit=1)
def get_content(self):
try:
content = self.content
mako_env = mako_template_env
template = mako_env.from_string(tools.ustr(content))
return template.render(self._get_template_variables())
except Exception:
_logger.error(
"Template from page with id = %s cannot be processed" % self.id
for record in self:
try:
raw = record.content or ""
converted = re.sub(r"\$\{([\w_]+)\}", r"{{ resolve('\1') }}", raw)
template = env.from_string(converted)
return template.render(resolve=record._resolve_reference)
except Exception:
_logger.error(
"Template from page with id = %s cannot be processed", record.id
)
return record.content
def _resolve_reference(self, code):
doc = self._get_document(code)
if self.env.context.get("raw_reference", False):
return html_escape(doc.display_name if doc else code)
sanitized_code = html_escape(code)
if not doc:
return (
f"<i><a href='#' class='oe_direct_line' "
f"data-oe-model='document.page' data-oe-id='' "
f"name='{sanitized_code}'>{sanitized_code}</a></i>"
)
return self.content
return (
f"<a href='#' class='oe_direct_line' data-oe-model='{doc._name}' "
f"data-oe-id='{doc.id}' name='{sanitized_code}'>"
f"{html_escape(doc.display_name)}</a>"
)
def get_raw_content(self):
return self.with_context(raw_reference=True).get_content()
return Markup(self.with_context(raw_reference=True).get_content())
@api.model_create_multi
def create(self, vals_list):
for vals in vals_list:
if not vals.get("reference"):
# Propose a default reference
reference = slugify(vals.get("name")).replace("-", "_")
try:
self._validate_reference(reference=reference)
vals["reference"] = reference
except ValidationError: # pylint: disable=W8138
# Do not fill reference.
pass
if not vals.get("reference") and vals.get("name"):
reference = self.env["ir.http"]._slugify(vals["name"]).replace("-", "_")
vals["reference"] = reference
return super().create(vals_list)

View File

@ -1,34 +1,32 @@
odoo.define("document_page_reference.backend", function (require) {
"use strict";
import {HtmlField, htmlField} from "@web/views/fields/html/html_field";
import {registry} from "@web/core/registry";
import {onMounted, useRef} from "@odoo/owl";
import {useService} from "@web/core/utils/hooks";
var field_registry = require("web.field_registry");
var FieldTextHtmlSimple = require("web_editor.field.html");
var FieldDocumentPage = FieldTextHtmlSimple.extend({
events: _.extend({}, FieldTextHtmlSimple.prototype.events, {
"click .oe_direct_line": "_onClickDirectLink",
}),
_onClickDirectLink: function (event) {
var self = this;
event.preventDefault();
event.stopPropagation();
var element = $(event.target).closest(".oe_direct_line")[0];
var default_reference = element.name;
var model = $(event.target).data("oe-model");
var id = $(event.target).data("oe-id");
var context = this.record.getContext(this.recordParams);
if (default_reference) {
context.default_reference = default_reference;
}
this._rpc({
model: model,
method: "get_formview_action",
args: [[parseInt(id, 10)]],
context: context,
}).then(function (action) {
self.trigger_up("do_action", {action: action});
class DocumentPageReferenceField extends HtmlField {
setup() {
super.setup();
this.orm = useService("orm");
this.action = useService("action");
onMounted(() => {
const links = document.querySelectorAll(".oe_direct_line");
links.forEach((link) => {
link.addEventListener("click", (event) =>
this._onClickDirectLink(event)
);
});
},
});
field_registry.add("document_page_reference", FieldDocumentPage);
return FieldDocumentPage;
});
}
_onClickDirectLink(event) {
const {oeModel: model, oeId} = event.target.dataset;
const id = parseInt(oeId, 10);
this.orm.call(model, "get_formview_action", [[id]], {}).then((action) => {
this.action.doAction(action);
});
}
}
registry.category("fields").add("document_page_reference", {
...htmlField,
component: DocumentPageReferenceField,
});

View File

@ -18,11 +18,13 @@ class TestDocumentReference(TransactionCase):
{"name": "Test Page 1", "content": "${r1}", "reference": "r2"}
)
def test_constrains_01(self):
def test_constraints_duplicate_reference(self):
"""Should raise if reference is not unique (same as another)."""
with self.assertRaises(ValidationError):
self.page2.write({"reference": self.page1.reference})
def test_constrains_02(self):
def test_constraints_invalid_reference(self):
"""Should raise if reference does not match the required pattern."""
with self.assertRaises(ValidationError):
self.page2.write({"reference": self.page2.reference + "-02"})
@ -35,7 +37,7 @@ class TestDocumentReference(TransactionCase):
self.assertEqual(self.page2.display_name, self.page1.get_raw_content())
def test_check_reference(self):
self.assertRegex(self.page1.content_parsed, ".*%s.*" % self.page2.display_name)
self.assertRegex(self.page1.content_parsed, f".*{self.page2.display_name}.*")
def test_no_reference(self):
self.page2.reference = "r3"
@ -48,31 +50,31 @@ class TestDocumentReference(TransactionCase):
{"name": "Test Page with no rEfErenCe", "content": "some content"}
)
self.assertEqual(new_page.reference, "test_page_with_no_reference")
new_page_duplicated_name = self.page_obj.create(
{
"name": "test page with no reference",
"content": "this should have an empty reference "
"because reference must be unique",
}
)
self.assertFalse(new_page_duplicated_name.reference)
with self.assertRaises(ValidationError):
new_page_duplicated_name = self.page_obj.create(
{
"name": "test page with no reference",
"content": "this should have an empty reference "
"because reference must be unique",
}
)
self.assertFalse(new_page_duplicated_name.reference)
def test_get_formview_action(self):
res = self.page1.get_formview_action()
view_id = self.env.ref("document_page.view_wiki_form").id
expected_result = {
expected_keys = {
"type": "ir.actions.act_window",
"context": {},
"res_model": "document.page",
"res_id": self.page1.id,
"view_mode": "form",
"view_type": "form",
"context": {},
"target": "current",
"views": [(view_id, "form")],
}
self.assertEqual(res, expected_result)
for key, expected_value in expected_keys.items():
self.assertEqual(res.get(key), expected_value, f"Mismatch in key: {key}")
def test_compute_content_parsed(self):
self.page1.content = "<p>"
self.page1.content = "<p></p>"
self.page1._compute_content_parsed()
self.assertEqual(str(self.page1.content_parsed), "<p></p>")

View File

@ -27,6 +27,7 @@
</field>
</field>
</record>
<record id="view_wiki_menu_form" model="ir.ui.view">
<field name="name">document.page.menu.form</field>
<field name="model">document.page</field>
@ -44,6 +45,7 @@
</field>
</field>
</record>
<record model="ir.ui.view" id="document_page_search_view">
<field name="name">document.page.search (in knowledge_reference)</field>
<field name="model">document.page</field>
@ -54,6 +56,7 @@
</field>
</field>
</record>
<record model="ir.ui.view" id="document_page_tree_view">
<field name="name">document.page.tree (in knowledge_reference)</field>
<field name="model">document.page</field>

View File

@ -8,7 +8,7 @@
<attribute name="t-if">1==0</attribute>
</xpath>
<xpath expr="//div[@t-raw='doc.content']" position="after">
<div t-raw="doc.get_raw_content()" />
<t t-out="doc.get_raw_content()" />
</xpath>
</template>
</odoo>

1
node_modules/.bin/acorn generated vendored Symbolic link
View File

@ -0,0 +1 @@
../acorn/bin/acorn

1
node_modules/.bin/eslint generated vendored Symbolic link
View File

@ -0,0 +1 @@
../eslint/bin/eslint.js

1
node_modules/.bin/eslint-config-prettier generated vendored Symbolic link
View File

@ -0,0 +1 @@
../eslint-config-prettier/bin/cli.js

1
node_modules/.bin/js-yaml generated vendored Symbolic link
View File

@ -0,0 +1 @@
../js-yaml/bin/js-yaml.js

1
node_modules/.bin/json5 generated vendored Symbolic link
View File

@ -0,0 +1 @@
../json5/lib/cli.js

1
node_modules/.bin/node-which generated vendored Symbolic link
View File

@ -0,0 +1 @@
../which/bin/node-which

1
node_modules/.bin/prettier generated vendored Symbolic link
View File

@ -0,0 +1 @@
../prettier/bin/prettier.cjs

1
node_modules/.bin/resolve generated vendored Symbolic link
View File

@ -0,0 +1 @@
../resolve/bin/resolve

1
node_modules/.bin/semver generated vendored Symbolic link
View File

@ -0,0 +1 @@
../semver/bin/semver.js

1
node_modules/.bin/xml2js generated vendored Symbolic link
View File

@ -0,0 +1 @@
../fast-xml-parser/cli.js

3830
node_modules/.package-lock.json generated vendored Normal file

File diff suppressed because it is too large Load Diff

604
node_modules/@es-joy/jsdoccomment/CHANGES.md generated vendored Normal file
View File

@ -0,0 +1,604 @@
# CHANGES for `@es-joy/jsdoccomment`
## 0.49.0
- fix: avoid changing `name` for `@template`; should be able to recover
optional brackets and defaults in AST
## 0.48.0
- chore: bump jsdoc-type-pratt-parser and devDeps.
## 0.47.0
- fix(`parseComment`): assume closing bracket of name is final instead of
first one
- chore: flat config/ESLint 9; change browser targets; lint; update devDeps.
## 0.46.0
- chore: update esquery, drop bundling of types, update devDeps
## 0.45.0
- feat: get following comment (experimental)
## 0.44.0
- feat: add `getNonJsdocComment` for getting non-JSDoc comments above node
## 0.43.1
- fix: for `@template` name parsing, ensure (default-)bracketed name is not broken with internal spaces.
## 0.43.0
This release brings surgical round trip parsing to generated AST and reconstruction of JSDoc comment blocks via: `parseComment` ->
`commentParserToESTree` -> `estreeToString`.
- feat: new option `spacing` for `commentParserToESTree`; the default is `compact` removing empty description lines.
Set to `preserve` to retain empty description lines.
- feat: new properties in the `JsdocBlock` generated AST `delimiterLineBreak` and `preterminalLineBreak` that encode
any line break after the opening `delimiter` and before the closing `terminal` string. Values are either `\n` or an
empty string.
- chore: update devDeps / switch to Vitest.
- New [API documentation](https://es-joy.github.io/jsdoccomment/).
Thanks:
- [@typhonrt](https://github.com/typhonrt)
## 0.42.0
- feat: expand argument for `parseComment` to accept a comment token string ([@typhonrt](https://github.com/typhonrt))
- chore: update devDeps.
## 0.41.0
- feat: look above surrounding parenthesis tokens for comment blocks, even if on a higher line than the corresponding AST structure
- chore: update comment-parser and devDeps.
## 0.40.1
- chore(TS): fix path issue
## 0.40.0
- chore: update comment-parser and devDeps.
- chore(TS): switch to NodeNext
## 0.39.4
- fix: include type exports for full inlineTags (and line) property support on blocks and tags
## 0.39.3
- fix: add type details for Node range and settings
## 0.39.2
- fix: export additional typedefs from index.js
## 0.39.1
- fix: typing export
## 0.39.0
- feat: types for test files and emit declaration files
- fix(estreeToString): add `JsdodInlineTag` stringify support
- refactor: lint
- docs: add `JsdocInlineTag` to README
- chore: update devDeps.
## 0.38.0
- feat: add parsing inline tags (#12); fixes #11
## 0.37.1
- chore: support Node 20
- chore: update esquery, devDeps.
## 0.37.0
## 0.37.0-pre.0
- fix: update `jsdoc-type-pratt-parser` (supports bracket indexes)
## 0.36.1
- fix(`getReducedASTNode`): stop checking for comment blocks at return
statement
## 0.36.0
- feat: add `hasPreterminalTagDescription` property
- fix: avoid description line properties if tag is present
- fix: ensure description and description lines added to terminal multi-line tag
## 0.35.0
- feat: add `hasPreterminalDescription` property
- fix: allow newline even for 1st line (after 0th)
## 0.34.0
- feat: add `descriptionStartLine` and `descriptionEndLine` properties
- fix: avoid duplication with 0 line comments
- chore: update devDeps.
## 0.33.4
- chore: republish as npm seems to have missed the release
## 0.33.3
- fix: ensure multi-line `description` includes newline except for
initial line descriptions
## 0.33.2
- fix: avoid repetition within multi-line descriptions
## 0.33.1
- fix: add to default no types: `description`, `example`, `file`,
`fileoverview`, `license`, `overview`, `see`, `summary`
- fix: add to no names: `file`, `fileoverview, `overview`
## 0.33.0
- chore: add Node 19 to `engines` (@RodEsp)
- chore: update devDeps. and build file accordingly
## 0.32.0
- feat: have comment checking stop at assignment patterns (comments for
defaults should not rise to function itself)
- chore: bump devDeps.
## 0.31.0
- feat: support default values with `@template` per
<https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#template>
## 0.30.0
- chore: bump `jsdoc-type-pratt-parser` and devDeps.
## 0.29.0
- fix: update `engines` as per current `getJSDocComment` behavior
- chore: update devDeps.
## 0.28.1
- fix(`getReducedASTNode`): token checking
- build: add Node 18 support (@WikiRik)
## 0.28.0
- chore: bump `engines` to support Node 18
## 0.27.0
- chore: bump `jsdoc-type-pratt-parser` and devDeps.
## 0.26.1
- fix(`estreeToString`): ensure `typeLines` may be picked up
## 0.26.0
- feat(`getJSDocComment`): allow function to detect comments just preceding a
parenthesized expression (these have no special AST but their tokens
have to be overpassed)
## 0.25.0
- feat(`parseComment`): properly support whitespace
- fix(`estreeToString`): carriage return placement for ending of JSDoc block
- fix(`commentParserToESTree`): avoid adding initial space before a tag if on
a single line
- test: make tests more accurate to jsdoc semantically
## 0.24.0
- feat(`estreeToString`): support stringification of `parsedType` but with
a new `preferRawType` option allowing the old behavior of using `rawType`
## 0.23.6
- fix(`commentParserToESTree`): ensure `postType` added after multi-line type
- fix(`estreeToString`): ensure `JsdocTypeLine` stringified with `initial` and
that they are joined together with newlines
## 0.23.5
- fix(`commentParserToESTree`): avoid duplicating tag names
## 0.23.4
- fix(`estreeToString`): add `delimiter`, etc. if adding `JsdocDescriptionLine`
for `JsdocBlock`
- fix(`estreeToString`): add line break when tags are present (unless already
ending in newline)
## 0.23.3
- fix(`estreeToString`): handle multi-line block descriptions followed by
tags with line break
## 0.23.2
- fix: ensure JsdocBlock stringifier has any initial whitespace on end line
## 0.23.1
- docs(README): update
## 0.23.0
- BREAKING CHANGE(`commentParserToESTree`): rename `start` and `end` to
`initial` and `terminal` to avoid any conflicts with Acorn-style parsers
- feat: add `initial` and `terminal` on `JsdocBlock`
## 0.22.2
- fix: preserve type tokens
- perf: cache tokenizers
## 0.22.1
- fix: ensure `getJSDocComment` does not treat block comments as JSDoc unless
their first asterisk is followed by whitespace
## 0.22.0
- fix: update dep. `jsdoc-type-pratt-parser`
- chore: update `comment-parser` and simplify as possible
## 0.21.2
- fix: only throw if the raw type is not empty
## 0.21.1
- fix: provide clearer error message for `throwOnTypeParsingErrors`
## 0.21.0
- feat: add `throwOnTypeParsingErrors` to receive run-time type parsing errors
for `parsedType`
- chore: update jsdoc-type-pratt-parser and devDeps.; also lints
## 0.20.1
- fix: resume catching bad parsed type (at least until
`jsdoc-type-pratt-parser` may support all expected types)
## 0.20.0
- feat: add estree stringifer
- fix: properly supports `name`/`postName` for multi-line type
- fix: allow pratt parser to fail (unless empty)
- fix: don't add tag postDelimiter when on 0 description line
- fix: avoid adding extra line when only name and no succeeding description
- docs: clarify re: `kind`
- test: add `parsedType` with correct mode; add tests
- chore: updates jsdoc-type-pratt-parser
- chore: updates devDeps.
## 0.19.0
### User-impacting
- feat: treat `@kind` as having no name
### Dev-impacting
- docs: jsdoc
- test: begin checking `jsdoccomment`
- test: adds lcov reporter and open script for it
- chore: update devDeps.
## 0.18.0
### User-impacting
- feat: add non-visitable `endLine` property (so can detect line number
when no description present)
- feat: supply `indent` default for `parseComment`
- fix: ensure `postName` gets a space for `@template` with a description
- fix: converting JSDoc comment with tag on same line as end (e.g., single
line) to AST
- chore: update `jsdoc-type-pratt-parser`
### Dev-impacting
- docs: add jsdoc blocks internally
- chore: update devDeps.
- test: avoid need for `expect`
- test: complete coverage for `commentHandler`, `parseComment` tests
## 0.17.0
### User-impacting
- Enhancement: Re-export `jsdoc-type-pratt-parser`
- Update: `jsdoc-type-pratt-parser` to 2.2.1
### Dev-impacting
- npm: Update devDeps.
## 0.16.0
### User-impacting
- Update: `jsdoc-type-pratt-parser` to 2.2.0
### Dev-impacting
- npm: Update devDeps.
## 0.15.0
### User-impacting
- Update: `jsdoc-type-pratt-parser` to 2.1.0
### Dev-impacting
- npm: Update devDeps.
## 0.14.2
### User-impacting
- Fix: Find comments previous to parentheses (used commonly in TypeScript)
### Dev-impacting
- npm: Update devDeps.
## 0.14.1
### User-impacting
- Update: `jsdoc-type-pratt-parser` to 2.0.2
## 0.14.0
### User-impacting
- Update: `jsdoc-type-pratt-parser` to 2.0.1
### Dev-impacting
- npm: Update devDeps.
## 0.13.0
### User-impacting
- Update: `comment-parser` to 1.3.0
- Fix: Allow comment on `ExportDefaultDeclaration`
## 0.12.0
### User-impacting
- Update: `jsdoc-type-pratt-parser` to 2.0.0
- Enhancement: Support Node 17 (@timgates42)
- Docs: Typo (@timgates42)
### Dev-impacting
- Linting: As per latest ash-nazg
- npm: Update devDeps.
## 0.11.0
- Update: For `@typescript/eslint-parser@5`, add `PropertyDefinition`
## 0.10.8
### User-impacting
- npm: Liberalize `engines` as per `comment-parser` change
- npm: Bump `comment-parser`
### Dev-impacting
- Linting: As per latest ash-nazg
- npm: Update devDeps.
## 0.10.7
- npm: Update comment-parser with CJS fix and re-exports
- npm: Update devDeps.
## 0.10.6
- Fix: Ensure copying latest build of `comment-parser`'s ESM utils
## 0.10.5
- npm: Bump fixed `jsdoc-type-pratt-parser` and devDeps.
## 0.10.4
- Fix: Bundle `comment-parser` nested imports so that IDEs (like Atom)
bundling older Node versions can still work. Still mirroring the
stricter `comment-parser` `engines` for now, however.
## 0.10.3
- npm: Avoid exporting nested subpaths for sake of older Node versions
## 0.10.2
- npm: Specify exact supported range: `^12.20 || ^14.14.0 || ^16`
## 0.10.1
- npm: Apply patch version of `comment-parser`
## 0.10.0
- npm: Point to stable `comment-parser`
## 0.9.0-alpha.6
### User-impacting
- Update: For `comment-parser` update, add `lineEnd`
## 0.9.0-alpha.5
### User-impacting
- npm: Bump `comment-parser` (for true ESM)
- Update: Remove extensions for packages for native ESM in `comment-parser` fix
### Dev-impacting
- npm: Update devDeps.
## 0.9.0-alpha.4
- Docs: Update repo info in `package.json`
## 0.9.0-alpha.3
- Fix: Due to `comment-parser` still needing changes, revert for now to alpha.1
## 0.9.0-alpha.2
### User-impacting
- npm: Bump `comment-parser` (for true ESM)
- Update: Remove extensions for packages for native ESM in `comment-parser` fix
### Dev-impacting
- npm: Update devDeps.
## 0.9.0-alpha.1
### User-impacting
- Breaking change: Indicate minimum for `engines` as Node >= 12
- npm: Bump `comment-parser`
### Dev-impacting
- npm: Lint cjs files
- npm: Fix eslint script
- npm: Update devDeps.
## 0.8.0
### User-impacting
- npm: Update `jsdoc-type-pratt-parser` (prerelease to stable patch)
### Dev-impacting
- npm: Update devDeps.
## 0.8.0-alpha.2
- Fix: Avoid erring with missing `typeLines`
## 0.8.0-alpha.1
- Breaking change: Export globally as `JsdocComment`
- Breaking change: Change `JSDoc` prefixes of all node types to `Jsdoc`
- Breaking change: Drop `jsdoctypeparserToESTree`
- Breaking enhancement: Switch to `jsdoc-type-pratt-parser` (toward greater
TypeScript expressivity and compatibility/support with catharsis)
- Enhancement: Export `jsdocTypeVisitorKeys` (from `jsdoc-type-pratt-parser`)
## 0.7.2
- Fix: Add `@description` to `noNames`
## 0.7.1
- Fix: Add `@summary` to `noNames`
## 0.7.0
- Enhancement: Allow specifying `noNames` and `noTypes` on `parseComment`
to override (or add to) tags which should have no names or types.
- Enhancement: Export `hasSeeWithLink` utility and `defaultNoTypes` and
`defaultNoNames`.
## 0.6.0
- Change `comment-parser` `tag` AST to avoid initial `@`
## 0.5.1
- Fix: Avoid setting `variation` name (just the description) (including in
dist)
- npm: Add `prepublishOnly` script
## 0.5.0
- Fix: Avoid setting `variation` name (just the description)
## 0.4.4
- Fix: Avoid setting `name` and `description` for simple `@template SomeName`
## 0.4.3
- npm: Ignores Github file
## 0.4.2
- Fix: Ensure replacement of camel-casing (used in `jsdoctypeparser` nodes and
visitor keys is global. The practical effect is that
`JSDocTypeNamed_parameter` -> `JSDocTypeNamedParameter`,
`JSDocTypeRecord_entry` -> `JSDocTypeRecordEntry`
`JSDocTypeNot_nullable` -> `JSDocTypeNotNullable`
`JSDocTypeInner_member` -> `JSDocTypeInnerMember`
`JSDocTypeInstance_member` -> `JSDocTypeInstanceMember`
`JSDocTypeString_value` -> `JSDocTypeStringValue`
`JSDocTypeNumber_value` -> `JSDocTypeNumberValue`
`JSDocTypeFile_path` -> `JSDocTypeFilePath`
`JSDocTypeType_query` -> `JSDocTypeTypeQuery`
`JSDocTypeKey_query` -> `JSDocTypeKeyQuery`
- Fix: Add missing `JSDocTypeLine` to visitor keys
- Docs: Explain AST structure/differences
## 0.4.1
- Docs: Indicate available methods with brief summary on README
## 0.4.0
- Enhancement: Expose `parseComment` and `getTokenizers`.
## 0.3.0
- Enhancement: Expose `toCamelCase` as new method rather than within a
utility file.
## 0.2.0
- Enhancement: Exposes new methods: `commentHandler`,
`commentParserToESTree`, `jsdocVisitorKeys`, `jsdoctypeparserToESTree`,
`jsdocTypeVisitorKeys`,
## 0.1.1
- Build: Add Babel to work with earlier Node
## 0.1.0
- Initial version

20
node_modules/@es-joy/jsdoccomment/LICENSE-MIT.txt generated vendored Normal file
View File

@ -0,0 +1,20 @@
Copyright JS Foundation and other contributors, https://js.foundation
Copyright (c) 2021 Brett Zamir
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.

241
node_modules/@es-joy/jsdoccomment/README.md generated vendored Normal file
View File

@ -0,0 +1,241 @@
# @es-joy/jsdoccomment
[![NPM](https://img.shields.io/npm/v/@es-joy/jsdoccomment.svg?label=npm)](https://www.npmjs.com/package/@es-joy/jsdoccomment)
[![License](https://img.shields.io/badge/license-MIT-yellowgreen.svg?style=flat)](https://github.com/es-joy/jsdoccomment/blob/main/LICENSE-MIT.txt)
[![Build Status](https://github.com/es-joy/jsdoccomment/workflows/CI/CD/badge.svg)](#)
[![API Docs](https://img.shields.io/badge/API%20Documentation-476ff0)](https://es-joy.github.io/jsdoccomment/)
This project aims to preserve and expand upon the
`SourceCode#getJSDocComment` functionality of the deprecated ESLint method.
It also exports a number of functions currently for working with JSDoc:
## API
### `parseComment`
For parsing `comment-parser` in a JSDoc-specific manner.
Might wish to have tags with or without tags, etc. derived from a split off
JSON file.
### `commentParserToESTree`
Converts [comment-parser](https://github.com/syavorsky/comment-parser)
AST to ESTree/ESLint/Babel friendly AST. See the "ESLint AST..." section below.
### `estreeToString`
Stringifies. In addition to the node argument, it accepts an optional second
options object with a single `preferRawType` key. If you don't need to modify
JSDoc type AST, you might wish to set this to `true` to get the benefits of
preserving the raw form, but for AST-based stringification of JSDoc types,
keep it `false` (the default).
### `jsdocVisitorKeys`
The [VisitorKeys](https://github.com/eslint/eslint-visitor-keys)
for `JsdocBlock`, `JsdocDescriptionLine`, and `JsdocTag`. More likely to be
subject to change or dropped in favor of another type parser.
### `jsdocTypeVisitorKeys`
Just a re-export of [VisitorKeys](https://github.com/eslint/eslint-visitor-keys)
from [`jsdoc-type-pratt-parser`](https://github.com/simonseyock/jsdoc-type-pratt-parser/).
### `getDefaultTagStructureForMode`
Provides info on JSDoc tags:
- `nameContents` ('namepath-referencing'|'namepath-defining'|
'dual-namepath-referencing'|false) - Whether and how a name is allowed
following any type. Tags without a proper name (value `false`) may still
have a description (which can appear like a name); `descriptionAllowed`
in such cases would be `true`.
The presence of a truthy `nameContents` value is therefore only intended
to signify whether separate parsing should occur for a name vs. a
description, and what its nature should be.
- `nameRequired` (boolean) - Whether a name must be present following any type.
- `descriptionAllowed` (boolean) - Whether a description (following any name)
is allowed.
- `typeAllowed` (boolean) - Whether the tag accepts a curly bracketed portion.
Even without a type, a tag may still have a name and/or description.
- `typeRequired` (boolean) - Whether a curly bracketed type must be present.
- `typeOrNameRequired` (boolean) - Whether either a curly bracketed type is
required or a name, but not necessarily both.
### Miscellaneous
Also currently exports these utilities:
- `getTokenizers` - Used with `parseComment` (its main core).
- `hasSeeWithLink` - A utility to detect if a tag is `@see` and has a `@link`.
- `commentHandler` - Used by `eslint-plugin-jsdoc`.
- `commentParserToESTree`- Converts [comment-parser](https://github.com/syavorsky/comment-parser)
AST to ESTree/ESLint/Babel friendly AST.
- `jsdocVisitorKeys` - The [VisitorKeys](https://github.com/eslint/eslint-visitor-keys)
for `JSDocBlock`, `JSDocDescriptionLine`, and `JSDocTag`.
- `jsdocTypeVisitorKeys` - [VisitorKeys](https://github.com/eslint/eslint-visitor-keys)
for `jsdoc-type-pratt-parser`.
- `defaultNoTypes` = The tags which allow no types by default:
`default`, `defaultvalue`, `description`, `example`, `file`,
`fileoverview`, `license`, `overview`, `see`, `summary`
- `defaultNoNames` - The tags which allow no names by default:
`access`, `author`, `default`, `defaultvalue`, `description`, `example`,
`exception`, `file`, `fileoverview`, `kind`, `license`, `overview`,
`return`, `returns`, `since`, `summary`, `throws`, `version`, `variation`
## ESLint AST produced for `comment-parser` nodes (`JsdocBlock`, `JsdocTag`, and `JsdocDescriptionLine`)
Note: Although not added in this package, `@es-joy/jsdoc-eslint-parser` adds
a `jsdoc` property to other ES nodes (using this project's `getJSDocComment`
to determine the specific comment-block that will be attached as AST).
### `JsdocBlock`
Has the following visitable properties:
1. `descriptionLines` (an array of `JsdocDescriptionLine` for multiline
descriptions).
2. `tags` (an array of `JsdocTag`; see below)
3. `inlineTags` (an array of `JsdocInlineTag`; see below)
Has the following custom non-visitable property:
1. `delimiterLineBreak` - A string containing any line break after `delimiter`.
2. `lastDescriptionLine` - A number
3. `endLine` - A number representing the line number with `end`/`terminal`
4. `descriptionStartLine` - A 0+ number indicating the line where any
description begins
5. `descriptionEndLine` - A 0+ number indicating the line where the description
ends
6. `hasPreterminalDescription` - Set to 0 or 1. On if has a block description
on the same line as the terminal `*/`.
7. `hasPreterminalTagDescription` - Set to 0 or 1. On if has a tag description
on the same line as the terminal `*/`.
8. `preterminalLineBreak` - A string containing any line break before `terminal`.
May also have the following non-visitable properties from `comment-parser`:
1. `description` - Same as `descriptionLines` but as a string with newlines.
2. `delimiter`
3. `postDelimiter`
4. `lineEnd`
5. `initial` (from `start`)
6. `terminal` (from `end`)
### `JsdocTag`
Has the following visitable properties:
1. `parsedType` (the `jsdoc-type-pratt-parser` AST representation of the tag's
type (see the `jsdoc-type-pratt-parser` section below)).
2. `typeLines` (an array of `JsdocTypeLine` for multiline type strings)
3. `descriptionLines` (an array of `JsdocDescriptionLine` for multiline
descriptions)
4. `inlineTags` (an array of `JsdocInlineTag`)
May also have the following non-visitable properties from `comment-parser`
(note that all are included from `comment-parser` except `end` as that is only
for JSDoc blocks and note that `type` is renamed to `rawType` and `start` to
`initial`):
1. `description` - Same as `descriptionLines` but as a string with newlines.
2. `rawType` - `comment-parser` has this named as `type`, but because of a
conflict with ESTree using `type` for Node type, we renamed it to
`rawType`. It is otherwise the same as in `comment-parser`, i.e., a string
with newlines, though with the initial `{` and final `}` stripped out.
See `typeLines` for the array version of this property.
3. `initial` - Renamed from `start` to avoid potential conflicts with
Acorn-style parser processing tools
4. `delimiter`
5. `postDelimiter`
6. `tag` (this does differ from `comment-parser` now in terms of our stripping
the initial `@`)
7. `postTag`
8. `name`
9. `postName`
10. `postType`
### `JsdocDescriptionLine`
No visitable properties.
May also have the following non-visitable properties from `comment-parser`:
1. `delimiter`
2. `postDelimiter`
3. `initial` (from `start`)
4. `description`
### `JsdocTypeLine`
No visitable properties.
May also have the following non-visitable properties from `comment-parser`:
1. `delimiter`
2. `postDelimiter`
3. `initial` (from `start`)
4. `rawType` - Renamed from `comment-parser` to avoid a conflict. See
explanation under `JsdocTag`
### `JsdocInlineTag`
No visitable properties.
Has the following non-visitable properties:
1. `format`: 'pipe' | 'plain' | 'prefix' | 'space'. These follow the styles of [link](https://jsdoc.app/tags-inline-link.html) or [tutorial](https://jsdoc.app/tags-inline-tutorial.html).
1. `pipe`: `{@link namepathOrURL|link text}`
2. `plain`: `{@link namepathOrURL}`
3. `prefix`: `[link text]{@link namepathOrURL}`
4. `space`: `{@link namepathOrURL link text (after the first space)}`
2. `namepathOrURL`: string
3. `tag`: string. The standard allows `tutorial` or `link`
4. `text`: string
## ESLint AST produced for `jsdoc-type-pratt-parser`
The AST, including `type`, remains as is from [jsdoc-type-pratt-parser](https://github.com/simonseyock/jsdoc-type-pratt-parser/).
The type will always begin with a `JsdocType` prefix added, along with a
camel-cased type name, e.g., `JsdocTypeUnion`.
The `jsdoc-type-pratt-parser` visitor keys are also preserved without change.
You can get a sense of the structure of these types using the parser's
[tester](https://jsdoc-type-pratt-parser.github.io/jsdoc-type-pratt-parser/).
## Installation
```shell
npm i @es-joy/jsdoccomment
```
## Changelog
The changelog can be found on the [CHANGES.md](https://github.com/es-joy/jsdoccomment/blob/main/CHANGES.md).
<!--## Contributing
Everyone is welcome to contribute. Please take a moment to review the [contributing guidelines](CONTRIBUTING.md).
-->
## Authors and license
[Brett Zamir](http://brett-zamir.me/) and
[contributors](https://github.com/es-joy/jsdoccomment/graphs/contributors).
MIT License, see the included [LICENSE-MIT.txt](https://github.com/es-joy/jsdoccomment/blob/main/LICENSE-MIT.txt) file.
## To-dos
1. Get complete code coverage
1. Given that `esquery` expects a `right` property to search for `>` (the
child selector), we should perhaps insist, for example, that params are
the child property for `JsdocBlock` or such. Where `:has()` is currently
needed, one could thus instead just use `>`.
1. Might add `trailing` for `JsdocBlock` to know whether it is followed by a
line break or what not; `comment-parser` does not provide, however
1. Fix and properly utilize `indent` argument (challenging for
`eslint-plugin-jsdoc` but needed for `jsdoc-eslint-parser` stringifiers
to be more faithful); should also then use the proposed `trailing` as well

91
node_modules/@es-joy/jsdoccomment/package.json generated vendored Normal file
View File

@ -0,0 +1,91 @@
{
"name": "@es-joy/jsdoccomment",
"version": "0.49.0",
"author": "Brett Zamir <brettz9@yahoo.com>",
"contributors": [],
"description": "Maintained replacement for ESLint's deprecated SourceCode#getJSDocComment along with other jsdoc utilities",
"license": "MIT",
"keywords": [
"ast",
"comment",
"estree",
"jsdoc",
"parser",
"eslint",
"sourcecode"
],
"type": "module",
"types": "./dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"import": "./src/index.js",
"require": "./dist/index.cjs.cjs"
},
"browserslist": [
"defaults, not op_mini all"
],
"typedocOptions": {
"dmtLinksService": {
"GitHub": "https://github.com/es-joy/jsdoccomment",
"NPM": "https://www.npmjs.com/package/@es-joy/jsdoccomment"
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/es-joy/jsdoccomment.git"
},
"bugs": {
"url": "https://github.com/es-joy/jsdoccomment/issues"
},
"homepage": "https://github.com/es-joy/jsdoccomment",
"engines": {
"node": ">=16"
},
"dependencies": {
"comment-parser": "1.4.1",
"esquery": "^1.6.0",
"jsdoc-type-pratt-parser": "~4.1.0"
},
"devDependencies": {
"@babel/core": "^7.25.2",
"@babel/plugin-syntax-class-properties": "^7.12.13",
"@babel/preset-env": "^7.25.3",
"@rollup/plugin-babel": "^6.0.4",
"@types/eslint": "^9.6.0",
"@types/esquery": "^1.5.4",
"@types/estraverse": "^5.1.7",
"@types/estree": "^1.0.5",
"@typescript-eslint/types": "^8.2.0",
"@typescript-eslint/visitor-keys": "^8.2.0",
"@typhonjs-build-test/esm-d-ts": "0.3.0-next.1",
"@typhonjs-typedoc/typedoc-pkg": "^0.0.5",
"@vitest/coverage-v8": "^2.0.5",
"@vitest/ui": "^2.0.5",
"eslint": "^9.9.0",
"eslint-config-ash-nazg": "36.12.0",
"espree": "^10.1.0",
"estraverse": "^5.3.0",
"rollup": "^4.21.0",
"typescript": "^5.5.4",
"typescript-eslint": "^8.2.0",
"vitest": "^2.0.5"
},
"files": [
"/dist",
"/src",
"CHANGES.md",
"LICENSE-MIT.txt"
],
"scripts": {
"build": "rollup -c && npm run types",
"docs": "typedoc-pkg --api-link es",
"eslint": "eslint .",
"lint": "npm run eslint --",
"open": "open ./coverage/index.html",
"test": "npm run lint && npm run build && npm run test-cov",
"test-ui": "vitest --ui --coverage",
"test-cov": "vitest --coverage",
"tsc": "tsc",
"types": "esm-d-ts gen ./src/index.js --output ./dist/index.d.ts"
}
}

View File

@ -0,0 +1,39 @@
import esquery from 'esquery';
import {
visitorKeys as jsdocTypePrattParserVisitorKeys
} from 'jsdoc-type-pratt-parser';
import {
commentParserToESTree, jsdocVisitorKeys
} from './commentParserToESTree.js';
/**
* @param {{[name: string]: any}} settings
* @returns {import('.').CommentHandler}
*/
const commentHandler = (settings) => {
/**
* @type {import('.').CommentHandler}
*/
return (commentSelector, jsdoc) => {
const {mode} = settings;
const selector = esquery.parse(commentSelector);
const ast = commentParserToESTree(jsdoc, mode);
const castAst = /** @type {unknown} */ (ast);
return esquery.matches(/** @type {import('estree').Node} */ (
castAst
), selector, undefined, {
visitorKeys: {
...jsdocTypePrattParserVisitorKeys,
...jsdocVisitorKeys
}
});
};
};
export {commentHandler};

View File

@ -0,0 +1,504 @@
import {parse as jsdocTypePrattParse} from 'jsdoc-type-pratt-parser';
/**
* Removes initial and ending brackets from `rawType`
* @param {JsdocTypeLine[]|JsdocTag} container
* @param {boolean} [isArr]
* @returns {void}
*/
const stripEncapsulatingBrackets = (container, isArr) => {
if (isArr) {
const firstItem = /** @type {JsdocTypeLine[]} */ (container)[0];
firstItem.rawType = firstItem.rawType.replace(
/^\{/u, ''
);
const lastItem = /** @type {JsdocTypeLine} */ (
/** @type {JsdocTypeLine[]} */ (
container
).at(-1)
);
lastItem.rawType = lastItem.rawType.replace(/\}$/u, '');
return;
}
/** @type {JsdocTag} */ (container).rawType =
/** @type {JsdocTag} */ (container).rawType.replace(
/^\{/u, ''
).replace(/\}$/u, '');
};
/**
* @typedef {{
* delimiter: string,
* postDelimiter: string,
* rawType: string,
* initial: string,
* type: "JsdocTypeLine"
* }} JsdocTypeLine
*/
/**
* @typedef {{
* delimiter: string,
* description: string,
* postDelimiter: string,
* initial: string,
* type: "JsdocDescriptionLine"
* }} JsdocDescriptionLine
*/
/**
* @typedef {{
* format: 'pipe' | 'plain' | 'prefix' | 'space',
* namepathOrURL: string,
* tag: string,
* text: string,
* }} JsdocInlineTagNoType
*/
/**
* @typedef {JsdocInlineTagNoType & {
* type: "JsdocInlineTag"
* }} JsdocInlineTag
*/
/**
* @typedef {{
* delimiter: string,
* description: string,
* descriptionLines: JsdocDescriptionLine[],
* initial: string,
* inlineTags: JsdocInlineTag[]
* name: string,
* postDelimiter: string,
* postName: string,
* postTag: string,
* postType: string,
* rawType: string,
* parsedType: import('jsdoc-type-pratt-parser').RootResult|null
* tag: string,
* type: "JsdocTag",
* typeLines: JsdocTypeLine[],
* }} JsdocTag
*/
/**
* @typedef {number} Integer
*/
/**
* @typedef {{
* delimiter: string,
* delimiterLineBreak: string,
* description: string,
* descriptionEndLine?: Integer,
* descriptionLines: JsdocDescriptionLine[],
* descriptionStartLine?: Integer,
* hasPreterminalDescription: 0|1,
* hasPreterminalTagDescription?: 1,
* initial: string,
* inlineTags: JsdocInlineTag[]
* lastDescriptionLine?: Integer,
* endLine: Integer,
* lineEnd: string,
* postDelimiter: string,
* tags: JsdocTag[],
* terminal: string,
* preterminalLineBreak: string,
* type: "JsdocBlock",
* }} JsdocBlock
*/
/**
* @param {object} cfg
* @param {string} cfg.text
* @param {string} cfg.tag
* @param {'pipe' | 'plain' | 'prefix' | 'space'} cfg.format
* @param {string} cfg.namepathOrURL
* @returns {JsdocInlineTag}
*/
const inlineTagToAST = ({text, tag, format, namepathOrURL}) => ({
text,
tag,
format,
namepathOrURL,
type: 'JsdocInlineTag'
});
/**
* Converts comment parser AST to ESTree format.
* @param {import('.').JsdocBlockWithInline} jsdoc
* @param {import('jsdoc-type-pratt-parser').ParseMode} mode
* @param {object} opts
* @param {'compact'|'preserve'} [opts.spacing] By default, empty lines are
* compacted; set to 'preserve' to preserve empty comment lines.
* @param {boolean} [opts.throwOnTypeParsingErrors]
* @returns {JsdocBlock}
*/
const commentParserToESTree = (jsdoc, mode, {
spacing = 'compact',
throwOnTypeParsingErrors = false
} = {}) => {
/**
* Strips brackets from a tag's `rawType` values and adds `parsedType`
* @param {JsdocTag} lastTag
* @returns {void}
*/
const cleanUpLastTag = (lastTag) => {
// Strip out `}` that encapsulates and is not part of
// the type
stripEncapsulatingBrackets(lastTag);
if (lastTag.typeLines.length) {
stripEncapsulatingBrackets(lastTag.typeLines, true);
}
// Remove single empty line description.
if (lastTag.descriptionLines.length === 1 &&
lastTag.descriptionLines[0].description === '') {
lastTag.descriptionLines.length = 0;
}
// With even a multiline type now in full, add parsing
let parsedType = null;
try {
parsedType = jsdocTypePrattParse(lastTag.rawType, mode);
} catch (err) {
// Ignore
if (lastTag.rawType && throwOnTypeParsingErrors) {
/** @type {Error} */ (
err
).message = `Tag @${lastTag.tag} with raw type ` +
`\`${lastTag.rawType}\` had parsing error: ${
/** @type {Error} */ (err).message}`;
throw err;
}
}
lastTag.parsedType = parsedType;
};
const {source, inlineTags: blockInlineTags} = jsdoc;
const {tokens: {
delimiter: delimiterRoot,
lineEnd: lineEndRoot,
postDelimiter: postDelimiterRoot,
start: startRoot,
end: endRoot
}} = source[0];
const endLine = source.length - 1;
/** @type {JsdocBlock} */
const ast = {
delimiter: delimiterRoot,
delimiterLineBreak: '\n',
description: '',
descriptionLines: [],
inlineTags: blockInlineTags.map((t) => inlineTagToAST(t)),
initial: startRoot,
tags: [],
// `terminal` will be overwritten if there are other entries
terminal: endRoot,
preterminalLineBreak: '\n',
hasPreterminalDescription: 0,
endLine,
postDelimiter: postDelimiterRoot,
lineEnd: lineEndRoot,
type: 'JsdocBlock'
};
/**
* @type {JsdocTag[]}
*/
const tags = [];
/** @type {Integer|undefined} */
let lastDescriptionLine;
/** @type {JsdocTag|null} */
let lastTag = null;
// Tracks when first valid tag description line is seen.
let tagDescriptionSeen = false;
let descLineStateOpen = true;
source.forEach((info, idx) => {
const {tokens} = info;
const {
delimiter,
description,
postDelimiter,
start: initial,
tag,
end,
type: rawType
} = tokens;
if (!tag && description && descLineStateOpen) {
if (ast.descriptionStartLine === undefined) {
ast.descriptionStartLine = idx;
}
ast.descriptionEndLine = idx;
}
if (tag || end) {
descLineStateOpen = false;
if (lastDescriptionLine === undefined) {
lastDescriptionLine = idx;
}
// Clean-up with last tag before end or new tag
if (lastTag) {
cleanUpLastTag(lastTag);
}
// Stop the iteration when we reach the end
// but only when there is no tag earlier in the line
// to still process
if (end && !tag) {
ast.terminal = end;
// Check if there are any description lines and if not then this is a
// one line comment block.
const isDelimiterLine = ast.descriptionLines.length === 0 &&
delimiter === '/**';
// Remove delimiter line break for one line comments blocks.
if (isDelimiterLine) {
ast.delimiterLineBreak = '';
}
if (description) {
// Remove terminal line break at end when description is defined.
if (ast.terminal === '*/') {
ast.preterminalLineBreak = '';
}
if (lastTag) {
ast.hasPreterminalTagDescription = 1;
} else {
ast.hasPreterminalDescription = 1;
}
const holder = lastTag || ast;
holder.description += (holder.description ? '\n' : '') + description;
// Do not include `delimiter` / `postDelimiter` for opening
// delimiter line.
holder.descriptionLines.push({
delimiter: isDelimiterLine ? '' : delimiter,
description,
postDelimiter: isDelimiterLine ? '' : postDelimiter,
initial,
type: 'JsdocDescriptionLine'
});
}
return;
}
const {
// eslint-disable-next-line no-unused-vars -- Discarding
end: ed,
delimiter: de,
postDelimiter: pd,
start: init,
...tkns
} = tokens;
if (!tokens.name) {
let i = 1;
while (source[idx + i]) {
const {tokens: {
name,
postName,
postType,
tag: tg
}} = source[idx + i];
if (tg) {
break;
}
if (name) {
tkns.postType = postType;
tkns.name = name;
tkns.postName = postName;
break;
}
i++;
}
}
/**
* @type {JsdocInlineTag[]}
*/
let tagInlineTags = [];
if (tag) {
// Assuming the tags from `source` are in the same order as `jsdoc.tags`
// we can use the `tags` length as index into the parser result tags.
tagInlineTags =
/**
* @type {import('comment-parser').Spec & {
* inlineTags: JsdocInlineTagNoType[]
* }}
*/ (
jsdoc.tags[tags.length]
).inlineTags.map(
(t) => inlineTagToAST(t)
);
}
/** @type {JsdocTag} */
const tagObj = {
...tkns,
initial: endLine ? init : '',
postDelimiter: lastDescriptionLine ? pd : '',
delimiter: lastDescriptionLine ? de : '',
descriptionLines: [],
inlineTags: tagInlineTags,
parsedType: null,
rawType: '',
type: 'JsdocTag',
typeLines: []
};
tagObj.tag = tagObj.tag.replace(/^@/u, '');
lastTag = tagObj;
tagDescriptionSeen = false;
tags.push(tagObj);
}
if (rawType) {
// Will strip rawType brackets after this tag
/** @type {JsdocTag} */ (lastTag).typeLines.push(
/** @type {JsdocTag} */ (lastTag).typeLines.length
? {
delimiter,
postDelimiter,
rawType,
initial,
type: 'JsdocTypeLine'
}
: {
delimiter: '',
postDelimiter: '',
rawType,
initial: '',
type: 'JsdocTypeLine'
}
);
/** @type {JsdocTag} */ (lastTag).rawType += /** @type {JsdocTag} */ (
lastTag
).rawType
? '\n' + rawType
: rawType;
}
// In `compact` mode skip processing if `description` is an empty string
// unless lastTag is being processed.
//
// In `preserve` mode process when `description` is not the `empty string
// or the `delimiter` is not `/**` ensuring empty lines are preserved.
if (((spacing === 'compact' && description) || lastTag) ||
(spacing === 'preserve' && (description || delimiter !== '/**'))) {
const holder = lastTag || ast;
// Check if there are any description lines and if not then this is a
// multi-line comment block with description on 0th line. Treat
// `delimiter` / `postDelimiter` / `initial` as being on a new line.
const isDelimiterLine = holder.descriptionLines.length === 0 &&
delimiter === '/**';
// Remove delimiter line break for one line comments blocks.
if (isDelimiterLine) {
ast.delimiterLineBreak = '';
}
// Track when the first description line is seen to avoid adding empty
// description lines for tag type lines.
tagDescriptionSeen ||= Boolean(lastTag &&
(rawType === '' || rawType?.endsWith('}')));
if (lastTag) {
if (tagDescriptionSeen) {
// The first tag description line is a continuation after type /
// name parsing.
const isFirstDescriptionLine = holder.descriptionLines.length === 0;
// For `compact` spacing must allow through first description line.
if ((spacing === 'compact' &&
(description || isFirstDescriptionLine)) ||
spacing === 'preserve') {
holder.descriptionLines.push({
delimiter: isFirstDescriptionLine ? '' : delimiter,
description,
postDelimiter: isFirstDescriptionLine ? '' : postDelimiter,
initial: isFirstDescriptionLine ? '' : initial,
type: 'JsdocDescriptionLine'
});
}
}
} else {
holder.descriptionLines.push({
delimiter: isDelimiterLine ? '' : delimiter,
description,
postDelimiter: isDelimiterLine ? '' : postDelimiter,
initial: isDelimiterLine ? `` : initial,
type: 'JsdocDescriptionLine'
});
}
if (!tag) {
if (lastTag) {
// For `compact` spacing must filter out any empty description lines
// after the initial `holder.description` has content.
if (tagDescriptionSeen && !(spacing === 'compact' &&
holder.description && description === '')) {
holder.description += !holder.description
? description
: '\n' + description;
}
} else {
holder.description += !holder.description
? description
: '\n' + description;
}
}
}
// Clean-up where last line itself has tag content
if (end && tag) {
ast.terminal = end;
ast.hasPreterminalTagDescription = 1;
// Remove terminal line break at end when tag is defined on last line.
if (ast.terminal === '*/') {
ast.preterminalLineBreak = '';
}
cleanUpLastTag(/** @type {JsdocTag} */ (lastTag));
}
});
ast.lastDescriptionLine = lastDescriptionLine;
ast.tags = tags;
return ast;
};
const jsdocVisitorKeys = {
JsdocBlock: ['descriptionLines', 'tags', 'inlineTags'],
JsdocDescriptionLine: [],
JsdocTypeLine: [],
JsdocTag: ['parsedType', 'typeLines', 'descriptionLines', 'inlineTags'],
JsdocInlineTag: []
};
export {commentParserToESTree, jsdocVisitorKeys};

179
node_modules/@es-joy/jsdoccomment/src/estreeToString.js generated vendored Normal file
View File

@ -0,0 +1,179 @@
import {stringify as prattStringify} from 'jsdoc-type-pratt-parser';
/** @type {Record<string, Function>} */
const stringifiers = {
JsdocBlock,
/**
* @param {import('./commentParserToESTree').JsdocDescriptionLine} node
* @returns {string}
*/
JsdocDescriptionLine ({
initial, delimiter, postDelimiter, description
}) {
return `${initial}${delimiter}${postDelimiter}${description}`;
},
/**
* @param {import('./commentParserToESTree').JsdocTypeLine} node
* @returns {string}
*/
JsdocTypeLine ({
initial, delimiter, postDelimiter, rawType
}) {
return `${initial}${delimiter}${postDelimiter}${rawType}`;
},
/**
* @param {import('./commentParserToESTree').JsdocInlineTag} node
*/
JsdocInlineTag ({format, namepathOrURL, tag, text}) {
return format === 'pipe'
? `{@${tag} ${namepathOrURL}|${text}}`
: format === 'plain'
? `{@${tag} ${namepathOrURL}}`
: format === 'prefix'
? `[${text}]{@${tag} ${namepathOrURL}}`
// "space"
: `{@${tag} ${namepathOrURL} ${text}}`;
},
JsdocTag
};
/**
* @todo convert for use by escodegen (until may be patched to support
* custom entries?).
* @param {import('./commentParserToESTree').JsdocBlock|
* import('./commentParserToESTree').JsdocDescriptionLine|
* import('./commentParserToESTree').JsdocTypeLine|
* import('./commentParserToESTree').JsdocTag|
* import('./commentParserToESTree').JsdocInlineTag|
* import('jsdoc-type-pratt-parser').RootResult
* } node
* @param {import('.').ESTreeToStringOptions} opts
* @throws {Error}
* @returns {string}
*/
function estreeToString (node, opts = {}) {
if (Object.prototype.hasOwnProperty.call(stringifiers, node.type)) {
return stringifiers[
/**
* @type {import('./commentParserToESTree').JsdocBlock|
* import('./commentParserToESTree').JsdocDescriptionLine|
* import('./commentParserToESTree').JsdocTypeLine|
* import('./commentParserToESTree').JsdocTag}
*/
(node).type
](
node,
opts
);
}
// We use raw type instead but it is a key as other apps may wish to traverse
if (node.type.startsWith('JsdocType')) {
return opts.preferRawType
? ''
: `{${prattStringify(
/** @type {import('jsdoc-type-pratt-parser').RootResult} */ (
node
)
)}}`;
}
throw new Error(`Unhandled node type: ${node.type}`);
}
/**
* @param {import('./commentParserToESTree').JsdocBlock} node
* @param {import('.').ESTreeToStringOptions} opts
* @returns {string}
*/
function JsdocBlock (node, opts) {
const {delimiter, delimiterLineBreak, descriptionLines,
initial, postDelimiter, preterminalLineBreak, tags, terminal} = node;
const terminalPrepend = preterminalLineBreak !== ''
? `${preterminalLineBreak}${initial} `
: '';
let result = `${initial}${delimiter}${postDelimiter}${delimiterLineBreak}`;
for (let i = 0; i < descriptionLines.length; i++) {
result += estreeToString(descriptionLines[i]);
if (i !== descriptionLines.length - 1 || tags.length) {
result += '\n';
}
}
for (let i = 0; i < tags.length; i++) {
result += estreeToString(tags[i], opts);
if (i !== tags.length - 1) {
result += '\n';
}
}
result += `${terminalPrepend}${terminal}`;
return result;
}
/**
* @param {import('./commentParserToESTree').JsdocTag} node
* @param {import('.').ESTreeToStringOptions} opts
* @returns {string}
*/
function JsdocTag (node, opts) {
const {
delimiter, descriptionLines, initial, name, parsedType, postDelimiter,
postName, postTag, postType, tag, typeLines
} = node;
let result = `${initial}${delimiter}${postDelimiter}@${tag}${postTag}`;
// Could do `rawType` but may have been changed; could also do
// `typeLines` but not as likely to be changed
// parsedType
// Comment this out later in favor of `parsedType`
// We can't use raw `typeLines` as first argument has delimiter on it
if (opts.preferRawType || !parsedType) {
if (typeLines.length) {
result += '{';
for (let i = 0; i < typeLines.length; i++) {
result += estreeToString(typeLines[i]);
if (i !== typeLines.length - 1) {
result += '\n';
}
}
result += '}';
}
} else if (parsedType?.type.startsWith('JsdocType')) {
result += `{${prattStringify(
/** @type {import('jsdoc-type-pratt-parser').RootResult} */ (
parsedType
)
)}}`;
}
result += name ? `${postType}${name}${postName}` : postType;
for (let i = 0; i < descriptionLines.length; i++) {
const descriptionLine = descriptionLines[i];
result += estreeToString(descriptionLine);
if (i !== descriptionLines.length - 1) {
result += '\n';
}
}
return result;
}
export {estreeToString};

50
node_modules/@es-joy/jsdoccomment/src/index.js generated vendored Normal file
View File

@ -0,0 +1,50 @@
/**
* @typedef {import('./commentParserToESTree').JsdocInlineTagNoType & {
* start: number,
* end: number,
* }} InlineTag
*/
/**
* @typedef {import('comment-parser').Spec & {
* line?: import('./commentParserToESTree').Integer,
* inlineTags: (import('./commentParserToESTree').JsdocInlineTagNoType & {
* line?: import('./commentParserToESTree').Integer
* })[]
* }} JsdocTagWithInline
*/
/**
* Expands on comment-parser's `Block` interface.
* @typedef {{
* description: string,
* source: import('comment-parser').Line[],
* problems: import('comment-parser').Problem[],
* tags: JsdocTagWithInline[],
* inlineTags: (import('./commentParserToESTree').JsdocInlineTagNoType & {
* line?: import('./commentParserToESTree').Integer
* })[]
* }} JsdocBlockWithInline
*/
/**
* @typedef {{preferRawType?: boolean}} ESTreeToStringOptions
*/
/**
* @callback CommentHandler
* @param {string} commentSelector
* @param {import('.').JsdocBlockWithInline} jsdoc
* @returns {boolean}
*/
export {visitorKeys as jsdocTypeVisitorKeys} from 'jsdoc-type-pratt-parser';
export * from 'jsdoc-type-pratt-parser';
export * from './commentHandler.js';
export * from './commentParserToESTree.js';
export * from './estreeToString.js';
export * from './jsdoccomment.js';
export * from './parseComment.js';
export * from './parseInlineTags.js';

487
node_modules/@es-joy/jsdoccomment/src/jsdoccomment.js generated vendored Normal file
View File

@ -0,0 +1,487 @@
/**
* Obtained originally from {@link https://github.com/eslint/eslint/blob/master/lib/util/source-code.js#L313}.
*
* @license MIT
*/
/**
* @typedef {import('eslint').AST.Token | import('estree').Comment | {
* type: import('eslint').AST.TokenType|"Line"|"Block"|"Shebang",
* range: [number, number],
* value: string
* }} Token
*/
/**
* @typedef {import('eslint').Rule.Node|
* import('@typescript-eslint/types').TSESTree.Node} ESLintOrTSNode
*/
/**
* @typedef {number} int
*/
/**
* Checks if the given token is a comment token or not.
*
* @param {Token} token - The token to check.
* @returns {boolean} `true` if the token is a comment token.
*/
const isCommentToken = (token) => {
return token.type === 'Line' || token.type === 'Block' ||
token.type === 'Shebang';
};
/**
* @param {(ESLintOrTSNode|import('estree').Comment) & {
* declaration?: any,
* decorators?: any[],
* parent?: import('eslint').Rule.Node & {
* decorators?: any[]
* }
* }} node
* @returns {import('@typescript-eslint/types').TSESTree.Decorator|undefined}
*/
const getDecorator = (node) => {
return node?.declaration?.decorators?.[0] || node?.decorators?.[0] ||
node?.parent?.decorators?.[0];
};
/**
* Check to see if it is a ES6 export declaration.
*
* @param {ESLintOrTSNode} astNode An AST node.
* @returns {boolean} whether the given node represents an export declaration.
* @private
*/
const looksLikeExport = function (astNode) {
return astNode.type === 'ExportDefaultDeclaration' ||
astNode.type === 'ExportNamedDeclaration' ||
astNode.type === 'ExportAllDeclaration' ||
astNode.type === 'ExportSpecifier';
};
/**
* @param {ESLintOrTSNode} astNode
* @returns {ESLintOrTSNode}
*/
const getTSFunctionComment = function (astNode) {
const {parent} = astNode;
/* v8 ignore next 3 */
if (!parent) {
return astNode;
}
const grandparent = parent.parent;
/* v8 ignore next 3 */
if (!grandparent) {
return astNode;
}
const greatGrandparent = grandparent.parent;
const greatGreatGrandparent = greatGrandparent && greatGrandparent.parent;
/* v8 ignore next 3 */
if (/** @type {ESLintOrTSNode} */ (parent).type !== 'TSTypeAnnotation') {
return astNode;
}
switch (/** @type {ESLintOrTSNode} */ (grandparent).type) {
// @ts-expect-error -- For `ClassProperty`.
case 'PropertyDefinition': case 'ClassProperty':
case 'TSDeclareFunction':
case 'TSMethodSignature':
case 'TSPropertySignature':
return grandparent;
case 'ArrowFunctionExpression':
/* v8 ignore next 3 */
if (!greatGrandparent) {
return astNode;
}
if (
greatGrandparent.type === 'VariableDeclarator'
// && greatGreatGrandparent.parent.type === 'VariableDeclaration'
) {
/* v8 ignore next 3 */
if (!greatGreatGrandparent || !greatGreatGrandparent.parent) {
return astNode;
}
return greatGreatGrandparent.parent;
}
/* v8 ignore next */
return astNode;
case 'FunctionExpression':
/* v8 ignore next 3 */
if (!greatGreatGrandparent) {
return astNode;
}
if (greatGrandparent.type === 'MethodDefinition') {
return greatGrandparent;
}
// Fallthrough
default:
/* v8 ignore next 3 */
if (grandparent.type !== 'Identifier') {
return astNode;
}
}
/* v8 ignore next 3 */
if (!greatGreatGrandparent) {
return astNode;
}
switch (greatGrandparent.type) {
case 'ArrowFunctionExpression':
if (
greatGreatGrandparent.type === 'VariableDeclarator' &&
greatGreatGrandparent.parent.type === 'VariableDeclaration'
) {
return greatGreatGrandparent.parent;
}
return astNode;
case 'FunctionDeclaration':
return greatGrandparent;
case 'VariableDeclarator':
if (greatGreatGrandparent.type === 'VariableDeclaration') {
return greatGreatGrandparent;
}
/* v8 ignore next 2 */
// Fallthrough
default:
/* v8 ignore next 3 */
return astNode;
}
};
const invokedExpression = new Set(
['CallExpression', 'OptionalCallExpression', 'NewExpression']
);
const allowableCommentNode = new Set([
'AssignmentPattern',
'VariableDeclaration',
'ExpressionStatement',
'MethodDefinition',
'Property',
'ObjectProperty',
'ClassProperty',
'PropertyDefinition',
'ExportDefaultDeclaration',
'ReturnStatement'
]);
/**
* Reduces the provided node to the appropriate node for evaluating
* JSDoc comment status.
*
* @param {ESLintOrTSNode} node An AST node.
* @param {import('eslint').SourceCode} sourceCode The ESLint SourceCode.
* @returns {ESLintOrTSNode} The AST node that
* can be evaluated for appropriate JSDoc comments.
*/
const getReducedASTNode = function (node, sourceCode) {
let {parent} = node;
switch (/** @type {ESLintOrTSNode} */ (node).type) {
case 'TSFunctionType':
return getTSFunctionComment(node);
case 'TSInterfaceDeclaration':
case 'TSTypeAliasDeclaration':
case 'TSEnumDeclaration':
case 'ClassDeclaration':
case 'FunctionDeclaration':
/* v8 ignore next 3 */
if (!parent) {
return node;
}
return looksLikeExport(parent) ? parent : node;
case 'TSDeclareFunction':
case 'ClassExpression':
case 'ObjectExpression':
case 'ArrowFunctionExpression':
case 'TSEmptyBodyFunctionExpression':
case 'FunctionExpression':
/* v8 ignore next 3 */
if (!parent) {
return node;
}
if (
!invokedExpression.has(parent.type)
) {
/**
* @type {ESLintOrTSNode|Token|null}
*/
let token = node;
do {
token = sourceCode.getTokenBefore(
/** @type {import('eslint').Rule.Node|import('eslint').AST.Token} */ (
token
),
{includeComments: true}
);
} while (token && token.type === 'Punctuator' && token.value === '(');
if (token && token.type === 'Block') {
return node;
}
if (sourceCode.getCommentsBefore(
/** @type {import('eslint').Rule.Node} */
(node)
).length) {
return node;
}
while (
!sourceCode.getCommentsBefore(
/** @type {import('eslint').Rule.Node} */
(parent)
).length &&
!(/Function/u).test(parent.type) &&
!allowableCommentNode.has(parent.type)
) {
({parent} = parent);
if (!parent) {
break;
}
}
if (parent && parent.type !== 'FunctionDeclaration' &&
parent.type !== 'Program'
) {
if (parent.parent && parent.parent.type === 'ExportNamedDeclaration') {
return parent.parent;
}
return parent;
}
}
return node;
default:
return node;
}
};
/**
* Checks for the presence of a JSDoc comment for the given node and returns it.
*
* @param {ESLintOrTSNode} astNode The AST node to get
* the comment for.
* @param {import('eslint').SourceCode} sourceCode
* @param {{maxLines: int, minLines: int, [name: string]: any}} settings
* @param {{nonJSDoc?: boolean}} [opts]
* @returns {Token|null} The Block comment token containing the JSDoc comment
* for the given node or null if not found.
*/
const findJSDocComment = (astNode, sourceCode, settings, opts = {}) => {
const {nonJSDoc} = opts;
const {minLines, maxLines} = settings;
/** @type {ESLintOrTSNode|import('estree').Comment} */
let currentNode = astNode;
let tokenBefore = null;
let parenthesisToken = null;
while (currentNode) {
const decorator = getDecorator(
/** @type {import('eslint').Rule.Node} */
(currentNode)
);
if (decorator) {
const dec = /** @type {unknown} */ (decorator);
currentNode = /** @type {import('eslint').Rule.Node} */ (dec);
}
tokenBefore = sourceCode.getTokenBefore(
/** @type {import('eslint').Rule.Node} */
(currentNode),
{includeComments: true}
);
if (
tokenBefore && tokenBefore.type === 'Punctuator' &&
tokenBefore.value === '('
) {
parenthesisToken = tokenBefore;
[tokenBefore] = sourceCode.getTokensBefore(
/** @type {import('eslint').Rule.Node} */
(currentNode),
{
count: 2,
includeComments: true
}
);
}
if (!tokenBefore || !isCommentToken(tokenBefore)) {
return null;
}
if (!nonJSDoc && tokenBefore.type === 'Line') {
currentNode = tokenBefore;
continue;
}
break;
}
/* v8 ignore next 3 */
if (!tokenBefore || !currentNode.loc || !tokenBefore.loc) {
return null;
}
if (
(
(nonJSDoc && (tokenBefore.type !== 'Block' ||
!(/^\*\s/u).test(tokenBefore.value))) ||
(!nonJSDoc && tokenBefore.type === 'Block' &&
(/^\*\s/u).test(tokenBefore.value))
) &&
currentNode.loc.start.line - (
/** @type {import('eslint').AST.Token} */
(parenthesisToken ?? tokenBefore)
).loc.end.line >= minLines &&
currentNode.loc.start.line - (
/** @type {import('eslint').AST.Token} */
(parenthesisToken ?? tokenBefore)
).loc.end.line <= maxLines
) {
return tokenBefore;
}
return null;
};
/**
* Retrieves the JSDoc comment for a given node.
*
* @param {import('eslint').SourceCode} sourceCode The ESLint SourceCode
* @param {import('eslint').Rule.Node} node The AST node to get
* the comment for.
* @param {{maxLines: int, minLines: int, [name: string]: any}} settings The
* settings in context
* @returns {Token|null} The Block comment
* token containing the JSDoc comment for the given node or
* null if not found.
* @public
*/
const getJSDocComment = function (sourceCode, node, settings) {
const reducedNode = getReducedASTNode(node, sourceCode);
return findJSDocComment(reducedNode, sourceCode, settings);
};
/**
* Retrieves the comment preceding a given node.
*
* @param {import('eslint').SourceCode} sourceCode The ESLint SourceCode
* @param {ESLintOrTSNode} node The AST node to get
* the comment for.
* @param {{maxLines: int, minLines: int, [name: string]: any}} settings The
* settings in context
* @returns {Token|null} The Block comment
* token containing the JSDoc comment for the given node or
* null if not found.
* @public
*/
const getNonJsdocComment = function (sourceCode, node, settings) {
const reducedNode = getReducedASTNode(node, sourceCode);
return findJSDocComment(reducedNode, sourceCode, settings, {
nonJSDoc: true
});
};
/**
* @param {ESLintOrTSNode|import('eslint').AST.Token|
* import('estree').Comment
* } nodeA The AST node or token to compare
* @param {ESLintOrTSNode|import('eslint').AST.Token|
* import('estree').Comment} nodeB The
* AST node or token to compare
*/
const compareLocEndToStart = (nodeA, nodeB) => {
/* v8 ignore next */
return (nodeA.loc?.end.line ?? 0) === (nodeB.loc?.start.line ?? 0);
};
/**
* Checks for the presence of a comment following the given node and
* returns it.
*
* This method is experimental.
*
* @param {import('eslint').SourceCode} sourceCode
* @param {ESLintOrTSNode} astNode The AST node to get
* the comment for.
* @returns {Token|null} The comment token containing the comment
* for the given node or null if not found.
*/
const getFollowingComment = function (sourceCode, astNode) {
/**
* @param {ESLintOrTSNode} node The
* AST node to get the comment for.
*/
const getTokensAfterIgnoringSemis = (node) => {
let tokenAfter = sourceCode.getTokenAfter(
/** @type {import('eslint').Rule.Node} */
(node),
{includeComments: true}
);
while (
tokenAfter && tokenAfter.type === 'Punctuator' &&
// tokenAfter.value === ')' // Don't apparently need to ignore
tokenAfter.value === ';'
) {
[tokenAfter] = sourceCode.getTokensAfter(tokenAfter, {
includeComments: true
});
}
return tokenAfter;
};
/**
* @param {ESLintOrTSNode} node The
* AST node to get the comment for.
*/
const tokenAfterIgnoringSemis = (node) => {
const tokenAfter = getTokensAfterIgnoringSemis(node);
return (
tokenAfter &&
isCommentToken(tokenAfter) &&
compareLocEndToStart(node, tokenAfter)
)
? tokenAfter
: null;
};
let tokenAfter = tokenAfterIgnoringSemis(astNode);
if (!tokenAfter) {
switch (astNode.type) {
case 'FunctionDeclaration':
tokenAfter = tokenAfterIgnoringSemis(
/** @type {ESLintOrTSNode} */
(astNode.body)
);
break;
case 'ExpressionStatement':
tokenAfter = tokenAfterIgnoringSemis(
/** @type {ESLintOrTSNode} */
(astNode.expression)
);
break;
/* v8 ignore next 3 */
default:
break;
}
}
return tokenAfter;
};
export {
getReducedASTNode, getJSDocComment, getNonJsdocComment,
getDecorator, findJSDocComment, getFollowingComment
};

186
node_modules/@es-joy/jsdoccomment/src/parseComment.js generated vendored Normal file
View File

@ -0,0 +1,186 @@
/* eslint-disable prefer-named-capture-group -- Temporary */
import {
parse as commentParser,
tokenizers
} from 'comment-parser';
import {parseInlineTags} from './parseInlineTags.js';
const {
name: nameTokenizer,
tag: tagTokenizer,
type: typeTokenizer,
description: descriptionTokenizer
} = tokenizers;
/**
* @param {import('comment-parser').Spec} spec
* @returns {boolean}
*/
export const hasSeeWithLink = (spec) => {
return spec.tag === 'see' && (/\{@link.+?\}/u).test(spec.source[0].source);
};
export const defaultNoTypes = [
'default', 'defaultvalue', 'description', 'example',
'file', 'fileoverview', 'license',
'overview', 'see', 'summary'
];
export const defaultNoNames = [
'access', 'author',
'default', 'defaultvalue',
'description',
'example', 'exception', 'file', 'fileoverview',
'kind',
'license', 'overview',
'return', 'returns',
'since', 'summary',
'throws',
'version', 'variation'
];
const optionalBrackets = /^\[(?<name>[^=]*)=[^\]]*\]/u;
const preserveTypeTokenizer = typeTokenizer('preserve');
const preserveDescriptionTokenizer = descriptionTokenizer('preserve');
const plainNameTokenizer = nameTokenizer();
/**
* Can't import `comment-parser/es6/parser/tokenizers/index.js`,
* so we redefine here.
* @typedef {(spec: import('comment-parser').Spec) =>
* import('comment-parser').Spec} CommentParserTokenizer
*/
/**
* @param {object} [cfg]
* @param {string[]} [cfg.noTypes]
* @param {string[]} [cfg.noNames]
* @returns {CommentParserTokenizer[]}
*/
const getTokenizers = ({
noTypes = defaultNoTypes,
noNames = defaultNoNames
} = {}) => {
// trim
return [
// Tag
tagTokenizer(),
/**
* Type tokenizer.
* @param {import('comment-parser').Spec} spec
* @returns {import('comment-parser').Spec}
*/
(spec) => {
if (noTypes.includes(spec.tag)) {
return spec;
}
return preserveTypeTokenizer(spec);
},
/**
* Name tokenizer.
* @param {import('comment-parser').Spec} spec
* @returns {import('comment-parser').Spec}
*/
(spec) => {
if (spec.tag === 'template') {
// const preWS = spec.postTag;
const remainder = spec.source[0].tokens.description;
let pos;
if (remainder.startsWith('[') && remainder.includes(']')) {
const endingBracketPos = remainder.lastIndexOf(']');
pos = remainder.slice(endingBracketPos).search(/(?<![\s,])\s/u);
if (pos > -1) { // Add offset to starting point if space found
pos += endingBracketPos;
}
} else {
pos = remainder.search(/(?<![\s,])\s/u);
}
const name = pos === -1 ? remainder : remainder.slice(0, pos);
const extra = remainder.slice(pos);
let postName = '', description = '', lineEnd = '';
if (pos > -1) {
[, postName, description, lineEnd] = /** @type {RegExpMatchArray} */ (
extra.match(/(\s*)([^\r]*)(\r)?/u)
);
}
spec.optional = optionalBrackets.test(name);
// name = /** @type {string} */ (
// /** @type {RegExpMatchArray} */ (
// name.match(optionalBrackets)
// )?.groups?.name
// );
spec.name = name;
const {tokens} = spec.source[0];
tokens.name = name;
tokens.postName = postName;
tokens.description = description;
tokens.lineEnd = lineEnd || '';
return spec;
}
if (noNames.includes(spec.tag) || hasSeeWithLink(spec)) {
return spec;
}
return plainNameTokenizer(spec);
},
/**
* Description tokenizer.
* @param {import('comment-parser').Spec} spec
* @returns {import('comment-parser').Spec}
*/
(spec) => {
return preserveDescriptionTokenizer(spec);
}
];
};
/**
* Accepts a comment token or complete comment string and converts it into
* `comment-parser` AST.
* @param {string | {value: string}} commentOrNode
* @param {string} [indent] Whitespace
* @returns {import('.').JsdocBlockWithInline}
*/
const parseComment = (commentOrNode, indent = '') => {
let block;
switch (typeof commentOrNode) {
case 'string':
// Preserve JSDoc block start/end indentation.
[block] = commentParser(`${indent}${commentOrNode}`, {
// @see https://github.com/yavorskiy/comment-parser/issues/21
tokenizers: getTokenizers()
});
break;
case 'object':
if (commentOrNode === null) {
throw new TypeError(`'commentOrNode' is not a string or object.`);
}
// Preserve JSDoc block start/end indentation.
[block] = commentParser(`${indent}/*${commentOrNode.value}*/`, {
// @see https://github.com/yavorskiy/comment-parser/issues/21
tokenizers: getTokenizers()
});
break;
default:
throw new TypeError(`'commentOrNode' is not a string or object.`);
}
return parseInlineTags(block);
};
export {getTokenizers, parseComment};

View File

@ -0,0 +1,108 @@
/**
* @param {RegExpMatchArray & {
* indices: {
* groups: {
* [key: string]: [number, number]
* }
* }
* groups: {[key: string]: string}
* }} match An inline tag regexp match.
* @returns {'pipe' | 'plain' | 'prefix' | 'space'}
*/
function determineFormat (match) {
const {separator, text} = match.groups;
const [, textEnd] = match.indices.groups.text;
const [tagStart] = match.indices.groups.tag;
if (!text) {
return 'plain';
} else if (separator === '|') {
return 'pipe';
} else if (textEnd < tagStart) {
return 'prefix';
}
return 'space';
}
/**
* Extracts inline tags from a description.
* @param {string} description
* @returns {import('.').InlineTag[]} Array of inline tags from the description.
*/
function parseDescription (description) {
/** @type {import('.').InlineTag[]} */
const result = [];
// This could have been expressed in a single pattern,
// but having two avoids a potentially exponential time regex.
const prefixedTextPattern = new RegExp(/(?:\[(?<text>[^\]]+)\])\{@(?<tag>[^}\s]+)\s?(?<namepathOrURL>[^}\s|]*)\}/gu, 'gud');
// The pattern used to match for text after tag uses a negative lookbehind
// on the ']' char to avoid matching the prefixed case too.
const suffixedAfterPattern = new RegExp(/(?<!\])\{@(?<tag>[^}\s]+)\s?(?<namepathOrURL>[^}\s|]*)\s*(?<separator>[\s|])?\s*(?<text>[^}]*)\}/gu, 'gud');
const matches = [
...description.matchAll(prefixedTextPattern),
...description.matchAll(suffixedAfterPattern)
];
for (const mtch of matches) {
const match = /**
* @type {RegExpMatchArray & {
* indices: {
* groups: {
* [key: string]: [number, number]
* }
* }
* groups: {[key: string]: string}
* }}
*/ (
mtch
);
const {tag, namepathOrURL, text} = match.groups;
const [start, end] = match.indices[0];
const format = determineFormat(match);
result.push({
tag,
namepathOrURL,
text,
format,
start,
end
});
}
return result;
}
/**
* Splits the `{@prefix}` from remaining `Spec.lines[].token.description`
* into the `inlineTags` tokens, and populates `spec.inlineTags`
* @param {import('comment-parser').Block} block
* @returns {import('.').JsdocBlockWithInline}
*/
export function parseInlineTags (block) {
const inlineTags =
/**
* @type {(import('./commentParserToESTree').JsdocInlineTagNoType & {
* line?: import('./commentParserToESTree').Integer
* })[]}
*/ (
parseDescription(block.description)
);
/** @type {import('.').JsdocBlockWithInline} */ (
block
).inlineTags = inlineTags;
for (const tag of block.tags) {
/**
* @type {import('.').JsdocTagWithInline}
*/ (tag).inlineTags = parseDescription(tag.description);
}
return (
/**
* @type {import('.').JsdocBlockWithInline}
*/ (block)
);
}

13
node_modules/@es-joy/jsdoccomment/src/toCamelCase.js generated vendored Normal file
View File

@ -0,0 +1,13 @@
/**
* @param {string} str
* @returns {string}
*/
const toCamelCase = (str) => {
return str.toLowerCase().replaceAll(/^[a-z]/gu, (init) => {
return init.toUpperCase();
}).replaceAll(/_(?<wordInit>[a-z])/gu, (_, n1, o, s, {wordInit}) => {
return wordInit.toUpperCase();
});
};
export {toCamelCase};

21
node_modules/@eslint-community/eslint-utils/LICENSE generated vendored Normal file
View File

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

37
node_modules/@eslint-community/eslint-utils/README.md generated vendored Normal file
View File

@ -0,0 +1,37 @@
# @eslint-community/eslint-utils
[![npm version](https://img.shields.io/npm/v/@eslint-community/eslint-utils.svg)](https://www.npmjs.com/package/@eslint-community/eslint-utils)
[![Downloads/month](https://img.shields.io/npm/dm/@eslint-community/eslint-utils.svg)](http://www.npmtrends.com/@eslint-community/eslint-utils)
[![Build Status](https://github.com/eslint-community/eslint-utils/workflows/CI/badge.svg)](https://github.com/eslint-community/eslint-utils/actions)
[![Coverage Status](https://codecov.io/gh/eslint-community/eslint-utils/branch/main/graph/badge.svg)](https://codecov.io/gh/eslint-community/eslint-utils)
## 🏁 Goal
This package provides utility functions and classes for make ESLint custom rules.
For examples:
- [`getStaticValue`](https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getstaticvalue) evaluates static value on AST.
- [`ReferenceTracker`](https://eslint-community.github.io/eslint-utils/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring.
## 📖 Usage
See [documentation](https://eslint-community.github.io/eslint-utils).
## 📰 Changelog
See [releases](https://github.com/eslint-community/eslint-utils/releases).
## ❤️ Contributing
Welcome contributing!
Please use GitHub's Issues/PRs.
### Development Tools
- `npm run test-coverage` runs tests and measures coverage.
- `npm run clean` removes the coverage result of `npm run test-coverage` command.
- `npm run coverage` shows the coverage result of the last `npm run test-coverage` command.
- `npm run lint` runs ESLint.
- `npm run watch` runs tests on each file change.

217
node_modules/@eslint-community/eslint-utils/index.d.mts generated vendored Normal file
View File

@ -0,0 +1,217 @@
import * as eslint from 'eslint';
import { Rule, AST } from 'eslint';
import * as estree from 'estree';
declare const READ: unique symbol;
declare const CALL: unique symbol;
declare const CONSTRUCT: unique symbol;
declare const ESM: unique symbol;
declare class ReferenceTracker {
constructor(globalScope: Scope$2, options?: {
mode?: "legacy" | "strict" | undefined;
globalObjectNames?: string[] | undefined;
} | undefined);
private variableStack;
private globalScope;
private mode;
private globalObjectNames;
iterateGlobalReferences<T>(traceMap: TraceMap$2<T>): IterableIterator<TrackedReferences$2<T>>;
iterateCjsReferences<T_1>(traceMap: TraceMap$2<T_1>): IterableIterator<TrackedReferences$2<T_1>>;
iterateEsmReferences<T_2>(traceMap: TraceMap$2<T_2>): IterableIterator<TrackedReferences$2<T_2>>;
iteratePropertyReferences<T_3>(node: Expression, traceMap: TraceMap$2<T_3>): IterableIterator<TrackedReferences$2<T_3>>;
private _iterateVariableReferences;
private _iteratePropertyReferences;
private _iterateLhsReferences;
private _iterateImportReferences;
}
declare namespace ReferenceTracker {
export { READ };
export { CALL };
export { CONSTRUCT };
export { ESM };
}
type Scope$2 = eslint.Scope.Scope;
type Expression = estree.Expression;
type TraceMap$2<T> = TraceMap$1<T>;
type TrackedReferences$2<T> = TrackedReferences$1<T>;
type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1;
type StaticValueProvided$1 = {
optional?: undefined;
value: unknown;
};
type StaticValueOptional$1 = {
optional?: true;
value: undefined;
};
type ReferenceTrackerOptions$1 = {
globalObjectNames?: string[];
mode?: "legacy" | "strict";
};
type TraceMap$1<T = unknown> = {
[i: string]: TraceMapObject<T>;
};
type TraceMapObject<T> = {
[i: string]: TraceMapObject<T>;
[CALL]?: T;
[CONSTRUCT]?: T;
[READ]?: T;
[ESM]?: boolean;
};
type TrackedReferences$1<T> = {
info: T;
node: Rule.Node;
path: string[];
type: typeof CALL | typeof CONSTRUCT | typeof READ;
};
type HasSideEffectOptions$1 = {
considerGetters?: boolean;
considerImplicitTypeConversion?: boolean;
};
type PunctuatorToken<Value extends string> = AST.Token & {
type: "Punctuator";
value: Value;
};
type ArrowToken$1 = PunctuatorToken<"=>">;
type CommaToken$1 = PunctuatorToken<",">;
type SemicolonToken$1 = PunctuatorToken<";">;
type ColonToken$1 = PunctuatorToken<":">;
type OpeningParenToken$1 = PunctuatorToken<"(">;
type ClosingParenToken$1 = PunctuatorToken<")">;
type OpeningBracketToken$1 = PunctuatorToken<"[">;
type ClosingBracketToken$1 = PunctuatorToken<"]">;
type OpeningBraceToken$1 = PunctuatorToken<"{">;
type ClosingBraceToken$1 = PunctuatorToken<"}">;
declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null;
type Scope$1 = eslint.Scope.Scope;
type Variable = eslint.Scope.Variable;
type Identifier = estree.Identifier;
declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null;
type SourceCode$2 = eslint.SourceCode;
type FunctionNode$1 = estree.Function;
type SourceLocation = estree.SourceLocation;
declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string;
type FunctionNode = estree.Function;
declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope;
type Scope = eslint.Scope.Scope;
type Node$4 = estree.Node;
declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined;
type MemberExpression = estree.MemberExpression;
type MethodDefinition = estree.MethodDefinition;
type Property = estree.Property;
type PropertyDefinition = estree.PropertyDefinition;
declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null;
type StaticValue$1 = StaticValue$2;
type Node$3 = estree.Node;
declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null;
type Node$2 = estree.Node;
declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean;
type Node$1 = estree.Node;
type SourceCode$1 = eslint.SourceCode;
declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1;
declare function isCommaToken(token: CommentOrToken): token is CommaToken$1;
declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1;
declare function isColonToken(token: CommentOrToken): token is ColonToken$1;
declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1;
declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1;
declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1;
declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1;
declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1;
declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1;
declare function isCommentToken(token: CommentOrToken): token is estree.Comment;
declare function isNotArrowToken(arg0: CommentOrToken): boolean;
declare function isNotCommaToken(arg0: CommentOrToken): boolean;
declare function isNotSemicolonToken(arg0: CommentOrToken): boolean;
declare function isNotColonToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean;
declare function isNotClosingParenToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean;
declare function isNotCommentToken(arg0: CommentOrToken): boolean;
type Token = eslint.AST.Token;
type Comment = estree.Comment;
type CommentOrToken = Comment | Token;
declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean;
type Node = estree.Node;
type SourceCode = eslint.SourceCode;
declare class PatternMatcher {
constructor(pattern: RegExp, options?: {
escaped?: boolean | undefined;
} | undefined);
execAll(str: string): IterableIterator<RegExpExecArray>;
test(str: string): boolean;
[Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string;
}
declare namespace _default {
export { CALL };
export { CONSTRUCT };
export { ESM };
export { findVariable };
export { getFunctionHeadLocation };
export { getFunctionNameWithKind };
export { getInnermostScope };
export { getPropertyName };
export { getStaticValue };
export { getStringIfConstant };
export { hasSideEffect };
export { isArrowToken };
export { isClosingBraceToken };
export { isClosingBracketToken };
export { isClosingParenToken };
export { isColonToken };
export { isCommaToken };
export { isCommentToken };
export { isNotArrowToken };
export { isNotClosingBraceToken };
export { isNotClosingBracketToken };
export { isNotClosingParenToken };
export { isNotColonToken };
export { isNotCommaToken };
export { isNotCommentToken };
export { isNotOpeningBraceToken };
export { isNotOpeningBracketToken };
export { isNotOpeningParenToken };
export { isNotSemicolonToken };
export { isOpeningBraceToken };
export { isOpeningBracketToken };
export { isOpeningParenToken };
export { isParenthesized };
export { isSemicolonToken };
export { PatternMatcher };
export { READ };
export { ReferenceTracker };
}
type StaticValue = StaticValue$2;
type StaticValueOptional = StaticValueOptional$1;
type StaticValueProvided = StaticValueProvided$1;
type ReferenceTrackerOptions = ReferenceTrackerOptions$1;
type TraceMap<T> = TraceMap$1<T>;
type TrackedReferences<T> = TrackedReferences$1<T>;
type HasSideEffectOptions = HasSideEffectOptions$1;
type ArrowToken = ArrowToken$1;
type CommaToken = CommaToken$1;
type SemicolonToken = SemicolonToken$1;
type ColonToken = ColonToken$1;
type OpeningParenToken = OpeningParenToken$1;
type ClosingParenToken = ClosingParenToken$1;
type OpeningBracketToken = OpeningBracketToken$1;
type ClosingBracketToken = ClosingBracketToken$1;
type OpeningBraceToken = OpeningBraceToken$1;
type ClosingBraceToken = ClosingBraceToken$1;
export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };

217
node_modules/@eslint-community/eslint-utils/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,217 @@
import * as eslint from 'eslint';
import { Rule, AST } from 'eslint';
import * as estree from 'estree';
declare const READ: unique symbol;
declare const CALL: unique symbol;
declare const CONSTRUCT: unique symbol;
declare const ESM: unique symbol;
declare class ReferenceTracker {
constructor(globalScope: Scope$2, options?: {
mode?: "legacy" | "strict" | undefined;
globalObjectNames?: string[] | undefined;
} | undefined);
private variableStack;
private globalScope;
private mode;
private globalObjectNames;
iterateGlobalReferences<T>(traceMap: TraceMap$2<T>): IterableIterator<TrackedReferences$2<T>>;
iterateCjsReferences<T_1>(traceMap: TraceMap$2<T_1>): IterableIterator<TrackedReferences$2<T_1>>;
iterateEsmReferences<T_2>(traceMap: TraceMap$2<T_2>): IterableIterator<TrackedReferences$2<T_2>>;
iteratePropertyReferences<T_3>(node: Expression, traceMap: TraceMap$2<T_3>): IterableIterator<TrackedReferences$2<T_3>>;
private _iterateVariableReferences;
private _iteratePropertyReferences;
private _iterateLhsReferences;
private _iterateImportReferences;
}
declare namespace ReferenceTracker {
export { READ };
export { CALL };
export { CONSTRUCT };
export { ESM };
}
type Scope$2 = eslint.Scope.Scope;
type Expression = estree.Expression;
type TraceMap$2<T> = TraceMap$1<T>;
type TrackedReferences$2<T> = TrackedReferences$1<T>;
type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1;
type StaticValueProvided$1 = {
optional?: undefined;
value: unknown;
};
type StaticValueOptional$1 = {
optional?: true;
value: undefined;
};
type ReferenceTrackerOptions$1 = {
globalObjectNames?: string[];
mode?: "legacy" | "strict";
};
type TraceMap$1<T = unknown> = {
[i: string]: TraceMapObject<T>;
};
type TraceMapObject<T> = {
[i: string]: TraceMapObject<T>;
[CALL]?: T;
[CONSTRUCT]?: T;
[READ]?: T;
[ESM]?: boolean;
};
type TrackedReferences$1<T> = {
info: T;
node: Rule.Node;
path: string[];
type: typeof CALL | typeof CONSTRUCT | typeof READ;
};
type HasSideEffectOptions$1 = {
considerGetters?: boolean;
considerImplicitTypeConversion?: boolean;
};
type PunctuatorToken<Value extends string> = AST.Token & {
type: "Punctuator";
value: Value;
};
type ArrowToken$1 = PunctuatorToken<"=>">;
type CommaToken$1 = PunctuatorToken<",">;
type SemicolonToken$1 = PunctuatorToken<";">;
type ColonToken$1 = PunctuatorToken<":">;
type OpeningParenToken$1 = PunctuatorToken<"(">;
type ClosingParenToken$1 = PunctuatorToken<")">;
type OpeningBracketToken$1 = PunctuatorToken<"[">;
type ClosingBracketToken$1 = PunctuatorToken<"]">;
type OpeningBraceToken$1 = PunctuatorToken<"{">;
type ClosingBraceToken$1 = PunctuatorToken<"}">;
declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null;
type Scope$1 = eslint.Scope.Scope;
type Variable = eslint.Scope.Variable;
type Identifier = estree.Identifier;
declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null;
type SourceCode$2 = eslint.SourceCode;
type FunctionNode$1 = estree.Function;
type SourceLocation = estree.SourceLocation;
declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string;
type FunctionNode = estree.Function;
declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope;
type Scope = eslint.Scope.Scope;
type Node$4 = estree.Node;
declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined;
type MemberExpression = estree.MemberExpression;
type MethodDefinition = estree.MethodDefinition;
type Property = estree.Property;
type PropertyDefinition = estree.PropertyDefinition;
declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null;
type StaticValue$1 = StaticValue$2;
type Node$3 = estree.Node;
declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null;
type Node$2 = estree.Node;
declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean;
type Node$1 = estree.Node;
type SourceCode$1 = eslint.SourceCode;
declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1;
declare function isCommaToken(token: CommentOrToken): token is CommaToken$1;
declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1;
declare function isColonToken(token: CommentOrToken): token is ColonToken$1;
declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1;
declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1;
declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1;
declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1;
declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1;
declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1;
declare function isCommentToken(token: CommentOrToken): token is estree.Comment;
declare function isNotArrowToken(arg0: CommentOrToken): boolean;
declare function isNotCommaToken(arg0: CommentOrToken): boolean;
declare function isNotSemicolonToken(arg0: CommentOrToken): boolean;
declare function isNotColonToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean;
declare function isNotClosingParenToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean;
declare function isNotCommentToken(arg0: CommentOrToken): boolean;
type Token = eslint.AST.Token;
type Comment = estree.Comment;
type CommentOrToken = Comment | Token;
declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean;
type Node = estree.Node;
type SourceCode = eslint.SourceCode;
declare class PatternMatcher {
constructor(pattern: RegExp, options?: {
escaped?: boolean | undefined;
} | undefined);
execAll(str: string): IterableIterator<RegExpExecArray>;
test(str: string): boolean;
[Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string;
}
declare namespace _default {
export { CALL };
export { CONSTRUCT };
export { ESM };
export { findVariable };
export { getFunctionHeadLocation };
export { getFunctionNameWithKind };
export { getInnermostScope };
export { getPropertyName };
export { getStaticValue };
export { getStringIfConstant };
export { hasSideEffect };
export { isArrowToken };
export { isClosingBraceToken };
export { isClosingBracketToken };
export { isClosingParenToken };
export { isColonToken };
export { isCommaToken };
export { isCommentToken };
export { isNotArrowToken };
export { isNotClosingBraceToken };
export { isNotClosingBracketToken };
export { isNotClosingParenToken };
export { isNotColonToken };
export { isNotCommaToken };
export { isNotCommentToken };
export { isNotOpeningBraceToken };
export { isNotOpeningBracketToken };
export { isNotOpeningParenToken };
export { isNotSemicolonToken };
export { isOpeningBraceToken };
export { isOpeningBracketToken };
export { isOpeningParenToken };
export { isParenthesized };
export { isSemicolonToken };
export { PatternMatcher };
export { READ };
export { ReferenceTracker };
}
type StaticValue = StaticValue$2;
type StaticValueOptional = StaticValueOptional$1;
type StaticValueProvided = StaticValueProvided$1;
type ReferenceTrackerOptions = ReferenceTrackerOptions$1;
type TraceMap<T> = TraceMap$1<T>;
type TrackedReferences<T> = TrackedReferences$1<T>;
type HasSideEffectOptions = HasSideEffectOptions$1;
type ArrowToken = ArrowToken$1;
type CommaToken = CommaToken$1;
type SemicolonToken = SemicolonToken$1;
type ColonToken = ColonToken$1;
type OpeningParenToken = OpeningParenToken$1;
type ClosingParenToken = ClosingParenToken$1;
type OpeningBracketToken = OpeningBracketToken$1;
type ClosingBracketToken = ClosingBracketToken$1;
type OpeningBraceToken = OpeningBraceToken$1;
type ClosingBraceToken = ClosingBraceToken$1;
export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };

2494
node_modules/@eslint-community/eslint-utils/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

2453
node_modules/@eslint-community/eslint-utils/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

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,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,89 @@
{
"name": "@eslint-community/eslint-utils",
"version": "4.7.0",
"description": "Utilities for ESLint plugins.",
"keywords": [
"eslint"
],
"homepage": "https://github.com/eslint-community/eslint-utils#readme",
"bugs": {
"url": "https://github.com/eslint-community/eslint-utils/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/eslint-community/eslint-utils"
},
"license": "MIT",
"author": "Toru Nagashima",
"sideEffects": false,
"exports": {
".": {
"import": "./index.mjs",
"require": "./index.js"
},
"./package.json": "./package.json"
},
"main": "index",
"module": "index.mjs",
"files": [
"index.*"
],
"scripts": {
"prebuild": "npm run -s clean",
"build": "npm run build:dts && npm run build:rollup",
"build:dts": "tsc -p tsconfig.build.json",
"build:rollup": "rollup -c",
"clean": "rimraf .nyc_output coverage index.* dist",
"coverage": "opener ./coverage/lcov-report/index.html",
"docs:build": "vitepress build docs",
"docs:watch": "vitepress dev docs",
"format": "npm run -s format:prettier -- --write",
"format:prettier": "prettier .",
"format:check": "npm run -s format:prettier -- --check",
"lint:eslint": "eslint .",
"lint:format": "npm run -s format:check",
"lint:installed-check": "installed-check -v -i installed-check -i npm-run-all2 -i knip -i rollup-plugin-dts",
"lint:knip": "knip",
"lint": "run-p lint:*",
"test-coverage": "c8 mocha --reporter dot \"test/*.mjs\"",
"test": "mocha --reporter dot \"test/*.mjs\"",
"preversion": "npm run test-coverage && npm run -s build",
"postversion": "git push && git push --tags",
"prewatch": "npm run -s clean",
"watch": "warun \"{src,test}/**/*.mjs\" -- npm run -s test:mocha"
},
"dependencies": {
"eslint-visitor-keys": "^3.4.3"
},
"devDependencies": {
"@eslint-community/eslint-plugin-mysticatea": "^15.6.1",
"@types/eslint": "^9.6.1",
"@types/estree": "^1.0.7",
"@typescript-eslint/parser": "^5.62.0",
"@typescript-eslint/types": "^5.62.0",
"c8": "^8.0.1",
"dot-prop": "^7.2.0",
"eslint": "^8.57.1",
"installed-check": "^8.0.1",
"knip": "^5.33.3",
"mocha": "^9.2.2",
"npm-run-all2": "^6.2.3",
"opener": "^1.5.2",
"prettier": "2.8.8",
"rimraf": "^3.0.2",
"rollup": "^2.79.2",
"rollup-plugin-dts": "^4.2.3",
"rollup-plugin-sourcemaps": "^0.6.3",
"semver": "^7.6.3",
"typescript": "^4.9.5",
"vitepress": "^1.4.1",
"warun": "^1.0.0"
},
"peerDependencies": {
"eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": "https://opencollective.com/eslint"
}

21
node_modules/@eslint-community/regexpp/LICENSE generated vendored Normal file
View File

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

177
node_modules/@eslint-community/regexpp/README.md generated vendored Normal file
View File

@ -0,0 +1,177 @@
# @eslint-community/regexpp
[![npm version](https://img.shields.io/npm/v/@eslint-community/regexpp.svg)](https://www.npmjs.com/package/@eslint-community/regexpp)
[![Downloads/month](https://img.shields.io/npm/dm/@eslint-community/regexpp.svg)](http://www.npmtrends.com/@eslint-community/regexpp)
[![Build Status](https://github.com/eslint-community/regexpp/workflows/CI/badge.svg)](https://github.com/eslint-community/regexpp/actions)
[![codecov](https://codecov.io/gh/eslint-community/regexpp/branch/main/graph/badge.svg)](https://codecov.io/gh/eslint-community/regexpp)
A regular expression parser for ECMAScript.
## 💿 Installation
```bash
$ npm install @eslint-community/regexpp
```
- require Node@^12.0.0 || ^14.0.0 || >=16.0.0.
## 📖 Usage
```ts
import {
AST,
RegExpParser,
RegExpValidator,
RegExpVisitor,
parseRegExpLiteral,
validateRegExpLiteral,
visitRegExpAST
} from "@eslint-community/regexpp"
```
### parseRegExpLiteral(source, options?)
Parse a given regular expression literal then make AST object.
This is equivalent to `new RegExpParser(options).parseLiteral(source)`.
- **Parameters:**
- `source` (`string | RegExp`) The source code to parse.
- `options?` ([`RegExpParser.Options`]) The options to parse.
- **Return:**
- The AST of the regular expression.
### validateRegExpLiteral(source, options?)
Validate a given regular expression literal.
This is equivalent to `new RegExpValidator(options).validateLiteral(source)`.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `options?` ([`RegExpValidator.Options`]) The options to validate.
### visitRegExpAST(ast, handlers)
Visit each node of a given AST.
This is equivalent to `new RegExpVisitor(handlers).visit(ast)`.
- **Parameters:**
- `ast` ([`AST.Node`]) The AST to visit.
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
### RegExpParser
#### new RegExpParser(options?)
- **Parameters:**
- `options?` ([`RegExpParser.Options`]) The options to parse.
#### parser.parseLiteral(source, start?, end?)
Parse a regular expression literal.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"/abc/g"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- **Return:**
- The AST of the regular expression.
#### parser.parsePattern(source, start?, end?, flags?)
Parse a regular expression pattern.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"abc"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
- **Return:**
- The AST of the regular expression pattern.
#### parser.parseFlags(source, start?, end?)
Parse a regular expression flags.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"gim"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- **Return:**
- The AST of the regular expression flags.
### RegExpValidator
#### new RegExpValidator(options)
- **Parameters:**
- `options` ([`RegExpValidator.Options`]) The options to validate.
#### validator.validateLiteral(source, start, end)
Validate a regular expression literal.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
#### validator.validatePattern(source, start, end, flags)
Validate a regular expression pattern.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
#### validator.validateFlags(source, start, end)
Validate a regular expression flags.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
### RegExpVisitor
#### new RegExpVisitor(handlers)
- **Parameters:**
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
#### visitor.visit(ast)
Validate a regular expression literal.
- **Parameters:**
- `ast` ([`AST.Node`]) The AST to visit.
## 📰 Changelog
- [GitHub Releases](https://github.com/eslint-community/regexpp/releases)
## 🍻 Contributing
Welcome contributing!
Please use GitHub's Issues/PRs.
### 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 clean` removes the temporary files which are created by `npm test` and `npm run build`.
- `npm run lint` runs ESLint.
- `npm run update:test` updates test fixtures.
- `npm run update:ids` updates `src/unicode/ids.ts`.
- `npm run watch` runs tests with `--watch` option.
[`AST.Node`]: src/ast.ts#L4
[`RegExpParser.Options`]: src/parser.ts#L743
[`RegExpValidator.Options`]: src/validator.ts#L220
[`RegExpVisitor.Handlers`]: src/visitor.ts#L291

1163
node_modules/@eslint-community/regexpp/index.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

3037
node_modules/@eslint-community/regexpp/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/@eslint-community/regexpp/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

3027
node_modules/@eslint-community/regexpp/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/@eslint-community/regexpp/index.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

91
node_modules/@eslint-community/regexpp/package.json generated vendored Normal file
View File

@ -0,0 +1,91 @@
{
"name": "@eslint-community/regexpp",
"version": "4.12.1",
"description": "Regular expression parser for ECMAScript.",
"keywords": [
"regexp",
"regular",
"expression",
"parser",
"validator",
"ast",
"abstract",
"syntax",
"tree",
"ecmascript",
"es2015",
"es2016",
"es2017",
"es2018",
"es2019",
"es2020",
"es2021",
"annexB"
],
"homepage": "https://github.com/eslint-community/regexpp#readme",
"bugs": {
"url": "https://github.com/eslint-community/regexpp/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/eslint-community/regexpp"
},
"license": "MIT",
"author": "Toru Nagashima",
"exports": {
".": {
"types": "./index.d.ts",
"import": "./index.mjs",
"default": "./index.js"
},
"./package.json": "./package.json"
},
"main": "index",
"files": [
"index.*"
],
"scripts": {
"prebuild": "npm run -s clean",
"build": "run-s build:*",
"build:tsc": "tsc --module es2015",
"build:rollup": "rollup -c",
"build:dts": "npm run -s build:tsc -- --removeComments false && dts-bundle --name @eslint-community/regexpp --main .temp/index.d.ts --out ../index.d.ts && prettier --write index.d.ts",
"clean": "rimraf .temp index.*",
"lint": "eslint . --ext .ts",
"test": "nyc _mocha \"test/*.ts\" --reporter dot --timeout 10000",
"debug": "mocha --require ts-node/register/transpile-only \"test/*.ts\" --reporter dot --timeout 10000",
"update:test": "ts-node scripts/update-fixtures.ts",
"update:unicode": "run-s update:unicode:*",
"update:unicode:ids": "ts-node scripts/update-unicode-ids.ts",
"update:unicode:props": "ts-node scripts/update-unicode-properties.ts",
"update:test262:extract": "ts-node -T scripts/extract-test262.ts",
"preversion": "npm test && npm run -s build",
"postversion": "git push && git push --tags",
"prewatch": "npm run -s clean",
"watch": "_mocha \"test/*.ts\" --require ts-node/register --reporter dot --timeout 10000 --watch-extensions ts --watch --growl"
},
"dependencies": {},
"devDependencies": {
"@eslint-community/eslint-plugin-mysticatea": "^15.5.1",
"@rollup/plugin-node-resolve": "^14.1.0",
"@types/eslint": "^8.44.3",
"@types/jsdom": "^16.2.15",
"@types/mocha": "^9.1.1",
"@types/node": "^12.20.55",
"dts-bundle": "^0.7.3",
"eslint": "^8.50.0",
"js-tokens": "^8.0.2",
"jsdom": "^19.0.0",
"mocha": "^9.2.2",
"npm-run-all2": "^6.2.2",
"nyc": "^14.1.1",
"rimraf": "^3.0.2",
"rollup": "^2.79.1",
"rollup-plugin-sourcemaps": "^0.6.3",
"ts-node": "^10.9.1",
"typescript": "~5.0.2"
},
"engines": {
"node": "^12.0.0 || ^14.0.0 || >=16.0.0"
}
}

201
node_modules/@eslint/config-array/LICENSE generated vendored Normal file
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 [yyyy] [name of copyright owner]
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.

358
node_modules/@eslint/config-array/README.md generated vendored Normal file
View File

@ -0,0 +1,358 @@
# Config Array
## Description
A config array is a way of managing configurations that are based on glob pattern matching of filenames. Each config array contains the information needed to determine the correct configuration for any file based on the filename.
**Note:** This is a generic package that can be used outside of ESLint. It contains no ESLint-specific functionality.
## Installation
For Node.js and compatible runtimes:
```shell
npm install @eslint/config-array
# or
yarn add @eslint/config-array
# or
pnpm install @eslint/config-array
# or
bun install @eslint/config-array
```
For Deno:
```shell
deno add @eslint/config-array
```
## Background
The basic idea is that all configuration, including overrides, can be represented by a single array where each item in the array is a config object. Config objects appearing later in the array override config objects appearing earlier in the array. You can calculate a config for a given file by traversing all config objects in the array to find the ones that match the filename. Matching is done by specifying glob patterns in `files` and `ignores` properties on each config object. Here's an example:
```js
export default [
// match all JSON files
{
name: "JSON Handler",
files: ["**/*.json"],
handler: jsonHandler,
},
// match only package.json
{
name: "package.json Handler",
files: ["package.json"],
handler: packageJsonHandler,
},
];
```
In this example, there are two config objects: the first matches all JSON files in all directories and the second matches just `package.json` in the base path directory (all the globs are evaluated as relative to a base path that can be specified). When you retrieve a configuration for `foo.json`, only the first config object matches so `handler` is equal to `jsonHandler`; when you retrieve a configuration for `package.json`, `handler` is equal to `packageJsonHandler` (because both config objects match, the second one wins).
## Usage
First, import the `ConfigArray` constructor:
```js
import { ConfigArray } from "@eslint/config-array";
// or using CommonJS
const { ConfigArray } = require("@eslint/config-array");
```
When you create a new instance of `ConfigArray`, you must pass in two arguments: an array of configs and an options object. The array of configs is most likely read in from a configuration file, so here's a typical example:
```js
const configFilename = path.resolve(process.cwd(), "my.config.js");
const { default: rawConfigs } = await import(configFilename);
const configs = new ConfigArray(rawConfigs, {
// the path to match filenames from
basePath: process.cwd(),
// additional items in each config
schema: mySchema,
});
```
This example reads in an object or array from `my.config.js` and passes it into the `ConfigArray` constructor as the first argument. The second argument is an object specifying the `basePath` (the directory in which `my.config.js` is found) and a `schema` to define the additional properties of a config object beyond `files`, `ignores`, and `name`.
### Specifying a Schema
The `schema` option is required for you to use additional properties in config objects. The schema is an object that follows the format of an [`ObjectSchema`](https://npmjs.com/package/@eslint/object-schema). The schema specifies both validation and merge rules that the `ConfigArray` instance needs to combine configs when there are multiple matches. Here's an example:
```js
const configFilename = path.resolve(process.cwd(), "my.config.js");
const { default: rawConfigs } = await import(configFilename);
const mySchema = {
// define the handler key in configs
handler: {
required: true,
merge(a, b) {
if (!b) return a;
if (!a) return b;
},
validate(value) {
if (typeof value !== "function") {
throw new TypeError("Function expected.");
}
}
}
};
const configs = new ConfigArray(rawConfigs, {
// the path to match filenames from
basePath: process.cwd(),
// additional item schemas in each config
schema: mySchema,
// additional config types supported (default: [])
extraConfigTypes: ["array", "function"];
});
```
### Config Arrays
Config arrays can be multidimensional, so it's possible for a config array to contain another config array when `extraConfigTypes` contains `"array"`, such as:
```js
export default [
// JS config
{
files: ["**/*.js"],
handler: jsHandler,
},
// JSON configs
[
// match all JSON files
{
name: "JSON Handler",
files: ["**/*.json"],
handler: jsonHandler,
},
// match only package.json
{
name: "package.json Handler",
files: ["package.json"],
handler: packageJsonHandler,
},
],
// filename must match function
{
files: [filePath => filePath.endsWith(".md")],
handler: markdownHandler,
},
// filename must match all patterns in subarray
{
files: [["*.test.*", "*.js"]],
handler: jsTestHandler,
},
// filename must not match patterns beginning with !
{
name: "Non-JS files",
files: ["!*.js"],
settings: {
js: false,
},
},
];
```
In this example, the array contains both config objects and a config array. When a config array is normalized (see details below), it is flattened so only config objects remain. However, the order of evaluation remains the same.
If the `files` array contains a function, then that function is called with the path of the file as it was passed in. The function is expected to return `true` if there is a match and `false` if not. (The `ignores` array can also contain functions.)
If the `files` array contains an item that is an array of strings and functions, then all patterns must match in order for the config to match. In the preceding examples, both `*.test.*` and `*.js` must match in order for the config object to be used.
If a pattern in the files array begins with `!` then it excludes that pattern. In the preceding example, any filename that doesn't end with `.js` will automatically get a `settings.js` property set to `false`.
You can also specify an `ignores` key that will force files matching those patterns to not be included. If the `ignores` key is in a config object without any other keys, then those ignores will always be applied; otherwise those ignores act as exclusions. Here's an example:
```js
export default [
// Always ignored
{
ignores: ["**/.git/**", "**/node_modules/**"]
},
// .eslintrc.js file is ignored only when .js file matches
{
files: ["**/*.js"],
ignores: [".eslintrc.js"]
handler: jsHandler
}
];
```
You can use negated patterns in `ignores` to exclude a file that was already ignored, such as:
```js
export default [
// Ignore all JSON files except tsconfig.json
{
files: ["**/*"],
ignores: ["**/*.json", "!tsconfig.json"],
},
];
```
### Config Functions
Config arrays can also include config functions when `extraConfigTypes` contains `"function"`. A config function accepts a single parameter, `context` (defined by you), and must return either a config object or a config array (it cannot return another function). Config functions allow end users to execute code in the creation of appropriate config objects. Here's an example:
```js
export default [
// JS config
{
files: ["**/*.js"],
handler: jsHandler,
},
// JSON configs
function (context) {
return [
// match all JSON files
{
name: context.name + " JSON Handler",
files: ["**/*.json"],
handler: jsonHandler,
},
// match only package.json
{
name: context.name + " package.json Handler",
files: ["package.json"],
handler: packageJsonHandler,
},
];
},
];
```
When a config array is normalized, each function is executed and replaced in the config array with the return value.
**Note:** Config functions can also be async.
### Normalizing Config Arrays
Once a config array has been created and loaded with all of the raw config data, it must be normalized before it can be used. The normalization process goes through and flattens the config array as well as executing all config functions to get their final values.
To normalize a config array, call the `normalize()` method and pass in a context object:
```js
await configs.normalize({
name: "MyApp",
});
```
The `normalize()` method returns a promise, so be sure to use the `await` operator. The config array instance is normalized in-place, so you don't need to create a new variable.
If you want to disallow async config functions, you can call `normalizeSync()` instead. This method is completely synchronous and does not require using the `await` operator as it does not return a promise:
```js
await configs.normalizeSync({
name: "MyApp",
});
```
**Important:** Once a `ConfigArray` is normalized, it cannot be changed further. You can, however, create a new `ConfigArray` and pass in the normalized instance to create an unnormalized copy.
### Getting Config for a File
To get the config for a file, use the `getConfig()` method on a normalized config array and pass in the filename to get a config for:
```js
// pass in filename
const fileConfig = configs.getConfig(
path.resolve(process.cwd(), "package.json"),
);
```
The config array always returns an object, even if there are no configs matching the given filename. You can then inspect the returned config object to determine how to proceed.
A few things to keep in mind:
- If a filename is not an absolute path, it will be resolved relative to the base path directory.
- The returned config object never has `files`, `ignores`, or `name` properties; the only properties on the object will be the other configuration options specified.
- The config array caches configs, so subsequent calls to `getConfig()` with the same filename will return in a fast lookup rather than another calculation.
- A config will only be generated if the filename matches an entry in a `files` key. A config will not be generated without matching a `files` key (configs without a `files` key are only applied when another config with a `files` key is applied; configs without `files` are never applied on their own). Any config with a `files` key entry that is `*` or ends with `/**` or `/*` will only be applied if another entry in the same `files` key matches or another config matches.
## Determining Ignored Paths
You can determine if a file is ignored by using the `isFileIgnored()` method and passing in the path of any file, as in this example:
```js
const ignored = configs.isFileIgnored("/foo/bar/baz.txt");
```
A file is considered ignored if any of the following is true:
- **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/a.js` is considered ignored.
- **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/baz/a.js` is considered ignored.
- **It matches an ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
- **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
- **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored.
For directories, use the `isDirectoryIgnored()` method and pass in the path of any directory, as in this example:
```js
const ignored = configs.isDirectoryIgnored("/foo/bar/");
```
A directory is considered ignored if any of the following is true:
- **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/baz` is considered ignored.
- **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/bar/baz/a.js` is considered ignored.
- **It matches and ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
- **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
- **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored.
**Important:** A pattern such as `foo/**` means that `foo` and `foo/` are _not_ ignored whereas `foo/bar` is ignored. If you want to ignore `foo` and all of its subdirectories, use the pattern `foo` or `foo/` in `ignores`.
## Caching Mechanisms
Each `ConfigArray` aggressively caches configuration objects to avoid unnecessary work. This caching occurs in two ways:
1. **File-based Caching.** For each filename that is passed into a method, the resulting config is cached against that filename so you're always guaranteed to get the same object returned from `getConfig()` whenever you pass the same filename in.
2. **Index-based Caching.** Whenever a config is calculated, the config elements that were used to create the config are also cached. So if a given filename matches elements 1, 5, and 7, the resulting config is cached with a key of `1,5,7`. That way, if another file is passed that matches the same config elements, the result is already known and doesn't have to be recalculated. That means two files that match all the same elements will return the same config from `getConfig()`.
## Acknowledgements
The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from:
- Teddy Katz (@not-an-aardvark)
- Toru Nagashima (@mysticatea)
- Kai Cataldo (@kaicataldo)
## License
Apache 2.0
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a> <a href="https://trunk.io/"><img src="https://images.opencollective.com/trunkio/fb92d60/avatar.png" alt="trunk.io" height="96"></a> <a href="https://shopify.engineering/"><img src="https://avatars.githubusercontent.com/u/8085" alt="Shopify" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/e6d15e1/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://nolebase.ayaka.io"><img src="https://avatars.githubusercontent.com/u/11081491" alt="Neko" height="32"></a> <a href="https://nx.dev"><img src="https://avatars.githubusercontent.com/u/23692104" alt="Nx" height="32"></a> <a href="https://opensource.mercedes-benz.com/"><img src="https://avatars.githubusercontent.com/u/34240465" alt="Mercedes-Benz Group" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="LambdaTest" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->

66
node_modules/@eslint/config-array/package.json generated vendored Normal file
View File

@ -0,0 +1,66 @@
{
"name": "@eslint/config-array",
"version": "0.20.0",
"description": "General purpose glob-based configuration matching.",
"author": "Nicholas C. Zakas",
"type": "module",
"main": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
"exports": {
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
},
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
}
},
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/eslint/rewrite.git"
},
"bugs": {
"url": "https://github.com/eslint/rewrite/issues"
},
"homepage": "https://github.com/eslint/rewrite#readme",
"scripts": {
"build:dedupe-types": "node ../../tools/dedupe-types.js dist/cjs/index.cjs dist/esm/index.js",
"build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts",
"build:std__path": "rollup -c rollup.std__path-config.js && node fix-std__path-imports",
"build": "rollup -c && npm run build:dedupe-types && tsc -p tsconfig.esm.json && npm run build:cts && npm run build:std__path",
"test:jsr": "npx jsr@latest publish --dry-run",
"pretest": "npm run build",
"test": "mocha tests/",
"test:coverage": "c8 npm test"
},
"keywords": [
"configuration",
"configarray",
"config file"
],
"license": "Apache-2.0",
"dependencies": {
"@eslint/object-schema": "^2.1.6",
"debug": "^4.3.1",
"minimatch": "^3.1.2"
},
"devDependencies": {
"@jsr/std__path": "^1.0.4",
"@types/minimatch": "^3.0.5",
"c8": "^9.1.0",
"mocha": "^10.4.0",
"rollup": "^4.16.2",
"rollup-plugin-copy": "^3.5.0",
"typescript": "^5.4.5"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
}

201
node_modules/@eslint/config-helpers/LICENSE generated vendored Normal file
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 [yyyy] [name of copyright owner]
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.

98
node_modules/@eslint/config-helpers/README.md generated vendored Normal file
View File

@ -0,0 +1,98 @@
# @eslint/config-helpers
## Description
Helper utilities for creating ESLint configuration.
## Installation
For Node.js and compatible runtimes:
```shell
npm install @eslint/config-helpers
# or
yarn add @eslint/config-helpers
# or
pnpm install @eslint/config-helpers
# or
bun install @eslint/config-helpers
```
For Deno:
```shell
deno add @eslint/config-helpers
```
## Usage
### `defineConfig()`
The `defineConfig()` function allows you to specify an ESLint configuration with full type checking and additional capabilities, such as `extends`. Here's an example:
```js
// eslint.config.js
import { defineConfig } from "@eslint/config-helpers";
import js from "@eslint/js";
export default defineConfig([
{
files: ["src/**/*.js"],
plugins: { js },
extends: ["js/recommended"],
rules: {
semi: "error",
"prefer-const": "error",
},
},
{
files: ["test/**/*.js"],
rules: {
"no-console": "off",
},
},
]);
```
### `globalIgnores()`
The `globalIgnores()` function allows you to specify patterns for files and directories that should be globally ignored by ESLint. This is useful for excluding files that you don't want to lint, such as build directories or third-party libraries. Here's an example:
```js
// eslint.config.js
import { defineConfig, globalIgnores } from "@eslint/config-helpers";
export default defineConfig([
{
files: ["src/**/*.js"],
rules: {
semi: "error",
"prefer-const": "error",
},
},
globalIgnores(["node_modules/", "dist/", "coverage/"]),
]);
```
## License
Apache 2.0
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Diamond Sponsors</h3>
<p><a href="https://www.ag-grid.com/"><img src="https://images.opencollective.com/ag-grid/2c8d545/logo.png" alt="AG Grid" height="128"></a></p><h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a> <a href="https://trunk.io/"><img src="https://images.opencollective.com/trunkio/fb92d60/avatar.png" alt="trunk.io" height="96"></a> <a href="https://shopify.engineering/"><img src="https://avatars.githubusercontent.com/u/8085" alt="Shopify" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/e6d15e1/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://americanexpress.io"><img src="https://avatars.githubusercontent.com/u/3853301" alt="American Express" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://nolebase.ayaka.io"><img src="https://avatars.githubusercontent.com/u/11081491" alt="Neko" height="32"></a> <a href="https://nx.dev"><img src="https://avatars.githubusercontent.com/u/23692104" alt="Nx" height="32"></a> <a href="https://opensource.mercedes-benz.com/"><img src="https://avatars.githubusercontent.com/u/34240465" alt="Mercedes-Benz Group" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="LambdaTest" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->

60
node_modules/@eslint/config-helpers/package.json generated vendored Normal file
View File

@ -0,0 +1,60 @@
{
"name": "@eslint/config-helpers",
"version": "0.2.2",
"description": "Helper utilities for creating ESLint configuration",
"type": "module",
"main": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
"exports": {
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
},
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
}
},
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"directories": {
"test": "tests"
},
"scripts": {
"build:dedupe-types": "node ../../tools/dedupe-types.js dist/cjs/index.cjs dist/esm/index.js",
"build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts",
"build": "rollup -c && npm run build:dedupe-types && tsc -p tsconfig.esm.json && npm run build:cts",
"test:jsr": "npx jsr@latest publish --dry-run",
"test": "mocha tests/*.js",
"test:coverage": "c8 npm test",
"test:types": "tsc -p tests/types/tsconfig.json"
},
"repository": {
"type": "git",
"url": "git+https://github.com/eslint/rewrite.git"
},
"keywords": [
"eslint"
],
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/eslint/rewrite/issues"
},
"homepage": "https://github.com/eslint/rewrite/tree/main/packages/config-helpers#readme",
"devDependencies": {
"@eslint/core": "^0.14.0",
"c8": "^9.1.0",
"eslint": "^9.19.0",
"mocha": "^10.4.0",
"rollup": "^4.16.2",
"rollup-plugin-copy": "^3.5.0",
"typescript": "^5.4.5"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
}

201
node_modules/@eslint/core/LICENSE generated vendored Normal file
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 [yyyy] [name of copyright owner]
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.

29
node_modules/@eslint/core/README.md generated vendored Normal file
View File

@ -0,0 +1,29 @@
# ESLint Core
## Overview
This package is the future home of the rewritten, runtime-agnostic ESLint core.
Right now, it exports the core types necessary to implement language plugins.
## License
Apache 2.0
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a> <a href="https://trunk.io/"><img src="https://images.opencollective.com/trunkio/fb92d60/avatar.png" alt="trunk.io" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/e6d15e1/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://nolebase.ayaka.io"><img src="https://avatars.githubusercontent.com/u/11081491" alt="Neko" height="32"></a> <a href="https://nx.dev"><img src="https://avatars.githubusercontent.com/u/23692104" alt="Nx" height="32"></a> <a href="https://opensource.mercedes-benz.com/"><img src="https://avatars.githubusercontent.com/u/34240465" alt="Mercedes-Benz Group" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="LambdaTest" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->

49
node_modules/@eslint/core/package.json generated vendored Normal file
View File

@ -0,0 +1,49 @@
{
"name": "@eslint/core",
"version": "0.13.0",
"description": "Runtime-agnostic core of ESLint",
"type": "module",
"types": "./dist/esm/types.d.ts",
"exports": {
"types": {
"import": "./dist/esm/types.d.ts",
"require": "./dist/cjs/types.d.cts"
}
},
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build:cts": "node -e \"fs.cpSync('dist/esm/types.d.ts', 'dist/cjs/types.d.cts')\"",
"build": "tsc && npm run build:cts",
"test:jsr": "npx jsr@latest publish --dry-run",
"test:types": "tsc -p tests/types/tsconfig.json"
},
"repository": {
"type": "git",
"url": "git+https://github.com/eslint/rewrite.git"
},
"keywords": [
"eslint",
"core"
],
"author": "Nicholas C. Zakas",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/eslint/rewrite/issues"
},
"homepage": "https://github.com/eslint/rewrite#readme",
"dependencies": {
"@types/json-schema": "^7.0.15"
},
"devDependencies": {
"json-schema": "^0.4.0",
"typescript": "^5.4.5"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
}

19
node_modules/@eslint/eslintrc/LICENSE generated vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright OpenJS Foundation and other contributors, <www.openjsf.org>
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.

128
node_modules/@eslint/eslintrc/README.md generated vendored Normal file
View File

@ -0,0 +1,128 @@
# ESLintRC Library
This repository contains the legacy ESLintRC configuration file format for ESLint. This package is not intended for use outside of the ESLint ecosystem. It is ESLint-specific and not intended for use in other programs.
**Note:** This package is frozen except for critical bug fixes as ESLint moves to a new config system.
## Installation
You can install the package as follows:
```shell
npm install @eslint/eslintrc -D
# or
yarn add @eslint/eslintrc -D
# or
pnpm install @eslint/eslintrc -D
# or
bun install @eslint/eslintrc -D
```
## Usage (ESM)
The primary class in this package is `FlatCompat`, which is a utility to translate ESLintRC-style configs into flat configs. Here's how you use it inside of your `eslint.config.js` file:
```js
import { FlatCompat } from "@eslint/eslintrc";
import js from "@eslint/js";
import path from "path";
import { fileURLToPath } from "url";
// mimic CommonJS variables -- not needed if using CommonJS
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname, // optional; default: process.cwd()
resolvePluginsRelativeTo: __dirname, // optional
recommendedConfig: js.configs.recommended, // optional unless you're using "eslint:recommended"
allConfig: js.configs.all, // optional unless you're using "eslint:all"
});
export default [
// mimic ESLintRC-style extends
...compat.extends("standard", "example", "plugin:react/recommended"),
// mimic environments
...compat.env({
es2020: true,
node: true
}),
// mimic plugins
...compat.plugins("jsx-a11y", "react"),
// translate an entire config
...compat.config({
plugins: ["jsx-a11y", "react"],
extends: "standard",
env: {
es2020: true,
node: true
},
rules: {
semi: "error"
}
})
];
```
## Usage (CommonJS)
Using `FlatCompat` in CommonJS files is similar to ESM, but you'll use `require()` and `module.exports` instead of `import` and `export`. Here's how you use it inside of your `eslint.config.js` CommonJS file:
```js
const { FlatCompat } = require("@eslint/eslintrc");
const js = require("@eslint/js");
const compat = new FlatCompat({
baseDirectory: __dirname, // optional; default: process.cwd()
resolvePluginsRelativeTo: __dirname, // optional
recommendedConfig: js.configs.recommended, // optional unless using "eslint:recommended"
allConfig: js.configs.all, // optional unless using "eslint:all"
});
module.exports = [
// mimic ESLintRC-style extends
...compat.extends("standard", "example", "plugin:react/recommended"),
// mimic environments
...compat.env({
es2020: true,
node: true
}),
// mimic plugins
...compat.plugins("jsx-a11y", "react"),
// translate an entire config
...compat.config({
plugins: ["jsx-a11y", "react"],
extends: "standard",
env: {
es2020: true,
node: true
},
rules: {
semi: "error"
}
})
];
```
## Troubleshooting
**TypeError: Missing parameter 'recommendedConfig' in FlatCompat constructor**
The `recommendedConfig` option is required when any config uses `eslint:recommended`, including any config in an `extends` clause. To fix this, follow the example above using `@eslint/js` to provide the `eslint:recommended` config.
**TypeError: Missing parameter 'allConfig' in FlatCompat constructor**
The `allConfig` option is required when any config uses `eslint:all`, including any config in an `extends` clause. To fix this, follow the example above using `@eslint/js` to provide the `eslint:all` config.
## License
MIT License

79
node_modules/@eslint/eslintrc/conf/config-schema.js generated vendored Normal file
View File

@ -0,0 +1,79 @@
/**
* @fileoverview Defines a schema for configs.
* @author Sylvan Mably
*/
const baseConfigProperties = {
$schema: { type: "string" },
env: { type: "object" },
extends: { $ref: "#/definitions/stringOrStrings" },
globals: { type: "object" },
overrides: {
type: "array",
items: { $ref: "#/definitions/overrideConfig" },
additionalItems: false
},
parser: { type: ["string", "null"] },
parserOptions: { type: "object" },
plugins: { type: "array" },
processor: { type: "string" },
rules: { type: "object" },
settings: { type: "object" },
noInlineConfig: { type: "boolean" },
reportUnusedDisableDirectives: { type: "boolean" },
ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
};
const configSchema = {
definitions: {
stringOrStrings: {
oneOf: [
{ type: "string" },
{
type: "array",
items: { type: "string" },
additionalItems: false
}
]
},
stringOrStringsRequired: {
oneOf: [
{ type: "string" },
{
type: "array",
items: { type: "string" },
additionalItems: false,
minItems: 1
}
]
},
// Config at top-level.
objectConfig: {
type: "object",
properties: {
root: { type: "boolean" },
ignorePatterns: { $ref: "#/definitions/stringOrStrings" },
...baseConfigProperties
},
additionalProperties: false
},
// Config in `overrides`.
overrideConfig: {
type: "object",
properties: {
excludedFiles: { $ref: "#/definitions/stringOrStrings" },
files: { $ref: "#/definitions/stringOrStringsRequired" },
...baseConfigProperties
},
required: ["files"],
additionalProperties: false
}
},
$ref: "#/definitions/objectConfig"
};
export default configSchema;

215
node_modules/@eslint/eslintrc/conf/environments.js generated vendored Normal file
View File

@ -0,0 +1,215 @@
/**
* @fileoverview Defines environment settings and globals.
* @author Elan Shanker
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import globals from "globals";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Get the object that has difference.
* @param {Record<string,boolean>} current The newer object.
* @param {Record<string,boolean>} prev The older object.
* @returns {Record<string,boolean>} The difference object.
*/
function getDiff(current, prev) {
const retv = {};
for (const [key, value] of Object.entries(current)) {
if (!Object.hasOwn(prev, key)) {
retv[key] = value;
}
}
return retv;
}
const newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ...
const newGlobals2017 = {
Atomics: false,
SharedArrayBuffer: false
};
const newGlobals2020 = {
BigInt: false,
BigInt64Array: false,
BigUint64Array: false,
globalThis: false
};
const newGlobals2021 = {
AggregateError: false,
FinalizationRegistry: false,
WeakRef: false
};
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/** @type {Map<string, import("../lib/shared/types").Environment>} */
export default new Map(Object.entries({
// Language
builtin: {
globals: globals.es5
},
es6: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 6
}
},
es2015: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 6
}
},
es2016: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 7
}
},
es2017: {
globals: { ...newGlobals2015, ...newGlobals2017 },
parserOptions: {
ecmaVersion: 8
}
},
es2018: {
globals: { ...newGlobals2015, ...newGlobals2017 },
parserOptions: {
ecmaVersion: 9
}
},
es2019: {
globals: { ...newGlobals2015, ...newGlobals2017 },
parserOptions: {
ecmaVersion: 10
}
},
es2020: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
parserOptions: {
ecmaVersion: 11
}
},
es2021: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
parserOptions: {
ecmaVersion: 12
}
},
es2022: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
parserOptions: {
ecmaVersion: 13
}
},
es2023: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
parserOptions: {
ecmaVersion: 14
}
},
es2024: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
parserOptions: {
ecmaVersion: 15
}
},
// Platforms
browser: {
globals: globals.browser
},
node: {
globals: globals.node,
parserOptions: {
ecmaFeatures: {
globalReturn: true
}
}
},
"shared-node-browser": {
globals: globals["shared-node-browser"]
},
worker: {
globals: globals.worker
},
serviceworker: {
globals: globals.serviceworker
},
// Frameworks
commonjs: {
globals: globals.commonjs,
parserOptions: {
ecmaFeatures: {
globalReturn: true
}
}
},
amd: {
globals: globals.amd
},
mocha: {
globals: globals.mocha
},
jasmine: {
globals: globals.jasmine
},
jest: {
globals: globals.jest
},
phantomjs: {
globals: globals.phantomjs
},
jquery: {
globals: globals.jquery
},
qunit: {
globals: globals.qunit
},
prototypejs: {
globals: globals.prototypejs
},
shelljs: {
globals: globals.shelljs
},
meteor: {
globals: globals.meteor
},
mongo: {
globals: globals.mongo
},
protractor: {
globals: globals.protractor
},
applescript: {
globals: globals.applescript
},
nashorn: {
globals: globals.nashorn
},
atomtest: {
globals: globals.atomtest
},
embertest: {
globals: globals.embertest
},
webextensions: {
globals: globals.webextensions
},
greasemonkey: {
globals: globals.greasemonkey
}
}));

View File

@ -0,0 +1,534 @@
/**
* @fileoverview `CascadingConfigArrayFactory` class.
*
* `CascadingConfigArrayFactory` class has a responsibility:
*
* 1. Handles cascading of config files.
*
* It provides two methods:
*
* - `getConfigArrayForFile(filePath)`
* Get the corresponded configuration of a given file. This method doesn't
* throw even if the given file didn't exist.
* - `clearCache()`
* Clear the internal cache. You have to call this method when
* `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends
* on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import debugOrig from "debug";
import os from "node:os";
import path from "node:path";
import { ConfigArrayFactory } from "./config-array-factory.js";
import {
ConfigArray,
ConfigDependency,
IgnorePattern
} from "./config-array/index.js";
import ConfigValidator from "./shared/config-validator.js";
import { emitDeprecationWarning } from "./shared/deprecation-warnings.js";
const debug = debugOrig("eslintrc:cascading-config-array-factory");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// Define types for VSCode IntelliSense.
/** @typedef {import("./shared/types").ConfigData} ConfigData */
/** @typedef {import("./shared/types").Parser} Parser */
/** @typedef {import("./shared/types").Plugin} Plugin */
/** @typedef {import("./shared/types").Rule} Rule */
/** @typedef {ReturnType<ConfigArrayFactory["create"]>} ConfigArray */
/**
* @typedef {Object} CascadingConfigArrayFactoryOptions
* @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
* @property {ConfigData} [baseConfig] The config by `baseConfig` option.
* @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.
* @property {string} [cwd] The base directory to start lookup.
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
* @property {string[]} [rulePaths] The value of `--rulesdir` option.
* @property {string} [specificConfigPath] The value of `--config` option.
* @property {boolean} [useEslintrc] if `false` then it doesn't load config files.
* @property {Function} loadRules The function to use to load rules.
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
* @property {Object} [resolver=ModuleResolver] The module resolver object.
* @property {string} eslintAllPath The path to the definitions for eslint:all.
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
*/
/**
* @typedef {Object} CascadingConfigArrayFactoryInternalSlots
* @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.
* @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.
* @property {ConfigArray} cliConfigArray The config array of CLI options.
* @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.
* @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.
* @property {Map<string, ConfigArray>} configCache The cache from directory paths to config arrays.
* @property {string} cwd The base directory to start lookup.
* @property {WeakMap<ConfigArray, ConfigArray>} finalizeCache The cache from config arrays to finalized config arrays.
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
* @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.
* @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.
* @property {boolean} useEslintrc if `false` then it doesn't load config files.
* @property {Function} loadRules The function to use to load rules.
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
* @property {Object} [resolver=ModuleResolver] The module resolver object.
* @property {string} eslintAllPath The path to the definitions for eslint:all.
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
*/
/** @type {WeakMap<CascadingConfigArrayFactory, CascadingConfigArrayFactoryInternalSlots>} */
const internalSlotsMap = new WeakMap();
/**
* Create the config array from `baseConfig` and `rulePaths`.
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
* @returns {ConfigArray} The config array of the base configs.
*/
function createBaseConfigArray({
configArrayFactory,
baseConfigData,
rulePaths,
cwd,
loadRules
}) {
const baseConfigArray = configArrayFactory.create(
baseConfigData,
{ name: "BaseConfig" }
);
/*
* Create the config array element for the default ignore patterns.
* This element has `ignorePattern` property that ignores the default
* patterns in the current working directory.
*/
baseConfigArray.unshift(configArrayFactory.create(
{ ignorePatterns: IgnorePattern.DefaultPatterns },
{ name: "DefaultIgnorePattern" }
)[0]);
/*
* Load rules `--rulesdir` option as a pseudo plugin.
* Use a pseudo plugin to define rules of `--rulesdir`, so we can validate
* the rule's options with only information in the config array.
*/
if (rulePaths && rulePaths.length > 0) {
baseConfigArray.push({
type: "config",
name: "--rulesdir",
filePath: "",
plugins: {
"": new ConfigDependency({
definition: {
rules: rulePaths.reduce(
(map, rulesPath) => Object.assign(
map,
loadRules(rulesPath, cwd)
),
{}
)
},
filePath: "",
id: "",
importerName: "--rulesdir",
importerPath: ""
})
}
});
}
return baseConfigArray;
}
/**
* Create the config array from CLI options.
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
* @returns {ConfigArray} The config array of the base configs.
*/
function createCLIConfigArray({
cliConfigData,
configArrayFactory,
cwd,
ignorePath,
specificConfigPath
}) {
const cliConfigArray = configArrayFactory.create(
cliConfigData,
{ name: "CLIOptions" }
);
cliConfigArray.unshift(
...(ignorePath
? configArrayFactory.loadESLintIgnore(ignorePath)
: configArrayFactory.loadDefaultESLintIgnore())
);
if (specificConfigPath) {
cliConfigArray.unshift(
...configArrayFactory.loadFile(
specificConfigPath,
{ name: "--config", basePath: cwd }
)
);
}
return cliConfigArray;
}
/**
* The error type when there are files matched by a glob, but all of them have been ignored.
*/
class ConfigurationNotFoundError extends Error {
/**
* @param {string} directoryPath The directory path.
*/
constructor(directoryPath) {
super(`No ESLint configuration found in ${directoryPath}.`);
this.messageTemplate = "no-config-found";
this.messageData = { directoryPath };
}
}
/**
* This class provides the functionality that enumerates every file which is
* matched by given glob patterns and that configuration.
*/
class CascadingConfigArrayFactory {
/**
* Initialize this enumerator.
* @param {CascadingConfigArrayFactoryOptions} options The options.
*/
constructor({
additionalPluginPool = new Map(),
baseConfig: baseConfigData = null,
cliConfig: cliConfigData = null,
cwd = process.cwd(),
ignorePath,
resolvePluginsRelativeTo,
rulePaths = [],
specificConfigPath = null,
useEslintrc = true,
builtInRules = new Map(),
loadRules,
resolver,
eslintRecommendedPath,
getEslintRecommendedConfig,
eslintAllPath,
getEslintAllConfig
} = {}) {
const configArrayFactory = new ConfigArrayFactory({
additionalPluginPool,
cwd,
resolvePluginsRelativeTo,
builtInRules,
resolver,
eslintRecommendedPath,
getEslintRecommendedConfig,
eslintAllPath,
getEslintAllConfig
});
internalSlotsMap.set(this, {
baseConfigArray: createBaseConfigArray({
baseConfigData,
configArrayFactory,
cwd,
rulePaths,
loadRules
}),
baseConfigData,
cliConfigArray: createCLIConfigArray({
cliConfigData,
configArrayFactory,
cwd,
ignorePath,
specificConfigPath
}),
cliConfigData,
configArrayFactory,
configCache: new Map(),
cwd,
finalizeCache: new WeakMap(),
ignorePath,
rulePaths,
specificConfigPath,
useEslintrc,
builtInRules,
loadRules
});
}
/**
* The path to the current working directory.
* This is used by tests.
* @type {string}
*/
get cwd() {
const { cwd } = internalSlotsMap.get(this);
return cwd;
}
/**
* Get the config array of a given file.
* If `filePath` was not given, it returns the config which contains only
* `baseConfigData` and `cliConfigData`.
* @param {string} [filePath] The file path to a file.
* @param {Object} [options] The options.
* @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.
* @returns {ConfigArray} The config array of the file.
*/
getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) {
const {
baseConfigArray,
cliConfigArray,
cwd
} = internalSlotsMap.get(this);
if (!filePath) {
return new ConfigArray(...baseConfigArray, ...cliConfigArray);
}
const directoryPath = path.dirname(path.resolve(cwd, filePath));
debug(`Load config files for ${directoryPath}.`);
return this._finalizeConfigArray(
this._loadConfigInAncestors(directoryPath),
directoryPath,
ignoreNotFoundError
);
}
/**
* Set the config data to override all configs.
* Require to call `clearCache()` method after this method is called.
* @param {ConfigData} configData The config data to override all configs.
* @returns {void}
*/
setOverrideConfig(configData) {
const slots = internalSlotsMap.get(this);
slots.cliConfigData = configData;
}
/**
* Clear config cache.
* @returns {void}
*/
clearCache() {
const slots = internalSlotsMap.get(this);
slots.baseConfigArray = createBaseConfigArray(slots);
slots.cliConfigArray = createCLIConfigArray(slots);
slots.configCache.clear();
}
/**
* Load and normalize config files from the ancestor directories.
* @param {string} directoryPath The path to a leaf directory.
* @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.
* @returns {ConfigArray} The loaded config.
* @throws {Error} If a config file is invalid.
* @private
*/
_loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {
const {
baseConfigArray,
configArrayFactory,
configCache,
cwd,
useEslintrc
} = internalSlotsMap.get(this);
if (!useEslintrc) {
return baseConfigArray;
}
let configArray = configCache.get(directoryPath);
// Hit cache.
if (configArray) {
debug(`Cache hit: ${directoryPath}.`);
return configArray;
}
debug(`No cache found: ${directoryPath}.`);
const homePath = os.homedir();
// Consider this is root.
if (directoryPath === homePath && cwd !== homePath) {
debug("Stop traversing because of considered root.");
if (configsExistInSubdirs) {
const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);
if (filePath) {
emitDeprecationWarning(
filePath,
"ESLINT_PERSONAL_CONFIG_SUPPRESS"
);
}
}
return this._cacheConfig(directoryPath, baseConfigArray);
}
// Load the config on this directory.
try {
configArray = configArrayFactory.loadInDirectory(directoryPath);
} catch (error) {
/* istanbul ignore next */
if (error.code === "EACCES") {
debug("Stop traversing because of 'EACCES' error.");
return this._cacheConfig(directoryPath, baseConfigArray);
}
throw error;
}
if (configArray.length > 0 && configArray.isRoot()) {
debug("Stop traversing because of 'root:true'.");
configArray.unshift(...baseConfigArray);
return this._cacheConfig(directoryPath, configArray);
}
// Load from the ancestors and merge it.
const parentPath = path.dirname(directoryPath);
const parentConfigArray = parentPath && parentPath !== directoryPath
? this._loadConfigInAncestors(
parentPath,
configsExistInSubdirs || configArray.length > 0
)
: baseConfigArray;
if (configArray.length > 0) {
configArray.unshift(...parentConfigArray);
} else {
configArray = parentConfigArray;
}
// Cache and return.
return this._cacheConfig(directoryPath, configArray);
}
/**
* Freeze and cache a given config.
* @param {string} directoryPath The path to a directory as a cache key.
* @param {ConfigArray} configArray The config array as a cache value.
* @returns {ConfigArray} The `configArray` (frozen).
*/
_cacheConfig(directoryPath, configArray) {
const { configCache } = internalSlotsMap.get(this);
Object.freeze(configArray);
configCache.set(directoryPath, configArray);
return configArray;
}
/**
* Finalize a given config array.
* Concatenate `--config` and other CLI options.
* @param {ConfigArray} configArray The parent config array.
* @param {string} directoryPath The path to the leaf directory to find config files.
* @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.
* @returns {ConfigArray} The loaded config.
* @throws {Error} If a config file is invalid.
* @private
*/
_finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {
const {
cliConfigArray,
configArrayFactory,
finalizeCache,
useEslintrc,
builtInRules
} = internalSlotsMap.get(this);
let finalConfigArray = finalizeCache.get(configArray);
if (!finalConfigArray) {
finalConfigArray = configArray;
// Load the personal config if there are no regular config files.
if (
useEslintrc &&
configArray.every(c => !c.filePath) &&
cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.
) {
const homePath = os.homedir();
debug("Loading the config file of the home directory:", homePath);
const personalConfigArray = configArrayFactory.loadInDirectory(
homePath,
{ name: "PersonalConfig" }
);
if (
personalConfigArray.length > 0 &&
!directoryPath.startsWith(homePath)
) {
const lastElement =
personalConfigArray.at(-1);
emitDeprecationWarning(
lastElement.filePath,
"ESLINT_PERSONAL_CONFIG_LOAD"
);
}
finalConfigArray = finalConfigArray.concat(personalConfigArray);
}
// Apply CLI options.
if (cliConfigArray.length > 0) {
finalConfigArray = finalConfigArray.concat(cliConfigArray);
}
// Validate rule settings and environments.
const validator = new ConfigValidator({
builtInRules
});
validator.validateConfigArray(finalConfigArray);
// Cache it.
Object.freeze(finalConfigArray);
finalizeCache.set(configArray, finalConfigArray);
debug(
"Configuration was determined: %o on %s",
finalConfigArray,
directoryPath
);
}
// At least one element (the default ignore patterns) exists.
if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {
throw new ConfigurationNotFoundError(directoryPath);
}
return finalConfigArray;
}
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export { CascadingConfigArrayFactory };

1162
node_modules/@eslint/eslintrc/lib/config-array-factory.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,512 @@
/**
* @fileoverview `ConfigArray` class.
*
* `ConfigArray` class expresses the full of a configuration. It has the entry
* config file, base config files that were extended, loaded parsers, and loaded
* plugins.
*
* `ConfigArray` class provides three properties and two methods.
*
* - `pluginEnvironments`
* - `pluginProcessors`
* - `pluginRules`
* The `Map` objects that contain the members of all plugins that this
* config array contains. Those map objects don't have mutation methods.
* Those keys are the member ID such as `pluginId/memberName`.
* - `isRoot()`
* If `true` then this configuration has `root:true` property.
* - `extractConfig(filePath)`
* Extract the final configuration for a given file. This means merging
* every config array element which that `criteria` property matched. The
* `filePath` argument must be an absolute path.
*
* `ConfigArrayFactory` provides the loading logic of config files.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import { ExtractedConfig } from "./extracted-config.js";
import { IgnorePattern } from "./ignore-pattern.js";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// Define types for VSCode IntelliSense.
/** @typedef {import("../../shared/types").Environment} Environment */
/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
/** @typedef {import("../../shared/types").RuleConf} RuleConf */
/** @typedef {import("../../shared/types").Rule} Rule */
/** @typedef {import("../../shared/types").Plugin} Plugin */
/** @typedef {import("../../shared/types").Processor} Processor */
/** @typedef {import("./config-dependency").DependentParser} DependentParser */
/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
/**
* @typedef {Object} ConfigArrayElement
* @property {string} name The name of this config element.
* @property {string} filePath The path to the source file of this config element.
* @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
* @property {Record<string, boolean>|undefined} env The environment settings.
* @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
* @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
* @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
* @property {DependentParser|undefined} parser The parser loader.
* @property {Object|undefined} parserOptions The parser options.
* @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
* @property {string|undefined} processor The processor name to refer plugin's processor.
* @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
* @property {boolean|undefined} root The flag to express root.
* @property {Record<string, RuleConf>|undefined} rules The rule settings
* @property {Object|undefined} settings The shared settings.
* @property {"config" | "ignore" | "implicit-processor"} type The element type.
*/
/**
* @typedef {Object} ConfigArrayInternalSlots
* @property {Map<string, ExtractedConfig>} cache The cache to extract configs.
* @property {ReadonlyMap<string, Environment>|null} envMap The map from environment ID to environment definition.
* @property {ReadonlyMap<string, Processor>|null} processorMap The map from processor ID to environment definition.
* @property {ReadonlyMap<string, Rule>|null} ruleMap The map from rule ID to rule definition.
*/
/** @type {WeakMap<ConfigArray, ConfigArrayInternalSlots>} */
const internalSlotsMap = new class extends WeakMap {
get(key) {
let value = super.get(key);
if (!value) {
value = {
cache: new Map(),
envMap: null,
processorMap: null,
ruleMap: null
};
super.set(key, value);
}
return value;
}
}();
/**
* Get the indices which are matched to a given file.
* @param {ConfigArrayElement[]} elements The elements.
* @param {string} filePath The path to a target file.
* @returns {number[]} The indices.
*/
function getMatchedIndices(elements, filePath) {
const indices = [];
for (let i = elements.length - 1; i >= 0; --i) {
const element = elements[i];
if (!element.criteria || (filePath && element.criteria.test(filePath))) {
indices.push(i);
}
}
return indices;
}
/**
* Check if a value is a non-null object.
* @param {any} x The value to check.
* @returns {boolean} `true` if the value is a non-null object.
*/
function isNonNullObject(x) {
return typeof x === "object" && x !== null;
}
/**
* Merge two objects.
*
* Assign every property values of `y` to `x` if `x` doesn't have the property.
* If `x`'s property value is an object, it does recursive.
* @param {Object} target The destination to merge
* @param {Object|undefined} source The source to merge.
* @returns {void}
*/
function mergeWithoutOverwrite(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
if (isNonNullObject(target[key])) {
mergeWithoutOverwrite(target[key], source[key]);
} else if (target[key] === void 0) {
if (isNonNullObject(source[key])) {
target[key] = Array.isArray(source[key]) ? [] : {};
mergeWithoutOverwrite(target[key], source[key]);
} else if (source[key] !== void 0) {
target[key] = source[key];
}
}
}
}
/**
* The error for plugin conflicts.
*/
class PluginConflictError extends Error {
/**
* Initialize this error object.
* @param {string} pluginId The plugin ID.
* @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.
*/
constructor(pluginId, plugins) {
super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`);
this.messageTemplate = "plugin-conflict";
this.messageData = { pluginId, plugins };
}
}
/**
* Merge plugins.
* `target`'s definition is prior to `source`'s.
* @param {Record<string, DependentPlugin>} target The destination to merge
* @param {Record<string, DependentPlugin>|undefined} source The source to merge.
* @returns {void}
* @throws {PluginConflictError} When a plugin was conflicted.
*/
function mergePlugins(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
const targetValue = target[key];
const sourceValue = source[key];
// Adopt the plugin which was found at first.
if (targetValue === void 0) {
if (sourceValue.error) {
throw sourceValue.error;
}
target[key] = sourceValue;
} else if (sourceValue.filePath !== targetValue.filePath) {
throw new PluginConflictError(key, [
{
filePath: targetValue.filePath,
importerName: targetValue.importerName
},
{
filePath: sourceValue.filePath,
importerName: sourceValue.importerName
}
]);
}
}
}
/**
* Merge rule configs.
* `target`'s definition is prior to `source`'s.
* @param {Record<string, Array>} target The destination to merge
* @param {Record<string, RuleConf>|undefined} source The source to merge.
* @returns {void}
*/
function mergeRuleConfigs(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
const targetDef = target[key];
const sourceDef = source[key];
// Adopt the rule config which was found at first.
if (targetDef === void 0) {
if (Array.isArray(sourceDef)) {
target[key] = [...sourceDef];
} else {
target[key] = [sourceDef];
}
/*
* If the first found rule config is severity only and the current rule
* config has options, merge the severity and the options.
*/
} else if (
targetDef.length === 1 &&
Array.isArray(sourceDef) &&
sourceDef.length >= 2
) {
targetDef.push(...sourceDef.slice(1));
}
}
}
/**
* Create the extracted config.
* @param {ConfigArray} instance The config elements.
* @param {number[]} indices The indices to use.
* @returns {ExtractedConfig} The extracted config.
* @throws {Error} When a plugin is conflicted.
*/
function createConfig(instance, indices) {
const config = new ExtractedConfig();
const ignorePatterns = [];
// Merge elements.
for (const index of indices) {
const element = instance[index];
// Adopt the parser which was found at first.
if (!config.parser && element.parser) {
if (element.parser.error) {
throw element.parser.error;
}
config.parser = element.parser;
}
// Adopt the processor which was found at first.
if (!config.processor && element.processor) {
config.processor = element.processor;
}
// Adopt the noInlineConfig which was found at first.
if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
config.noInlineConfig = element.noInlineConfig;
config.configNameOfNoInlineConfig = element.name;
}
// Adopt the reportUnusedDisableDirectives which was found at first.
if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
}
// Collect ignorePatterns
if (element.ignorePattern) {
ignorePatterns.push(element.ignorePattern);
}
// Merge others.
mergeWithoutOverwrite(config.env, element.env);
mergeWithoutOverwrite(config.globals, element.globals);
mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
mergeWithoutOverwrite(config.settings, element.settings);
mergePlugins(config.plugins, element.plugins);
mergeRuleConfigs(config.rules, element.rules);
}
// Create the predicate function for ignore patterns.
if (ignorePatterns.length > 0) {
config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
}
return config;
}
/**
* Collect definitions.
* @template T, U
* @param {string} pluginId The plugin ID for prefix.
* @param {Record<string,T>} defs The definitions to collect.
* @param {Map<string, U>} map The map to output.
* @returns {void}
*/
function collect(pluginId, defs, map) {
if (defs) {
const prefix = pluginId && `${pluginId}/`;
for (const [key, value] of Object.entries(defs)) {
map.set(`${prefix}${key}`, value);
}
}
}
/**
* Delete the mutation methods from a given map.
* @param {Map<any, any>} map The map object to delete.
* @returns {void}
*/
function deleteMutationMethods(map) {
Object.defineProperties(map, {
clear: { configurable: true, value: void 0 },
delete: { configurable: true, value: void 0 },
set: { configurable: true, value: void 0 }
});
}
/**
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
* @param {ConfigArrayElement[]} elements The config elements.
* @param {ConfigArrayInternalSlots} slots The internal slots.
* @returns {void}
*/
function initPluginMemberMaps(elements, slots) {
const processed = new Set();
slots.envMap = new Map();
slots.processorMap = new Map();
slots.ruleMap = new Map();
for (const element of elements) {
if (!element.plugins) {
continue;
}
for (const [pluginId, value] of Object.entries(element.plugins)) {
const plugin = value.definition;
if (!plugin || processed.has(pluginId)) {
continue;
}
processed.add(pluginId);
collect(pluginId, plugin.environments, slots.envMap);
collect(pluginId, plugin.processors, slots.processorMap);
collect(pluginId, plugin.rules, slots.ruleMap);
}
}
deleteMutationMethods(slots.envMap);
deleteMutationMethods(slots.processorMap);
deleteMutationMethods(slots.ruleMap);
}
/**
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
* @param {ConfigArray} instance The config elements.
* @returns {ConfigArrayInternalSlots} The extracted config.
*/
function ensurePluginMemberMaps(instance) {
const slots = internalSlotsMap.get(instance);
if (!slots.ruleMap) {
initPluginMemberMaps(instance, slots);
}
return slots;
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* The Config Array.
*
* `ConfigArray` instance contains all settings, parsers, and plugins.
* You need to call `ConfigArray#extractConfig(filePath)` method in order to
* extract, merge and get only the config data which is related to an arbitrary
* file.
* @extends {Array<ConfigArrayElement>}
*/
class ConfigArray extends Array {
/**
* Get the plugin environments.
* The returned map cannot be mutated.
* @type {ReadonlyMap<string, Environment>} The plugin environments.
*/
get pluginEnvironments() {
return ensurePluginMemberMaps(this).envMap;
}
/**
* Get the plugin processors.
* The returned map cannot be mutated.
* @type {ReadonlyMap<string, Processor>} The plugin processors.
*/
get pluginProcessors() {
return ensurePluginMemberMaps(this).processorMap;
}
/**
* Get the plugin rules.
* The returned map cannot be mutated.
* @returns {ReadonlyMap<string, Rule>} The plugin rules.
*/
get pluginRules() {
return ensurePluginMemberMaps(this).ruleMap;
}
/**
* Check if this config has `root` flag.
* @returns {boolean} `true` if this config array is root.
*/
isRoot() {
for (let i = this.length - 1; i >= 0; --i) {
const root = this[i].root;
if (typeof root === "boolean") {
return root;
}
}
return false;
}
/**
* Extract the config data which is related to a given file.
* @param {string} filePath The absolute path to the target file.
* @returns {ExtractedConfig} The extracted config data.
*/
extractConfig(filePath) {
const { cache } = internalSlotsMap.get(this);
const indices = getMatchedIndices(this, filePath);
const cacheKey = indices.join(",");
if (!cache.has(cacheKey)) {
cache.set(cacheKey, createConfig(this, indices));
}
return cache.get(cacheKey);
}
/**
* Check if a given path is an additional lint target.
* @param {string} filePath The absolute path to the target file.
* @returns {boolean} `true` if the file is an additional lint target.
*/
isAdditionalTargetPath(filePath) {
for (const { criteria, type } of this) {
if (
type === "config" &&
criteria &&
!criteria.endsWithWildcard &&
criteria.test(filePath)
) {
return true;
}
}
return false;
}
}
/**
* Get the used extracted configs.
* CLIEngine will use this method to collect used deprecated rules.
* @param {ConfigArray} instance The config array object to get.
* @returns {ExtractedConfig[]} The used extracted configs.
* @private
*/
function getUsedExtractedConfigs(instance) {
const { cache } = internalSlotsMap.get(instance);
return Array.from(cache.values());
}
export {
ConfigArray,
getUsedExtractedConfigs
};

View File

@ -0,0 +1,124 @@
/**
* @fileoverview `ConfigDependency` class.
*
* `ConfigDependency` class expresses a loaded parser or plugin.
*
* If the parser or plugin was loaded successfully, it has `definition` property
* and `filePath` property. Otherwise, it has `error` property.
*
* When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it
* omits `definition` property.
*
* `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers
* or plugins.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import util from "node:util";
/**
* The class is to store parsers or plugins.
* This class hides the loaded object from `JSON.stringify()` and `console.log`.
* @template T
*/
class ConfigDependency {
/**
* Initialize this instance.
* @param {Object} data The dependency data.
* @param {T} [data.definition] The dependency if the loading succeeded.
* @param {T} [data.original] The original, non-normalized dependency if the loading succeeded.
* @param {Error} [data.error] The error object if the loading failed.
* @param {string} [data.filePath] The actual path to the dependency if the loading succeeded.
* @param {string} data.id The ID of this dependency.
* @param {string} data.importerName The name of the config file which loads this dependency.
* @param {string} data.importerPath The path to the config file which loads this dependency.
*/
constructor({
definition = null,
original = null,
error = null,
filePath = null,
id,
importerName,
importerPath
}) {
/**
* The loaded dependency if the loading succeeded.
* @type {T|null}
*/
this.definition = definition;
/**
* The original dependency as loaded directly from disk if the loading succeeded.
* @type {T|null}
*/
this.original = original;
/**
* The error object if the loading failed.
* @type {Error|null}
*/
this.error = error;
/**
* The loaded dependency if the loading succeeded.
* @type {string|null}
*/
this.filePath = filePath;
/**
* The ID of this dependency.
* @type {string}
*/
this.id = id;
/**
* The name of the config file which loads this dependency.
* @type {string}
*/
this.importerName = importerName;
/**
* The path to the config file which loads this dependency.
* @type {string}
*/
this.importerPath = importerPath;
}
/**
* Converts this instance to a JSON compatible object.
* @returns {Object} a JSON compatible object.
*/
toJSON() {
const obj = this[util.inspect.custom]();
// Display `error.message` (`Error#message` is unenumerable).
if (obj.error instanceof Error) {
obj.error = { ...obj.error, message: obj.error.message };
}
return obj;
}
/**
* Custom inspect method for Node.js `console.log()`.
* @returns {Object} an object to display by `console.log()`.
*/
[util.inspect.custom]() {
const {
definition: _ignore1, // eslint-disable-line no-unused-vars -- needed to make `obj` correct
original: _ignore2, // eslint-disable-line no-unused-vars -- needed to make `obj` correct
...obj
} = this;
return obj;
}
}
/** @typedef {ConfigDependency<import("../../shared/types").Parser>} DependentParser */
/** @typedef {ConfigDependency<import("../../shared/types").Plugin>} DependentPlugin */
export { ConfigDependency };

View File

@ -0,0 +1,145 @@
/**
* @fileoverview `ExtractedConfig` class.
*
* `ExtractedConfig` class expresses a final configuration for a specific file.
*
* It provides one method.
*
* - `toCompatibleObjectAsConfigFileContent()`
* Convert this configuration to the compatible object as the content of
* config files. It converts the loaded parser and plugins to strings.
* `CLIEngine#getConfigForFile(filePath)` method uses this method.
*
* `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import { IgnorePattern } from "./ignore-pattern.js";
// For VSCode intellisense
/** @typedef {import("../../shared/types").ConfigData} ConfigData */
/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
/** @typedef {import("../../shared/types").SeverityConf} SeverityConf */
/** @typedef {import("./config-dependency").DependentParser} DependentParser */
/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
/**
* Check if `xs` starts with `ys`.
* @template T
* @param {T[]} xs The array to check.
* @param {T[]} ys The array that may be the first part of `xs`.
* @returns {boolean} `true` if `xs` starts with `ys`.
*/
function startsWith(xs, ys) {
return xs.length >= ys.length && ys.every((y, i) => y === xs[i]);
}
/**
* The class for extracted config data.
*/
class ExtractedConfig {
constructor() {
/**
* The config name what `noInlineConfig` setting came from.
* @type {string}
*/
this.configNameOfNoInlineConfig = "";
/**
* Environments.
* @type {Record<string, boolean>}
*/
this.env = {};
/**
* Global variables.
* @type {Record<string, GlobalConf>}
*/
this.globals = {};
/**
* The glob patterns that ignore to lint.
* @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined}
*/
this.ignores = void 0;
/**
* The flag that disables directive comments.
* @type {boolean|undefined}
*/
this.noInlineConfig = void 0;
/**
* Parser definition.
* @type {DependentParser|null}
*/
this.parser = null;
/**
* Options for the parser.
* @type {Object}
*/
this.parserOptions = {};
/**
* Plugin definitions.
* @type {Record<string, DependentPlugin>}
*/
this.plugins = {};
/**
* Processor ID.
* @type {string|null}
*/
this.processor = null;
/**
* The flag that reports unused `eslint-disable` directive comments.
* @type {boolean|undefined}
*/
this.reportUnusedDisableDirectives = void 0;
/**
* Rule settings.
* @type {Record<string, [SeverityConf, ...any[]]>}
*/
this.rules = {};
/**
* Shared settings.
* @type {Object}
*/
this.settings = {};
}
/**
* Convert this config to the compatible object as a config file content.
* @returns {ConfigData} The converted object.
*/
toCompatibleObjectAsConfigFileContent() {
const {
/* eslint-disable no-unused-vars -- needed to make `config` correct */
configNameOfNoInlineConfig: _ignore1,
processor: _ignore2,
/* eslint-enable no-unused-vars -- needed to make `config` correct */
ignores,
...config
} = this;
config.parser = config.parser && config.parser.filePath;
config.plugins = Object.keys(config.plugins).filter(Boolean).reverse();
config.ignorePatterns = ignores ? ignores.patterns : [];
// Strip the default patterns from `ignorePatterns`.
if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) {
config.ignorePatterns =
config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length);
}
return config;
}
}
export { ExtractedConfig };

View File

@ -0,0 +1,239 @@
/**
* @fileoverview `IgnorePattern` class.
*
* `IgnorePattern` class has the set of glob patterns and the base path.
*
* It provides two static methods.
*
* - `IgnorePattern.createDefaultIgnore(cwd)`
* Create the default predicate function.
* - `IgnorePattern.createIgnore(ignorePatterns)`
* Create the predicate function from multiple `IgnorePattern` objects.
*
* It provides two properties and a method.
*
* - `patterns`
* The glob patterns that ignore to lint.
* - `basePath`
* The base path of the glob patterns. If absolute paths existed in the
* glob patterns, those are handled as relative paths to the base path.
* - `getPatternsRelativeTo(basePath)`
* Get `patterns` as modified for a given base path. It modifies the
* absolute paths in the patterns as prepending the difference of two base
* paths.
*
* `ConfigArrayFactory` creates `IgnorePattern` objects when it processes
* `ignorePatterns` properties.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import assert from "node:assert";
import path from "node:path";
import ignore from "ignore";
import debugOrig from "debug";
const debug = debugOrig("eslintrc:ignore-pattern");
/** @typedef {ReturnType<import("ignore").default>} Ignore */
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Get the path to the common ancestor directory of given paths.
* @param {string[]} sourcePaths The paths to calculate the common ancestor.
* @returns {string} The path to the common ancestor directory.
*/
function getCommonAncestorPath(sourcePaths) {
let result = sourcePaths[0];
for (let i = 1; i < sourcePaths.length; ++i) {
const a = result;
const b = sourcePaths[i];
// Set the shorter one (it's the common ancestor if one includes the other).
result = a.length < b.length ? a : b;
// Set the common ancestor.
for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) {
if (a[j] !== b[j]) {
result = a.slice(0, lastSepPos);
break;
}
if (a[j] === path.sep) {
lastSepPos = j;
}
}
}
let resolvedResult = result || path.sep;
// if Windows common ancestor is root of drive must have trailing slash to be absolute.
if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") {
resolvedResult += path.sep;
}
return resolvedResult;
}
/**
* Make relative path.
* @param {string} from The source path to get relative path.
* @param {string} to The destination path to get relative path.
* @returns {string} The relative path.
*/
function relative(from, to) {
const relPath = path.relative(from, to);
if (path.sep === "/") {
return relPath;
}
return relPath.split(path.sep).join("/");
}
/**
* Get the trailing slash if existed.
* @param {string} filePath The path to check.
* @returns {string} The trailing slash if existed.
*/
function dirSuffix(filePath) {
const isDir = (
filePath.endsWith(path.sep) ||
(process.platform === "win32" && filePath.endsWith("/"))
);
return isDir ? "/" : "";
}
const DefaultPatterns = Object.freeze(["/**/node_modules/*"]);
const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]);
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
/**
* Represents a set of glob patterns to ignore against a base path.
*/
class IgnorePattern {
/**
* The default patterns.
* @type {string[]}
*/
static get DefaultPatterns() {
return DefaultPatterns;
}
/**
* Create the default predicate function.
* @param {string} cwd The current working directory.
* @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}}
* The preficate function.
* The first argument is an absolute path that is checked.
* The second argument is the flag to not ignore dotfiles.
* If the predicate function returned `true`, it means the path should be ignored.
*/
static createDefaultIgnore(cwd) {
return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]);
}
/**
* Create the predicate function from multiple `IgnorePattern` objects.
* @param {IgnorePattern[]} ignorePatterns The list of ignore patterns.
* @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}}
* The preficate function.
* The first argument is an absolute path that is checked.
* The second argument is the flag to not ignore dotfiles.
* If the predicate function returned `true`, it means the path should be ignored.
*/
static createIgnore(ignorePatterns) {
debug("Create with: %o", ignorePatterns);
const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath));
const patterns = ignorePatterns.flatMap(p => p.getPatternsRelativeTo(basePath));
const ig = ignore({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]);
const dotIg = ignore({ allowRelativePaths: true }).add(patterns);
debug(" processed: %o", { basePath, patterns });
return Object.assign(
(filePath, dot = false) => {
assert(path.isAbsolute(filePath), "'filePath' should be an absolute path.");
const relPathRaw = relative(basePath, filePath);
const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath));
const adoptedIg = dot ? dotIg : ig;
const result = relPath !== "" && adoptedIg.ignores(relPath);
debug("Check", { filePath, dot, relativePath: relPath, result });
return result;
},
{ basePath, patterns }
);
}
/**
* Initialize a new `IgnorePattern` instance.
* @param {string[]} patterns The glob patterns that ignore to lint.
* @param {string} basePath The base path of `patterns`.
*/
constructor(patterns, basePath) {
assert(path.isAbsolute(basePath), "'basePath' should be an absolute path.");
/**
* The glob patterns that ignore to lint.
* @type {string[]}
*/
this.patterns = patterns;
/**
* The base path of `patterns`.
* @type {string}
*/
this.basePath = basePath;
/**
* If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`.
*
* It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility.
* It's `false` as-is for `ignorePatterns` property in config files.
* @type {boolean}
*/
this.loose = false;
}
/**
* Get `patterns` as modified for a given base path. It modifies the
* absolute paths in the patterns as prepending the difference of two base
* paths.
* @param {string} newBasePath The base path.
* @returns {string[]} Modifired patterns.
*/
getPatternsRelativeTo(newBasePath) {
assert(path.isAbsolute(newBasePath), "'newBasePath' should be an absolute path.");
const { basePath, loose, patterns } = this;
if (newBasePath === basePath) {
return patterns;
}
const prefix = `/${relative(newBasePath, basePath)}`;
return patterns.map(pattern => {
const negative = pattern.startsWith("!");
const head = negative ? "!" : "";
const body = negative ? pattern.slice(1) : pattern;
if (body.startsWith("/") || body.startsWith("../")) {
return `${head}${prefix}${body}`;
}
return loose ? pattern : `${head}${prefix}/**/${body}`;
});
}
}
export { IgnorePattern };

View File

@ -0,0 +1,19 @@
/**
* @fileoverview `ConfigArray` class.
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import { ConfigArray, getUsedExtractedConfigs } from "./config-array.js";
import { ConfigDependency } from "./config-dependency.js";
import { ExtractedConfig } from "./extracted-config.js";
import { IgnorePattern } from "./ignore-pattern.js";
import { OverrideTester } from "./override-tester.js";
export {
ConfigArray,
ConfigDependency,
ExtractedConfig,
IgnorePattern,
OverrideTester,
getUsedExtractedConfigs
};

View File

@ -0,0 +1,227 @@
/**
* @fileoverview `OverrideTester` class.
*
* `OverrideTester` class handles `files` property and `excludedFiles` property
* of `overrides` config.
*
* It provides one method.
*
* - `test(filePath)`
* Test if a file path matches the pair of `files` property and
* `excludedFiles` property. The `filePath` argument must be an absolute
* path.
*
* `ConfigArrayFactory` creates `OverrideTester` objects when it processes
* `overrides` properties.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import assert from "node:assert";
import path from "node:path";
import util from "node:util";
import minimatch from "minimatch";
const { Minimatch } = minimatch;
const minimatchOpts = { dot: true, matchBase: true };
/**
* @typedef {Object} Pattern
* @property {InstanceType<Minimatch>[] | null} includes The positive matchers.
* @property {InstanceType<Minimatch>[] | null} excludes The negative matchers.
*/
/**
* Normalize a given pattern to an array.
* @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns.
* @returns {string[]|null} Normalized patterns.
* @private
*/
function normalizePatterns(patterns) {
if (Array.isArray(patterns)) {
return patterns.filter(Boolean);
}
if (typeof patterns === "string" && patterns) {
return [patterns];
}
return [];
}
/**
* Create the matchers of given patterns.
* @param {string[]} patterns The patterns.
* @returns {InstanceType<Minimatch>[] | null} The matchers.
*/
function toMatcher(patterns) {
if (patterns.length === 0) {
return null;
}
return patterns.map(pattern => {
if (/^\.[/\\]/u.test(pattern)) {
return new Minimatch(
pattern.slice(2),
// `./*.js` should not match with `subdir/foo.js`
{ ...minimatchOpts, matchBase: false }
);
}
return new Minimatch(pattern, minimatchOpts);
});
}
/**
* Convert a given matcher to string.
* @param {Pattern} matchers The matchers.
* @returns {string} The string expression of the matcher.
*/
function patternToJson({ includes, excludes }) {
return {
includes: includes && includes.map(m => m.pattern),
excludes: excludes && excludes.map(m => m.pattern)
};
}
/**
* The class to test given paths are matched by the patterns.
*/
class OverrideTester {
/**
* Create a tester with given criteria.
* If there are no criteria, returns `null`.
* @param {string|string[]} files The glob patterns for included files.
* @param {string|string[]} excludedFiles The glob patterns for excluded files.
* @param {string} basePath The path to the base directory to test paths.
* @returns {OverrideTester|null} The created instance or `null`.
* @throws {Error} When invalid patterns are given.
*/
static create(files, excludedFiles, basePath) {
const includePatterns = normalizePatterns(files);
const excludePatterns = normalizePatterns(excludedFiles);
let endsWithWildcard = false;
if (includePatterns.length === 0) {
return null;
}
// Rejects absolute paths or relative paths to parents.
for (const pattern of includePatterns) {
if (path.isAbsolute(pattern) || pattern.includes("..")) {
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
}
if (pattern.endsWith("*")) {
endsWithWildcard = true;
}
}
for (const pattern of excludePatterns) {
if (path.isAbsolute(pattern) || pattern.includes("..")) {
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
}
}
const includes = toMatcher(includePatterns);
const excludes = toMatcher(excludePatterns);
return new OverrideTester(
[{ includes, excludes }],
basePath,
endsWithWildcard
);
}
/**
* Combine two testers by logical and.
* If either of the testers was `null`, returns the other tester.
* The `basePath` property of the two must be the same value.
* @param {OverrideTester|null} a A tester.
* @param {OverrideTester|null} b Another tester.
* @returns {OverrideTester|null} Combined tester.
*/
static and(a, b) {
if (!b) {
return a && new OverrideTester(
a.patterns,
a.basePath,
a.endsWithWildcard
);
}
if (!a) {
return new OverrideTester(
b.patterns,
b.basePath,
b.endsWithWildcard
);
}
assert.strictEqual(a.basePath, b.basePath);
return new OverrideTester(
a.patterns.concat(b.patterns),
a.basePath,
a.endsWithWildcard || b.endsWithWildcard
);
}
/**
* Initialize this instance.
* @param {Pattern[]} patterns The matchers.
* @param {string} basePath The base path.
* @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`.
*/
constructor(patterns, basePath, endsWithWildcard = false) {
/** @type {Pattern[]} */
this.patterns = patterns;
/** @type {string} */
this.basePath = basePath;
/** @type {boolean} */
this.endsWithWildcard = endsWithWildcard;
}
/**
* Test if a given path is matched or not.
* @param {string} filePath The absolute path to the target file.
* @returns {boolean} `true` if the path was matched.
* @throws {Error} When invalid `filePath` is given.
*/
test(filePath) {
if (typeof filePath !== "string" || !path.isAbsolute(filePath)) {
throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`);
}
const relativePath = path.relative(this.basePath, filePath);
return this.patterns.every(({ includes, excludes }) => (
(!includes || includes.some(m => m.match(relativePath))) &&
(!excludes || !excludes.some(m => m.match(relativePath)))
));
}
/**
* Converts this instance to a JSON compatible object.
* @returns {Object} a JSON compatible object.
*/
toJSON() {
if (this.patterns.length === 1) {
return {
...patternToJson(this.patterns[0]),
basePath: this.basePath
};
}
return {
AND: this.patterns.map(patternToJson),
basePath: this.basePath
};
}
/**
* Custom inspect method for Node.js `console.log()`.
* @returns {Object} an object to display by `console.log()`.
*/
[util.inspect.custom]() {
return this.toJSON();
}
}
export { OverrideTester };

319
node_modules/@eslint/eslintrc/lib/flat-compat.js generated vendored Normal file
View File

@ -0,0 +1,319 @@
/**
* @fileoverview Compatibility class for flat config.
* @author Nicholas C. Zakas
*/
//-----------------------------------------------------------------------------
// Requirements
//-----------------------------------------------------------------------------
import createDebug from "debug";
import path from "node:path";
import environments from "../conf/environments.js";
import { ConfigArrayFactory } from "./config-array-factory.js";
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
/** @typedef {import("../../shared/types").Environment} Environment */
/** @typedef {import("../../shared/types").Processor} Processor */
const debug = createDebug("eslintrc:flat-compat");
const cafactory = Symbol("cafactory");
/**
* Translates an ESLintRC-style config object into a flag-config-style config
* object.
* @param {Object} eslintrcConfig An ESLintRC-style config object.
* @param {Object} options Options to help translate the config.
* @param {string} options.resolveConfigRelativeTo To the directory to resolve
* configs from.
* @param {string} options.resolvePluginsRelativeTo The directory to resolve
* plugins from.
* @param {ReadOnlyMap<string,Environment>} options.pluginEnvironments A map of plugin environment
* names to objects.
* @param {ReadOnlyMap<string,Processor>} options.pluginProcessors A map of plugin processor
* names to objects.
* @returns {Object} A flag-config-style config object.
* @throws {Error} If a plugin or environment cannot be resolved.
*/
function translateESLintRC(eslintrcConfig, {
resolveConfigRelativeTo,
resolvePluginsRelativeTo,
pluginEnvironments,
pluginProcessors
}) {
const flatConfig = {};
const configs = [];
const languageOptions = {};
const linterOptions = {};
const keysToCopy = ["settings", "rules", "processor"];
const languageOptionsKeysToCopy = ["globals", "parser", "parserOptions"];
const linterOptionsKeysToCopy = ["noInlineConfig", "reportUnusedDisableDirectives"];
// copy over simple translations
for (const key of keysToCopy) {
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
flatConfig[key] = eslintrcConfig[key];
}
}
// copy over languageOptions
for (const key of languageOptionsKeysToCopy) {
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
// create the languageOptions key in the flat config
flatConfig.languageOptions = languageOptions;
if (key === "parser") {
debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`);
if (eslintrcConfig[key].error) {
throw eslintrcConfig[key].error;
}
languageOptions[key] = eslintrcConfig[key].definition;
continue;
}
// clone any object values that are in the eslintrc config
if (eslintrcConfig[key] && typeof eslintrcConfig[key] === "object") {
languageOptions[key] = {
...eslintrcConfig[key]
};
} else {
languageOptions[key] = eslintrcConfig[key];
}
}
}
// copy over linterOptions
for (const key of linterOptionsKeysToCopy) {
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
flatConfig.linterOptions = linterOptions;
linterOptions[key] = eslintrcConfig[key];
}
}
// move ecmaVersion a level up
if (languageOptions.parserOptions) {
if ("ecmaVersion" in languageOptions.parserOptions) {
languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion;
delete languageOptions.parserOptions.ecmaVersion;
}
if ("sourceType" in languageOptions.parserOptions) {
languageOptions.sourceType = languageOptions.parserOptions.sourceType;
delete languageOptions.parserOptions.sourceType;
}
// check to see if we even need parserOptions anymore and remove it if not
if (Object.keys(languageOptions.parserOptions).length === 0) {
delete languageOptions.parserOptions;
}
}
// overrides
if (eslintrcConfig.criteria) {
flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)];
}
// translate plugins
if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === "object") {
debug(`Translating plugins: ${eslintrcConfig.plugins}`);
flatConfig.plugins = {};
for (const pluginName of Object.keys(eslintrcConfig.plugins)) {
debug(`Translating plugin: ${pluginName}`);
debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`);
const { original: plugin, error } = eslintrcConfig.plugins[pluginName];
if (error) {
throw error;
}
flatConfig.plugins[pluginName] = plugin;
// create a config for any processors
if (plugin.processors) {
for (const processorName of Object.keys(plugin.processors)) {
if (processorName.startsWith(".")) {
debug(`Assigning processor: ${pluginName}/${processorName}`);
configs.unshift({
files: [`**/*${processorName}`],
processor: pluginProcessors.get(`${pluginName}/${processorName}`)
});
}
}
}
}
}
// translate env - must come after plugins
if (eslintrcConfig.env && typeof eslintrcConfig.env === "object") {
for (const envName of Object.keys(eslintrcConfig.env)) {
// only add environments that are true
if (eslintrcConfig.env[envName]) {
debug(`Translating environment: ${envName}`);
if (environments.has(envName)) {
// built-in environments should be defined first
configs.unshift(...translateESLintRC({
criteria: eslintrcConfig.criteria,
...environments.get(envName)
}, {
resolveConfigRelativeTo,
resolvePluginsRelativeTo
}));
} else if (pluginEnvironments.has(envName)) {
// if the environment comes from a plugin, it should come after the plugin config
configs.push(...translateESLintRC({
criteria: eslintrcConfig.criteria,
...pluginEnvironments.get(envName)
}, {
resolveConfigRelativeTo,
resolvePluginsRelativeTo
}));
}
}
}
}
// only add if there are actually keys in the config
if (Object.keys(flatConfig).length > 0) {
configs.push(flatConfig);
}
return configs;
}
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* A compatibility class for working with configs.
*/
class FlatCompat {
constructor({
baseDirectory = process.cwd(),
resolvePluginsRelativeTo = baseDirectory,
recommendedConfig,
allConfig
} = {}) {
this.baseDirectory = baseDirectory;
this.resolvePluginsRelativeTo = resolvePluginsRelativeTo;
this[cafactory] = new ConfigArrayFactory({
cwd: baseDirectory,
resolvePluginsRelativeTo,
getEslintAllConfig() {
if (!allConfig) {
throw new TypeError("Missing parameter 'allConfig' in FlatCompat constructor.");
}
return allConfig;
},
getEslintRecommendedConfig() {
if (!recommendedConfig) {
throw new TypeError("Missing parameter 'recommendedConfig' in FlatCompat constructor.");
}
return recommendedConfig;
}
});
}
/**
* Translates an ESLintRC-style config into a flag-config-style config.
* @param {Object} eslintrcConfig The ESLintRC-style config object.
* @returns {Object} A flag-config-style config object.
*/
config(eslintrcConfig) {
const eslintrcArray = this[cafactory].create(eslintrcConfig, {
basePath: this.baseDirectory
});
const flatArray = [];
let hasIgnorePatterns = false;
eslintrcArray.forEach(configData => {
if (configData.type === "config") {
hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern;
flatArray.push(...translateESLintRC(configData, {
resolveConfigRelativeTo: path.join(this.baseDirectory, "__placeholder.js"),
resolvePluginsRelativeTo: path.join(this.resolvePluginsRelativeTo, "__placeholder.js"),
pluginEnvironments: eslintrcArray.pluginEnvironments,
pluginProcessors: eslintrcArray.pluginProcessors
}));
}
});
// combine ignorePatterns to emulate ESLintRC behavior better
if (hasIgnorePatterns) {
flatArray.unshift({
ignores: [filePath => {
// Compute the final config for this file.
// This filters config array elements by `files`/`excludedFiles` then merges the elements.
const finalConfig = eslintrcArray.extractConfig(filePath);
// Test the `ignorePattern` properties of the final config.
return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath);
}]
});
}
return flatArray;
}
/**
* Translates the `env` section of an ESLintRC-style config.
* @param {Object} envConfig The `env` section of an ESLintRC config.
* @returns {Object[]} An array of flag-config objects representing the environments.
*/
env(envConfig) {
return this.config({
env: envConfig
});
}
/**
* Translates the `extends` section of an ESLintRC-style config.
* @param {...string} configsToExtend The names of the configs to load.
* @returns {Object[]} An array of flag-config objects representing the config.
*/
extends(...configsToExtend) {
return this.config({
extends: configsToExtend
});
}
/**
* Translates the `plugins` section of an ESLintRC-style config.
* @param {...string} plugins The names of the plugins to load.
* @returns {Object[]} An array of flag-config objects representing the plugins.
*/
plugins(...plugins) {
return this.config({
plugins
});
}
}
export { FlatCompat };

29
node_modules/@eslint/eslintrc/lib/index-universal.js generated vendored Normal file
View File

@ -0,0 +1,29 @@
/**
* @fileoverview Package exports for @eslint/eslintrc
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import * as ConfigOps from "./shared/config-ops.js";
import ConfigValidator from "./shared/config-validator.js";
import * as naming from "./shared/naming.js";
import environments from "../conf/environments.js";
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
const Legacy = {
environments,
// shared
ConfigOps,
ConfigValidator,
naming
};
export {
Legacy
};

58
node_modules/@eslint/eslintrc/lib/index.js generated vendored Normal file
View File

@ -0,0 +1,58 @@
/**
* @fileoverview Package exports for @eslint/eslintrc
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import {
ConfigArrayFactory,
createContext as createConfigArrayFactoryContext,
loadConfigFile
} from "./config-array-factory.js";
import { CascadingConfigArrayFactory } from "./cascading-config-array-factory.js";
import * as ModuleResolver from "./shared/relative-module-resolver.js";
import { ConfigArray, getUsedExtractedConfigs } from "./config-array/index.js";
import { ConfigDependency } from "./config-array/config-dependency.js";
import { ExtractedConfig } from "./config-array/extracted-config.js";
import { IgnorePattern } from "./config-array/ignore-pattern.js";
import { OverrideTester } from "./config-array/override-tester.js";
import * as ConfigOps from "./shared/config-ops.js";
import ConfigValidator from "./shared/config-validator.js";
import * as naming from "./shared/naming.js";
import { FlatCompat } from "./flat-compat.js";
import environments from "../conf/environments.js";
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
const Legacy = {
ConfigArray,
createConfigArrayFactoryContext,
CascadingConfigArrayFactory,
ConfigArrayFactory,
ConfigDependency,
ExtractedConfig,
IgnorePattern,
OverrideTester,
getUsedExtractedConfigs,
environments,
loadConfigFile,
// shared
ConfigOps,
ConfigValidator,
ModuleResolver,
naming
};
export {
Legacy,
FlatCompat
};

191
node_modules/@eslint/eslintrc/lib/shared/ajv.js generated vendored Normal file
View File

@ -0,0 +1,191 @@
/**
* @fileoverview The instance of Ajv validator.
* @author Evgeny Poberezkin
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import Ajv from "ajv";
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
/*
* Copied from ajv/lib/refs/json-schema-draft-04.json
* The MIT License (MIT)
* Copyright (c) 2015-2017 Evgeny Poberezkin
*/
const metaSchema = {
id: "http://json-schema.org/draft-04/schema#",
$schema: "http://json-schema.org/draft-04/schema#",
description: "Core schema meta-schema",
definitions: {
schemaArray: {
type: "array",
minItems: 1,
items: { $ref: "#" }
},
positiveInteger: {
type: "integer",
minimum: 0
},
positiveIntegerDefault0: {
allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }]
},
simpleTypes: {
enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
},
stringArray: {
type: "array",
items: { type: "string" },
minItems: 1,
uniqueItems: true
}
},
type: "object",
properties: {
id: {
type: "string"
},
$schema: {
type: "string"
},
title: {
type: "string"
},
description: {
type: "string"
},
default: { },
multipleOf: {
type: "number",
minimum: 0,
exclusiveMinimum: true
},
maximum: {
type: "number"
},
exclusiveMaximum: {
type: "boolean",
default: false
},
minimum: {
type: "number"
},
exclusiveMinimum: {
type: "boolean",
default: false
},
maxLength: { $ref: "#/definitions/positiveInteger" },
minLength: { $ref: "#/definitions/positiveIntegerDefault0" },
pattern: {
type: "string",
format: "regex"
},
additionalItems: {
anyOf: [
{ type: "boolean" },
{ $ref: "#" }
],
default: { }
},
items: {
anyOf: [
{ $ref: "#" },
{ $ref: "#/definitions/schemaArray" }
],
default: { }
},
maxItems: { $ref: "#/definitions/positiveInteger" },
minItems: { $ref: "#/definitions/positiveIntegerDefault0" },
uniqueItems: {
type: "boolean",
default: false
},
maxProperties: { $ref: "#/definitions/positiveInteger" },
minProperties: { $ref: "#/definitions/positiveIntegerDefault0" },
required: { $ref: "#/definitions/stringArray" },
additionalProperties: {
anyOf: [
{ type: "boolean" },
{ $ref: "#" }
],
default: { }
},
definitions: {
type: "object",
additionalProperties: { $ref: "#" },
default: { }
},
properties: {
type: "object",
additionalProperties: { $ref: "#" },
default: { }
},
patternProperties: {
type: "object",
additionalProperties: { $ref: "#" },
default: { }
},
dependencies: {
type: "object",
additionalProperties: {
anyOf: [
{ $ref: "#" },
{ $ref: "#/definitions/stringArray" }
]
}
},
enum: {
type: "array",
minItems: 1,
uniqueItems: true
},
type: {
anyOf: [
{ $ref: "#/definitions/simpleTypes" },
{
type: "array",
items: { $ref: "#/definitions/simpleTypes" },
minItems: 1,
uniqueItems: true
}
]
},
format: { type: "string" },
allOf: { $ref: "#/definitions/schemaArray" },
anyOf: { $ref: "#/definitions/schemaArray" },
oneOf: { $ref: "#/definitions/schemaArray" },
not: { $ref: "#" }
},
dependencies: {
exclusiveMaximum: ["maximum"],
exclusiveMinimum: ["minimum"]
},
default: { }
};
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export default (additionalOptions = {}) => {
const ajv = new Ajv({
meta: false,
useDefaults: true,
validateSchema: false,
missingRefs: "ignore",
verbose: true,
schemaId: "auto",
...additionalOptions
});
ajv.addMetaSchema(metaSchema);
// eslint-disable-next-line no-underscore-dangle -- part of the API
ajv._opts.defaultMeta = metaSchema.id;
return ajv;
};

135
node_modules/@eslint/eslintrc/lib/shared/config-ops.js generated vendored Normal file
View File

@ -0,0 +1,135 @@
/**
* @fileoverview Config file operations. This file must be usable in the browser,
* so no Node-specific code can be here.
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
map[value] = index;
return map;
}, {}),
VALID_SEVERITIES = new Set([0, 1, 2, "off", "warn", "error"]);
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Normalizes the severity value of a rule's configuration to a number
* @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
* received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
* the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
* whose first element is one of the above values. Strings are matched case-insensitively.
* @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
*/
function getRuleSeverity(ruleConfig) {
const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
return severityValue;
}
if (typeof severityValue === "string") {
return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
}
return 0;
}
/**
* Converts old-style severity settings (0, 1, 2) into new-style
* severity settings (off, warn, error) for all rules. Assumption is that severity
* values have already been validated as correct.
* @param {Object} config The config object to normalize.
* @returns {void}
*/
function normalizeToStrings(config) {
if (config.rules) {
Object.keys(config.rules).forEach(ruleId => {
const ruleConfig = config.rules[ruleId];
if (typeof ruleConfig === "number") {
config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
} else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
}
});
}
}
/**
* Determines if the severity for the given rule configuration represents an error.
* @param {int|string|Array} ruleConfig The configuration for an individual rule.
* @returns {boolean} True if the rule represents an error, false if not.
*/
function isErrorSeverity(ruleConfig) {
return getRuleSeverity(ruleConfig) === 2;
}
/**
* Checks whether a given config has valid severity or not.
* @param {number|string|Array} ruleConfig The configuration for an individual rule.
* @returns {boolean} `true` if the configuration has valid severity.
*/
function isValidSeverity(ruleConfig) {
let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
if (typeof severity === "string") {
severity = severity.toLowerCase();
}
return VALID_SEVERITIES.has(severity);
}
/**
* Checks whether every rule of a given config has valid severity or not.
* @param {Object} config The configuration for rules.
* @returns {boolean} `true` if the configuration has valid severity.
*/
function isEverySeverityValid(config) {
return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));
}
/**
* Normalizes a value for a global in a config
* @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
* a global directive comment
* @returns {("readable"|"writeable"|"off")} The value normalized as a string
* @throws Error if global value is invalid
*/
function normalizeConfigGlobal(configuredValue) {
switch (configuredValue) {
case "off":
return "off";
case true:
case "true":
case "writeable":
case "writable":
return "writable";
case null:
case false:
case "false":
case "readable":
case "readonly":
return "readonly";
default:
throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
}
}
export {
getRuleSeverity,
normalizeToStrings,
isErrorSeverity,
isValidSeverity,
isEverySeverityValid,
normalizeConfigGlobal
};

View File

@ -0,0 +1,383 @@
/**
* @fileoverview Validates configs.
* @author Brandon Mills
*/
/* eslint class-methods-use-this: "off" -- not needed in this file */
//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------
/** @typedef {import("../shared/types").Rule} Rule */
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import util from "node:util";
import * as ConfigOps from "./config-ops.js";
import { emitDeprecationWarning } from "./deprecation-warnings.js";
import ajvOrig from "./ajv.js";
import { deepMergeArrays } from "./deep-merge-arrays.js";
import configSchema from "../../conf/config-schema.js";
import BuiltInEnvironments from "../../conf/environments.js";
const ajv = ajvOrig();
const ruleValidators = new WeakMap();
const noop = Function.prototype;
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
let validateSchema;
const severityMap = {
error: 2,
warn: 1,
off: 0
};
const validated = new WeakSet();
// JSON schema that disallows passing any options
const noOptionsSchema = Object.freeze({
type: "array",
minItems: 0,
maxItems: 0
});
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* Validator for configuration objects.
*/
export default class ConfigValidator {
constructor({ builtInRules = new Map() } = {}) {
this.builtInRules = builtInRules;
}
/**
* Gets a complete options schema for a rule.
* @param {Rule} rule A rule object
* @throws {TypeError} If `meta.schema` is specified but is not an array, object or `false`.
* @returns {Object|null} JSON Schema for the rule's options.
* `null` if rule wasn't passed or its `meta.schema` is `false`.
*/
getRuleOptionsSchema(rule) {
if (!rule) {
return null;
}
if (!rule.meta) {
return { ...noOptionsSchema }; // default if `meta.schema` is not specified
}
const schema = rule.meta.schema;
if (typeof schema === "undefined") {
return { ...noOptionsSchema }; // default if `meta.schema` is not specified
}
// `schema:false` is an allowed explicit opt-out of options validation for the rule
if (schema === false) {
return null;
}
if (typeof schema !== "object" || schema === null) {
throw new TypeError("Rule's `meta.schema` must be an array or object");
}
// ESLint-specific array form needs to be converted into a valid JSON Schema definition
if (Array.isArray(schema)) {
if (schema.length) {
return {
type: "array",
items: schema,
minItems: 0,
maxItems: schema.length
};
}
// `schema:[]` is an explicit way to specify that the rule does not accept any options
return { ...noOptionsSchema };
}
// `schema:<object>` is assumed to be a valid JSON Schema definition
return schema;
}
/**
* Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
* @param {options} options The given options for the rule.
* @returns {number|string} The rule's severity value
* @throws {Error} If the severity is invalid.
*/
validateRuleSeverity(options) {
const severity = Array.isArray(options) ? options[0] : options;
const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
return normSeverity;
}
throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
}
/**
* Validates the non-severity options passed to a rule, based on its schema.
* @param {{create: Function}} rule The rule to validate
* @param {Array} localOptions The options for the rule, excluding severity
* @returns {void}
* @throws {Error} If the options are invalid.
*/
validateRuleSchema(rule, localOptions) {
if (!ruleValidators.has(rule)) {
try {
const schema = this.getRuleOptionsSchema(rule);
if (schema) {
ruleValidators.set(rule, ajv.compile(schema));
}
} catch (err) {
const errorWithCode = new Error(err.message, { cause: err });
errorWithCode.code = "ESLINT_INVALID_RULE_OPTIONS_SCHEMA";
throw errorWithCode;
}
}
const validateRule = ruleValidators.get(rule);
if (validateRule) {
const mergedOptions = deepMergeArrays(rule.meta?.defaultOptions, localOptions);
validateRule(mergedOptions);
if (validateRule.errors) {
throw new Error(validateRule.errors.map(
error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
).join(""));
}
}
}
/**
* Validates a rule's options against its schema.
* @param {{create: Function}|null} rule The rule that the config is being validated for
* @param {string} ruleId The rule's unique name.
* @param {Array|number} options The given options for the rule.
* @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
* no source is prepended to the message.
* @returns {void}
* @throws {Error} If the options are invalid.
*/
validateRuleOptions(rule, ruleId, options, source = null) {
try {
const severity = this.validateRuleSeverity(options);
if (severity !== 0) {
this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
}
} catch (err) {
let enhancedMessage = err.code === "ESLINT_INVALID_RULE_OPTIONS_SCHEMA"
? `Error while processing options validation schema of rule '${ruleId}': ${err.message}`
: `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
if (typeof source === "string") {
enhancedMessage = `${source}:\n\t${enhancedMessage}`;
}
const enhancedError = new Error(enhancedMessage, { cause: err });
if (err.code) {
enhancedError.code = err.code;
}
throw enhancedError;
}
}
/**
* Validates an environment object
* @param {Object} environment The environment config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded environments.
* @returns {void}
* @throws {Error} If the environment is invalid.
*/
validateEnvironment(
environment,
source,
getAdditionalEnv = noop
) {
// not having an environment is ok
if (!environment) {
return;
}
Object.keys(environment).forEach(id => {
const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;
if (!env) {
const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
throw new Error(message);
}
});
}
/**
* Validates a rules config object
* @param {Object} rulesConfig The rules config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {(ruleId:string) => Object} getAdditionalRule A map from strings to loaded rules
* @returns {void}
*/
validateRules(
rulesConfig,
source,
getAdditionalRule = noop
) {
if (!rulesConfig) {
return;
}
Object.keys(rulesConfig).forEach(id => {
const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
this.validateRuleOptions(rule, id, rulesConfig[id], source);
});
}
/**
* Validates a `globals` section of a config file
* @param {Object} globalsConfig The `globals` section
* @param {string|null} source The name of the configuration source to report in the event of an error.
* @returns {void}
*/
validateGlobals(globalsConfig, source = null) {
if (!globalsConfig) {
return;
}
Object.entries(globalsConfig)
.forEach(([configuredGlobal, configuredValue]) => {
try {
ConfigOps.normalizeConfigGlobal(configuredValue);
} catch (err) {
throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
}
});
}
/**
* Validate `processor` configuration.
* @param {string|undefined} processorName The processor name.
* @param {string} source The name of config file.
* @param {(id:string) => Processor} getProcessor The getter of defined processors.
* @returns {void}
* @throws {Error} If the processor is invalid.
*/
validateProcessor(processorName, source, getProcessor) {
if (processorName && !getProcessor(processorName)) {
throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
}
}
/**
* Formats an array of schema validation errors.
* @param {Array} errors An array of error messages to format.
* @returns {string} Formatted error message
*/
formatErrors(errors) {
return errors.map(error => {
if (error.keyword === "additionalProperties") {
const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
return `Unexpected top-level property "${formattedPropertyPath}"`;
}
if (error.keyword === "type") {
const formattedField = error.dataPath.slice(1);
const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
const formattedValue = JSON.stringify(error.data);
return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
}
const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
}).map(message => `\t- ${message}.\n`).join("");
}
/**
* Validates the top level properties of the config object.
* @param {Object} config The config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @returns {void}
* @throws {Error} If the config is invalid.
*/
validateConfigSchema(config, source = null) {
validateSchema = validateSchema || ajv.compile(configSchema);
if (!validateSchema(config)) {
throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
}
if (Object.hasOwn(config, "ecmaFeatures")) {
emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
}
}
/**
* Validates an entire config object.
* @param {Object} config The config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {(ruleId:string) => Object} [getAdditionalRule] A map from strings to loaded rules.
* @param {(envId:string) => Object} [getAdditionalEnv] A map from strings to loaded envs.
* @returns {void}
*/
validate(config, source, getAdditionalRule, getAdditionalEnv) {
this.validateConfigSchema(config, source);
this.validateRules(config.rules, source, getAdditionalRule);
this.validateEnvironment(config.env, source, getAdditionalEnv);
this.validateGlobals(config.globals, source);
for (const override of config.overrides || []) {
this.validateRules(override.rules, source, getAdditionalRule);
this.validateEnvironment(override.env, source, getAdditionalEnv);
this.validateGlobals(config.globals, source);
}
}
/**
* Validate config array object.
* @param {ConfigArray} configArray The config array to validate.
* @returns {void}
*/
validateConfigArray(configArray) {
const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
// Validate.
for (const element of configArray) {
if (validated.has(element)) {
continue;
}
validated.add(element);
this.validateEnvironment(element.env, element.name, getPluginEnv);
this.validateGlobals(element.globals, element.name);
this.validateProcessor(element.processor, element.name, getPluginProcessor);
this.validateRules(element.rules, element.name, getPluginRule);
}
}
}

View File

@ -0,0 +1,58 @@
/**
* @fileoverview Applies default rule options
* @author JoshuaKGoldberg
*/
/**
* Check if the variable contains an object strictly rejecting arrays
* @param {unknown} value an object
* @returns {boolean} Whether value is an object
*/
function isObjectNotArray(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/**
* Deeply merges second on top of first, creating a new {} object if needed.
* @param {T} first Base, default value.
* @param {U} second User-specified value.
* @returns {T | U | (T & U)} Merged equivalent of second on top of first.
*/
function deepMergeObjects(first, second) {
if (second === void 0) {
return first;
}
if (!isObjectNotArray(first) || !isObjectNotArray(second)) {
return second;
}
const result = { ...first, ...second };
for (const key of Object.keys(second)) {
if (Object.prototype.propertyIsEnumerable.call(first, key)) {
result[key] = deepMergeObjects(first[key], second[key]);
}
}
return result;
}
/**
* Deeply merges second on top of first, creating a new [] array if needed.
* @param {T[] | undefined} first Base, default values.
* @param {U[] | undefined} second User-specified values.
* @returns {(T | U | (T & U))[]} Merged equivalent of second on top of first.
*/
function deepMergeArrays(first, second) {
if (!first || !second) {
return second || first || [];
}
return [
...first.map((value, i) => deepMergeObjects(value, second[i])),
...second.slice(first.length)
];
}
export { deepMergeArrays };

View File

@ -0,0 +1,63 @@
/**
* @fileoverview Provide the function that emits deprecation warnings.
* @author Toru Nagashima <http://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import path from "node:path";
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
// Defitions for deprecation warnings.
const deprecationWarningMessages = {
ESLINT_LEGACY_ECMAFEATURES:
"The 'ecmaFeatures' config file property is deprecated and has no effect.",
ESLINT_PERSONAL_CONFIG_LOAD:
"'~/.eslintrc.*' config files have been deprecated. " +
"Please use a config file per project or the '--config' option.",
ESLINT_PERSONAL_CONFIG_SUPPRESS:
"'~/.eslintrc.*' config files have been deprecated. " +
"Please remove it or add 'root:true' to the config files in your " +
"projects in order to avoid loading '~/.eslintrc.*' accidentally."
};
const sourceFileErrorCache = new Set();
/**
* Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
* for each unique file path, but repeated invocations with the same file path have no effect.
* No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
* @param {string} source The name of the configuration source to report the warning for.
* @param {string} errorCode The warning message to show.
* @returns {void}
*/
function emitDeprecationWarning(source, errorCode) {
const cacheKey = JSON.stringify({ source, errorCode });
if (sourceFileErrorCache.has(cacheKey)) {
return;
}
sourceFileErrorCache.add(cacheKey);
const rel = path.relative(process.cwd(), source);
const message = deprecationWarningMessages[errorCode];
process.emitWarning(
`${message} (found in "${rel}")`,
"DeprecationWarning",
errorCode
);
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export {
emitDeprecationWarning
};

96
node_modules/@eslint/eslintrc/lib/shared/naming.js generated vendored Normal file
View File

@ -0,0 +1,96 @@
/**
* @fileoverview Common helpers for naming of plugins, formatters and configs
*/
const NAMESPACE_REGEX = /^@.*\//iu;
/**
* Brings package name to correct format based on prefix
* @param {string} name The name of the package.
* @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
* @returns {string} Normalized name of the package
* @private
*/
function normalizePackageName(name, prefix) {
let normalizedName = name;
/**
* On Windows, name can come in with Windows slashes instead of Unix slashes.
* Normalize to Unix first to avoid errors later on.
* https://github.com/eslint/eslint/issues/5644
*/
if (normalizedName.includes("\\")) {
normalizedName = normalizedName.replace(/\\/gu, "/");
}
if (normalizedName.charAt(0) === "@") {
/**
* it's a scoped package
* package name is the prefix, or just a username
*/
const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"),
scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u");
if (scopedPackageShortcutRegex.test(normalizedName)) {
normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);
} else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
/**
* for scoped packages, insert the prefix after the first / unless
* the path is already @scope/eslint or @scope/eslint-xxx-yyy
*/
normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`);
}
} else if (!normalizedName.startsWith(`${prefix}-`)) {
normalizedName = `${prefix}-${normalizedName}`;
}
return normalizedName;
}
/**
* Removes the prefix from a fullname.
* @param {string} fullname The term which may have the prefix.
* @param {string} prefix The prefix to remove.
* @returns {string} The term without prefix.
*/
function getShorthandName(fullname, prefix) {
if (fullname[0] === "@") {
let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
if (matchResult) {
return matchResult[1];
}
matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
if (matchResult) {
return `${matchResult[1]}/${matchResult[2]}`;
}
} else if (fullname.startsWith(`${prefix}-`)) {
return fullname.slice(prefix.length + 1);
}
return fullname;
}
/**
* Gets the scope (namespace) of a term.
* @param {string} term The term which may have the namespace.
* @returns {string} The namespace of the term if it has one.
*/
function getNamespaceFromTerm(term) {
const match = term.match(NAMESPACE_REGEX);
return match ? match[0] : "";
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export {
normalizePackageName,
getShorthandName,
getNamespaceFromTerm
};

View File

@ -0,0 +1,43 @@
/**
* Utility for resolving a module relative to another module
* @author Teddy Katz
*/
import Module from "node:module";
/*
* `Module.createRequire` is added in v12.2.0. It supports URL as well.
* We only support the case where the argument is a filepath, not a URL.
*/
const createRequire = Module.createRequire;
/**
* Resolves a Node module relative to another module
* @param {string} moduleName The name of a Node module, or a path to a Node module.
* @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
* a file rather than a directory, but the file need not actually exist.
* @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
* @throws {Error} When the module cannot be resolved.
*/
function resolve(moduleName, relativeToPath) {
try {
return createRequire(relativeToPath).resolve(moduleName);
} catch (error) {
// This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
if (
typeof error === "object" &&
error !== null &&
error.code === "MODULE_NOT_FOUND" &&
!error.requireStack &&
error.message.includes(moduleName)
) {
error.message += `\nRequire stack:\n- ${relativeToPath}`;
}
throw error;
}
}
export {
resolve
};

149
node_modules/@eslint/eslintrc/lib/shared/types.js generated vendored Normal file
View File

@ -0,0 +1,149 @@
/**
* @fileoverview Define common types for input completion.
* @author Toru Nagashima <https://github.com/mysticatea>
*/
/** @type {any} */
export default {};
/** @typedef {boolean | "off" | "readable" | "readonly" | "writable" | "writeable"} GlobalConf */
/** @typedef {0 | 1 | 2 | "off" | "warn" | "error"} SeverityConf */
/** @typedef {SeverityConf | [SeverityConf, ...any[]]} RuleConf */
/**
* @typedef {Object} EcmaFeatures
* @property {boolean} [globalReturn] Enabling `return` statements at the top-level.
* @property {boolean} [jsx] Enabling JSX syntax.
* @property {boolean} [impliedStrict] Enabling strict mode always.
*/
/**
* @typedef {Object} ParserOptions
* @property {EcmaFeatures} [ecmaFeatures] The optional features.
* @property {3|5|6|7|8|9|10|11|12|2015|2016|2017|2018|2019|2020|2021} [ecmaVersion] The ECMAScript version (or revision number).
* @property {"script"|"module"} [sourceType] The source code type.
*/
/**
* @typedef {Object} ConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {string | string[]} [ignorePatterns] The glob patterns that ignore to lint.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {boolean} [root] The root flag.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} OverrideConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [excludedFiles] The glob pattarns for excluded files.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {string | string[]} files The glob patterns for target files.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} ParseResult
* @property {Object} ast The AST.
* @property {ScopeManager} [scopeManager] The scope manager of the AST.
* @property {Record<string, any>} [services] The services that the parser provides.
* @property {Record<string, string[]>} [visitorKeys] The visitor keys of the AST.
*/
/**
* @typedef {Object} Parser
* @property {(text:string, options:ParserOptions) => Object} parse The definition of global variables.
* @property {(text:string, options:ParserOptions) => ParseResult} [parseForESLint] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} Environment
* @property {Record<string, GlobalConf>} [globals] The definition of global variables.
* @property {ParserOptions} [parserOptions] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} LintMessage
* @property {number} column The 1-based column number.
* @property {number} [endColumn] The 1-based column number of the end location.
* @property {number} [endLine] The 1-based line number of the end location.
* @property {boolean} fatal If `true` then this is a fatal error.
* @property {{range:[number,number], text:string}} [fix] Information for autofix.
* @property {number} line The 1-based line number.
* @property {string} message The error message.
* @property {string|null} ruleId The ID of the rule which makes this message.
* @property {0|1|2} severity The severity of this message.
* @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions.
*/
/**
* @typedef {Object} SuggestionResult
* @property {string} desc A short description.
* @property {string} [messageId] Id referencing a message for the description.
* @property {{ text: string, range: number[] }} fix fix result info
*/
/**
* @typedef {Object} Processor
* @property {(text:string, filename:string) => Array<string | { text:string, filename:string }>} [preprocess] The function to extract code blocks.
* @property {(messagesList:LintMessage[][], filename:string) => LintMessage[]} [postprocess] The function to merge messages.
* @property {boolean} [supportsAutofix] If `true` then it means the processor supports autofix.
*/
/**
* @typedef {Object} RuleMetaDocs
* @property {string} category The category of the rule.
* @property {string} description The description of the rule.
* @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset.
* @property {string} url The URL of the rule documentation.
*/
/**
* @typedef {Object} RuleMeta
* @property {boolean} [deprecated] If `true` then the rule has been deprecated.
* @property {RuleMetaDocs} docs The document information of the rule.
* @property {"code"|"whitespace"} [fixable] The autofix type.
* @property {Record<string,string>} [messages] The messages the rule reports.
* @property {string[]} [replacedBy] The IDs of the alternative rules.
* @property {Array|Object} schema The option schema of the rule.
* @property {"problem"|"suggestion"|"layout"} type The rule type.
*/
/**
* @typedef {Object} Rule
* @property {Function} create The factory of the rule.
* @property {RuleMeta} meta The meta data of the rule.
*/
/**
* @typedef {Object} Plugin
* @property {Record<string, ConfigData>} [configs] The definition of plugin configs.
* @property {Record<string, Environment>} [environments] The definition of plugin environments.
* @property {Record<string, Processor>} [processors] The definition of plugin processors.
* @property {Record<string, Function | Rule>} [rules] The definition of plugin rules.
*/
/**
* Information of deprecated rules.
* @typedef {Object} DeprecatedRuleInfo
* @property {string} ruleId The rule ID.
* @property {string[]} replacedBy The rule IDs that replace this deprecated rule.
*/

76
node_modules/@eslint/eslintrc/lib/types/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,76 @@
/**
* @fileoverview This file contains the core types for ESLint. It was initially extracted
* from the `@types/eslint__eslintrc` package.
*/
/*
* MIT License
* Copyright (c) Microsoft Corporation.
*
* 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
*/
import type { Linter } from "eslint";
/**
* A compatibility class for working with configs.
*/
export class FlatCompat {
constructor({
baseDirectory,
resolvePluginsRelativeTo,
recommendedConfig,
allConfig,
}?: {
/**
* default: process.cwd()
*/
baseDirectory?: string;
resolvePluginsRelativeTo?: string;
recommendedConfig?: Linter.LegacyConfig;
allConfig?: Linter.LegacyConfig;
});
/**
* Translates an ESLintRC-style config into a flag-config-style config.
* @param eslintrcConfig The ESLintRC-style config object.
* @returns A flag-config-style config object.
*/
config(eslintrcConfig: Linter.LegacyConfig): Linter.Config[];
/**
* Translates the `env` section of an ESLintRC-style config.
* @param envConfig The `env` section of an ESLintRC config.
* @returns An array of flag-config objects representing the environments.
*/
env(envConfig: { [name: string]: boolean }): Linter.Config[];
/**
* Translates the `extends` section of an ESLintRC-style config.
* @param configsToExtend The names of the configs to load.
* @returns An array of flag-config objects representing the config.
*/
extends(...configsToExtend: string[]): Linter.Config[];
/**
* Translates the `plugins` section of an ESLintRC-style config.
* @param plugins The names of the plugins to load.
* @returns An array of flag-config objects representing the plugins.
*/
plugins(...plugins: string[]): Linter.Config[];
}

84
node_modules/@eslint/eslintrc/package.json generated vendored Normal file
View File

@ -0,0 +1,84 @@
{
"name": "@eslint/eslintrc",
"version": "3.3.1",
"description": "The legacy ESLintRC config file format for ESLint",
"type": "module",
"main": "./dist/eslintrc.cjs",
"types": "./dist/eslintrc.d.cts",
"exports": {
".": {
"import": "./lib/index.js",
"require": "./dist/eslintrc.cjs",
"types": "./lib/types/index.d.ts"
},
"./package.json": "./package.json",
"./universal": {
"import": "./lib/index-universal.js",
"require": "./dist/eslintrc-universal.cjs"
}
},
"files": [
"lib",
"conf",
"LICENSE",
"dist",
"universal.js"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rollup -c && node -e \"fs.copyFileSync('./lib/types/index.d.ts', './dist/eslintrc.d.cts')\"",
"lint": "eslint . --report-unused-disable-directives",
"lint:fix": "npm run lint -- --fix",
"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 -R progress -c 'tests/lib/*.cjs' && c8 mocha -R progress -c 'tests/lib/**/*.js'",
"test:types": "tsc -p tests/lib/types/tsconfig.json"
},
"repository": "eslint/eslintrc",
"funding": "https://opencollective.com/eslint",
"keywords": [
"ESLint",
"ESLintRC",
"Configuration"
],
"author": "Nicholas C. Zakas",
"license": "MIT",
"bugs": {
"url": "https://github.com/eslint/eslintrc/issues"
},
"homepage": "https://github.com/eslint/eslintrc#readme",
"devDependencies": {
"c8": "^7.7.3",
"chai": "^4.3.4",
"eslint": "^9.20.1",
"eslint-config-eslint": "^11.0.0",
"eslint-release": "^3.2.0",
"fs-teardown": "^0.1.3",
"mocha": "^9.0.3",
"rollup": "^2.70.1",
"shelljs": "^0.8.5",
"sinon": "^11.1.2",
"temp-dir": "^2.0.0",
"typescript": "^5.7.3"
},
"dependencies": {
"ajv": "^6.12.4",
"debug": "^4.3.2",
"espree": "^10.0.1",
"globals": "^14.0.0",
"ignore": "^5.2.0",
"import-fresh": "^3.2.1",
"js-yaml": "^4.1.0",
"minimatch": "^3.1.2",
"strip-json-comments": "^3.1.1"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
}

10
node_modules/@eslint/eslintrc/universal.js generated vendored Normal file
View File

@ -0,0 +1,10 @@
/* global module, require -- required for CJS file */
// Jest (and probably some other runtimes with custom implementations of
// `require`) doesn't support `exports` in `package.json`, so this file is here
// to help them load this module. Note that it is also `.js` and not `.cjs` for
// the same reason - `cjs` files requires to be loaded with an extension, but
// since Jest doesn't respect `module` outside of ESM mode it still works in
// this case (and the `require` in _this_ file does specify the extension).
module.exports = require("./dist/eslintrc-universal.cjs");

19
node_modules/@eslint/js/LICENSE generated vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright OpenJS Foundation and other contributors, <www.openjsf.org>
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.

69
node_modules/@eslint/js/README.md generated vendored Normal file
View File

@ -0,0 +1,69 @@
[![npm version](https://img.shields.io/npm/v/@eslint/js.svg)](https://www.npmjs.com/package/@eslint/js)
# ESLint JavaScript Plugin
[Website](https://eslint.org) | [Configure ESLint](https://eslint.org/docs/latest/use/configure) | [Rules](https://eslint.org/docs/rules/) | [Contributing](https://eslint.org/docs/latest/contribute) | [Twitter](https://twitter.com/geteslint) | [Chatroom](https://eslint.org/chat)
The beginnings of separating out JavaScript-specific functionality from ESLint.
Right now, this plugin contains two configurations:
- `recommended` - enables the rules recommended by the ESLint team (the replacement for `"eslint:recommended"`)
- `all` - enables all ESLint rules (the replacement for `"eslint:all"`)
## Installation
```shell
npm install @eslint/js -D
```
## Usage
Use in your `eslint.config.js` file anytime you want to extend one of the configs:
```js
import { defineConfig } from "eslint/config";
import js from "@eslint/js";
export default defineConfig([
// apply recommended rules to JS files
{
name: "your-project/recommended-rules",
files: ["**/*.js"],
plugins: {
js,
},
extends: ["js/recommended"],
},
// apply recommended rules to JS files with an override
{
name: "your-project/recommended-rules-with-override",
files: ["**/*.js"],
plugins: {
js,
},
extends: ["js/recommended"],
rules: {
"no-unused-vars": "warn",
},
},
// apply all rules to JS files
{
name: "your-project/all-rules",
files: ["**/*.js"],
plugins: {
js,
},
extends: ["js/all"],
rules: {
"no-unused-vars": "warn",
},
},
]);
```
## License
MIT

35
node_modules/@eslint/js/package.json generated vendored Normal file
View File

@ -0,0 +1,35 @@
{
"name": "@eslint/js",
"version": "9.26.0",
"description": "ESLint JavaScript language implementation",
"main": "./src/index.js",
"types": "./types/index.d.ts",
"scripts": {
"test:types": "tsc -p tests/types/tsconfig.json"
},
"files": [
"LICENSE",
"README.md",
"src",
"types"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/eslint/eslint.git",
"directory": "packages/js"
},
"homepage": "https://eslint.org",
"bugs": "https://github.com/eslint/eslint/issues/",
"keywords": [
"javascript",
"eslint-plugin",
"eslint"
],
"license": "MIT",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
}

215
node_modules/@eslint/js/src/configs/eslint-all.js generated vendored Normal file
View File

@ -0,0 +1,215 @@
/*
* WARNING: This file is autogenerated using the tools/update-eslint-all.js
* script. Do not edit manually.
*/
"use strict";
/*
* IMPORTANT!
*
* We cannot add a "name" property to this object because it's still used in eslintrc
* which doesn't support the "name" property. If we add a "name" property, it will
* cause an error.
*/
module.exports = Object.freeze({
"rules": {
"accessor-pairs": "error",
"array-callback-return": "error",
"arrow-body-style": "error",
"block-scoped-var": "error",
"camelcase": "error",
"capitalized-comments": "error",
"class-methods-use-this": "error",
"complexity": "error",
"consistent-return": "error",
"consistent-this": "error",
"constructor-super": "error",
"curly": "error",
"default-case": "error",
"default-case-last": "error",
"default-param-last": "error",
"dot-notation": "error",
"eqeqeq": "error",
"for-direction": "error",
"func-name-matching": "error",
"func-names": "error",
"func-style": "error",
"getter-return": "error",
"grouped-accessor-pairs": "error",
"guard-for-in": "error",
"id-denylist": "error",
"id-length": "error",
"id-match": "error",
"init-declarations": "error",
"logical-assignment-operators": "error",
"max-classes-per-file": "error",
"max-depth": "error",
"max-lines": "error",
"max-lines-per-function": "error",
"max-nested-callbacks": "error",
"max-params": "error",
"max-statements": "error",
"new-cap": "error",
"no-alert": "error",
"no-array-constructor": "error",
"no-async-promise-executor": "error",
"no-await-in-loop": "error",
"no-bitwise": "error",
"no-caller": "error",
"no-case-declarations": "error",
"no-class-assign": "error",
"no-compare-neg-zero": "error",
"no-cond-assign": "error",
"no-console": "error",
"no-const-assign": "error",
"no-constant-binary-expression": "error",
"no-constant-condition": "error",
"no-constructor-return": "error",
"no-continue": "error",
"no-control-regex": "error",
"no-debugger": "error",
"no-delete-var": "error",
"no-div-regex": "error",
"no-dupe-args": "error",
"no-dupe-class-members": "error",
"no-dupe-else-if": "error",
"no-dupe-keys": "error",
"no-duplicate-case": "error",
"no-duplicate-imports": "error",
"no-else-return": "error",
"no-empty": "error",
"no-empty-character-class": "error",
"no-empty-function": "error",
"no-empty-pattern": "error",
"no-empty-static-block": "error",
"no-eq-null": "error",
"no-eval": "error",
"no-ex-assign": "error",
"no-extend-native": "error",
"no-extra-bind": "error",
"no-extra-boolean-cast": "error",
"no-extra-label": "error",
"no-fallthrough": "error",
"no-func-assign": "error",
"no-global-assign": "error",
"no-implicit-coercion": "error",
"no-implicit-globals": "error",
"no-implied-eval": "error",
"no-import-assign": "error",
"no-inline-comments": "error",
"no-inner-declarations": "error",
"no-invalid-regexp": "error",
"no-invalid-this": "error",
"no-irregular-whitespace": "error",
"no-iterator": "error",
"no-label-var": "error",
"no-labels": "error",
"no-lone-blocks": "error",
"no-lonely-if": "error",
"no-loop-func": "error",
"no-loss-of-precision": "error",
"no-magic-numbers": "error",
"no-misleading-character-class": "error",
"no-multi-assign": "error",
"no-multi-str": "error",
"no-negated-condition": "error",
"no-nested-ternary": "error",
"no-new": "error",
"no-new-func": "error",
"no-new-native-nonconstructor": "error",
"no-new-wrappers": "error",
"no-nonoctal-decimal-escape": "error",
"no-obj-calls": "error",
"no-object-constructor": "error",
"no-octal": "error",
"no-octal-escape": "error",
"no-param-reassign": "error",
"no-plusplus": "error",
"no-promise-executor-return": "error",
"no-proto": "error",
"no-prototype-builtins": "error",
"no-redeclare": "error",
"no-regex-spaces": "error",
"no-restricted-exports": "error",
"no-restricted-globals": "error",
"no-restricted-imports": "error",
"no-restricted-properties": "error",
"no-restricted-syntax": "error",
"no-return-assign": "error",
"no-script-url": "error",
"no-self-assign": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-setter-return": "error",
"no-shadow": "error",
"no-shadow-restricted-names": "error",
"no-sparse-arrays": "error",
"no-template-curly-in-string": "error",
"no-ternary": "error",
"no-this-before-super": "error",
"no-throw-literal": "error",
"no-undef": "error",
"no-undef-init": "error",
"no-undefined": "error",
"no-underscore-dangle": "error",
"no-unexpected-multiline": "error",
"no-unmodified-loop-condition": "error",
"no-unneeded-ternary": "error",
"no-unreachable": "error",
"no-unreachable-loop": "error",
"no-unsafe-finally": "error",
"no-unsafe-negation": "error",
"no-unsafe-optional-chaining": "error",
"no-unused-expressions": "error",
"no-unused-labels": "error",
"no-unused-private-class-members": "error",
"no-unused-vars": "error",
"no-use-before-define": "error",
"no-useless-assignment": "error",
"no-useless-backreference": "error",
"no-useless-call": "error",
"no-useless-catch": "error",
"no-useless-computed-key": "error",
"no-useless-concat": "error",
"no-useless-constructor": "error",
"no-useless-escape": "error",
"no-useless-rename": "error",
"no-useless-return": "error",
"no-var": "error",
"no-void": "error",
"no-warning-comments": "error",
"no-with": "error",
"object-shorthand": "error",
"one-var": "error",
"operator-assignment": "error",
"prefer-arrow-callback": "error",
"prefer-const": "error",
"prefer-destructuring": "error",
"prefer-exponentiation-operator": "error",
"prefer-named-capture-group": "error",
"prefer-numeric-literals": "error",
"prefer-object-has-own": "error",
"prefer-object-spread": "error",
"prefer-promise-reject-errors": "error",
"prefer-regex-literals": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"prefer-template": "error",
"radix": "error",
"require-atomic-updates": "error",
"require-await": "error",
"require-unicode-regexp": "error",
"require-yield": "error",
"sort-imports": "error",
"sort-keys": "error",
"sort-vars": "error",
"strict": "error",
"symbol-description": "error",
"unicode-bom": "error",
"use-isnan": "error",
"valid-typeof": "error",
"vars-on-top": "error",
"yoda": "error"
}
});

View File

@ -0,0 +1,83 @@
/**
* @fileoverview Configuration applied when a user configuration extends from
* eslint:recommended.
* @author Nicholas C. Zakas
*/
"use strict";
/* eslint sort-keys: ["error", "asc"] -- Long, so make more readable */
/*
* IMPORTANT!
*
* We cannot add a "name" property to this object because it's still used in eslintrc
* which doesn't support the "name" property. If we add a "name" property, it will
* cause an error.
*/
module.exports = Object.freeze({
rules: Object.freeze({
"constructor-super": "error",
"for-direction": "error",
"getter-return": "error",
"no-async-promise-executor": "error",
"no-case-declarations": "error",
"no-class-assign": "error",
"no-compare-neg-zero": "error",
"no-cond-assign": "error",
"no-const-assign": "error",
"no-constant-binary-expression": "error",
"no-constant-condition": "error",
"no-control-regex": "error",
"no-debugger": "error",
"no-delete-var": "error",
"no-dupe-args": "error",
"no-dupe-class-members": "error",
"no-dupe-else-if": "error",
"no-dupe-keys": "error",
"no-duplicate-case": "error",
"no-empty": "error",
"no-empty-character-class": "error",
"no-empty-pattern": "error",
"no-empty-static-block": "error",
"no-ex-assign": "error",
"no-extra-boolean-cast": "error",
"no-fallthrough": "error",
"no-func-assign": "error",
"no-global-assign": "error",
"no-import-assign": "error",
"no-invalid-regexp": "error",
"no-irregular-whitespace": "error",
"no-loss-of-precision": "error",
"no-misleading-character-class": "error",
"no-new-native-nonconstructor": "error",
"no-nonoctal-decimal-escape": "error",
"no-obj-calls": "error",
"no-octal": "error",
"no-prototype-builtins": "error",
"no-redeclare": "error",
"no-regex-spaces": "error",
"no-self-assign": "error",
"no-setter-return": "error",
"no-shadow-restricted-names": "error",
"no-sparse-arrays": "error",
"no-this-before-super": "error",
"no-undef": "error",
"no-unexpected-multiline": "error",
"no-unreachable": "error",
"no-unsafe-finally": "error",
"no-unsafe-negation": "error",
"no-unsafe-optional-chaining": "error",
"no-unused-labels": "error",
"no-unused-private-class-members": "error",
"no-unused-vars": "error",
"no-useless-backreference": "error",
"no-useless-catch": "error",
"no-useless-escape": "error",
"no-with": "error",
"require-yield": "error",
"use-isnan": "error",
"valid-typeof": "error",
}),
});

23
node_modules/@eslint/js/src/index.js generated vendored Normal file
View File

@ -0,0 +1,23 @@
/**
* @fileoverview Main package entrypoint.
* @author Nicholas C. Zakas
*/
"use strict";
const { name, version } = require("../package.json");
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
meta: {
name,
version,
},
configs: {
all: require("./configs/eslint-all"),
recommended: require("./configs/eslint-recommended"),
},
};

14
node_modules/@eslint/js/types/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,14 @@
import type { Linter } from "eslint";
declare const js: {
readonly meta: {
readonly name: string;
readonly version: string;
};
readonly configs: {
readonly recommended: { readonly rules: Readonly<Linter.RulesRecord> };
readonly all: { readonly rules: Readonly<Linter.RulesRecord> };
};
};
export = js;

201
node_modules/@eslint/object-schema/LICENSE generated vendored Normal file
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 [yyyy] [name of copyright owner]
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.

242
node_modules/@eslint/object-schema/README.md generated vendored Normal file
View File

@ -0,0 +1,242 @@
# ObjectSchema Package
## Overview
A JavaScript object merge/validation utility where you can define a different merge and validation strategy for each key. This is helpful when you need to validate complex data structures and then merge them in a way that is more complex than `Object.assign()`. This is used in the [`@eslint/config-array`](https://npmjs.com/package/@eslint/config-array) package but can also be used on its own.
## Installation
For Node.js and compatible runtimes:
```shell
npm install @eslint/object-schema
# or
yarn add @eslint/object-schema
# or
pnpm install @eslint/object-schema
# or
bun install @eslint/object-schema
```
For Deno:
```shell
deno add @eslint/object-schema
```
## Usage
Import the `ObjectSchema` constructor:
```js
// using ESM
import { ObjectSchema } from "@eslint/object-schema";
// using CommonJS
const { ObjectSchema } = require("@eslint/object-schema");
const schema = new ObjectSchema({
// define a definition for the "downloads" key
downloads: {
required: true,
merge(value1, value2) {
return value1 + value2;
},
validate(value) {
if (typeof value !== "number") {
throw new Error("Expected downloads to be a number.");
}
},
},
// define a strategy for the "versions" key
version: {
required: true,
merge(value1, value2) {
return value1.concat(value2);
},
validate(value) {
if (!Array.isArray(value)) {
throw new Error("Expected versions to be an array.");
}
},
},
});
const record1 = {
downloads: 25,
versions: ["v1.0.0", "v1.1.0", "v1.2.0"],
};
const record2 = {
downloads: 125,
versions: ["v2.0.0", "v2.1.0", "v3.0.0"],
};
// make sure the records are valid
schema.validate(record1);
schema.validate(record2);
// merge together (schema.merge() accepts any number of objects)
const result = schema.merge(record1, record2);
// result looks like this:
const result = {
downloads: 75,
versions: ["v1.0.0", "v1.1.0", "v1.2.0", "v2.0.0", "v2.1.0", "v3.0.0"],
};
```
## Tips and Tricks
### Named merge strategies
Instead of specifying a `merge()` method, you can specify one of the following strings to use a default merge strategy:
- `"assign"` - use `Object.assign()` to merge the two values into one object.
- `"overwrite"` - the second value always replaces the first.
- `"replace"` - the second value replaces the first if the second is not `undefined`.
For example:
```js
const schema = new ObjectSchema({
name: {
merge: "replace",
validate() {},
},
});
```
### Named validation strategies
Instead of specifying a `validate()` method, you can specify one of the following strings to use a default validation strategy:
- `"array"` - value must be an array.
- `"boolean"` - value must be a boolean.
- `"number"` - value must be a number.
- `"object"` - value must be an object.
- `"object?"` - value must be an object or null.
- `"string"` - value must be a string.
- `"string!"` - value must be a non-empty string.
For example:
```js
const schema = new ObjectSchema({
name: {
merge: "replace",
validate: "string",
},
});
```
### Subschemas
If you are defining a key that is, itself, an object, you can simplify the process by using a subschema. Instead of defining `merge()` and `validate()`, assign a `schema` key that contains a schema definition, like this:
```js
const schema = new ObjectSchema({
name: {
schema: {
first: {
merge: "replace",
validate: "string",
},
last: {
merge: "replace",
validate: "string",
},
},
},
});
schema.validate({
name: {
first: "n",
last: "z",
},
});
```
### Remove Keys During Merge
If the merge strategy for a key returns `undefined`, then the key will not appear in the final object. For example:
```js
const schema = new ObjectSchema({
date: {
merge() {
return undefined;
},
validate(value) {
Date.parse(value); // throws an error when invalid
},
},
});
const object1 = { date: "5/5/2005" };
const object2 = { date: "6/6/2006" };
const result = schema.merge(object1, object2);
console.log("date" in result); // false
```
### Requiring Another Key Be Present
If you'd like the presence of one key to require the presence of another key, you can use the `requires` property to specify an array of other properties that any key requires. For example:
```js
const schema = new ObjectSchema();
const schema = new ObjectSchema({
date: {
merge() {
return undefined;
},
validate(value) {
Date.parse(value); // throws an error when invalid
},
},
time: {
requires: ["date"],
merge(first, second) {
return second;
},
validate(value) {
// ...
},
},
});
// throws error: Key "time" requires keys "date"
schema.validate({
time: "13:45",
});
```
In this example, even though `date` is an optional key, it is required to be present whenever `time` is present.
## License
Apache 2.0
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a> <a href="https://trunk.io/"><img src="https://images.opencollective.com/trunkio/fb92d60/avatar.png" alt="trunk.io" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://www.serptriumph.com/"><img src="https://images.opencollective.com/serp-triumph5/fea3074/logo.png" alt="SERP Triumph" height="64"></a> <a href="https://www.jetbrains.com/"><img src="https://images.opencollective.com/jetbrains/fe76f99/logo.png" alt="JetBrains" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://americanexpress.io"><img src="https://avatars.githubusercontent.com/u/3853301" alt="American Express" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://nolebase.ayaka.io"><img src="https://avatars.githubusercontent.com/u/11081491" alt="Neko" height="32"></a> <a href="https://nx.dev"><img src="https://avatars.githubusercontent.com/u/23692104" alt="Nx" height="32"></a> <a href="https://opensource.mercedes-benz.com/"><img src="https://avatars.githubusercontent.com/u/34240465" alt="Mercedes-Benz Group" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->

60
node_modules/@eslint/object-schema/package.json generated vendored Normal file
View File

@ -0,0 +1,60 @@
{
"name": "@eslint/object-schema",
"version": "2.1.6",
"description": "An object schema merger/validator",
"type": "module",
"main": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
"exports": {
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
},
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
}
},
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"directories": {
"test": "tests"
},
"scripts": {
"build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts",
"build": "rollup -c && tsc -p tsconfig.esm.json && npm run build:cts",
"test:jsr": "npx jsr@latest publish --dry-run",
"test": "mocha tests/",
"test:coverage": "c8 npm test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/eslint/rewrite.git"
},
"keywords": [
"object",
"validation",
"schema",
"merge"
],
"author": "Nicholas C. Zakas",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/eslint/rewrite/issues"
},
"homepage": "https://github.com/eslint/rewrite#readme",
"devDependencies": {
"c8": "^9.1.0",
"mocha": "^10.4.0",
"rollup": "^4.16.2",
"rollup-plugin-copy": "^3.5.0",
"typescript": "^5.4.5"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
}

201
node_modules/@eslint/plugin-kit/LICENSE generated vendored Normal file
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 [yyyy] [name of copyright owner]
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.

273
node_modules/@eslint/plugin-kit/README.md generated vendored Normal file
View File

@ -0,0 +1,273 @@
# ESLint Plugin Kit
## Description
A collection of utilities to help build ESLint plugins.
## Installation
For Node.js and compatible runtimes:
```shell
npm install @eslint/plugin-kit
# or
yarn add @eslint/plugin-kit
# or
pnpm install @eslint/plugin-kit
# or
bun install @eslint/plugin-kit
```
For Deno:
```shell
deno add @eslint/plugin-kit
```
## Usage
This package exports the following utilities:
- `ConfigCommentParser` - used to parse ESLint configuration comments (i.e., `/* eslint-disable rule */`)
- `VisitNodeStep` and `CallMethodStep` - used to help implement `SourceCode#traverse()`
- `Directive` - used to help implement `SourceCode#getDisableDirectives()`
- `TextSourceCodeBase` - base class to help implement the `SourceCode` interface
### `ConfigCommentParser`
To use the `ConfigCommentParser` class, import it from the package and create a new instance, such as:
```js
import { ConfigCommentParser } from "@eslint/plugin-kit";
// create a new instance
const commentParser = new ConfigCommentParser();
// pass in a comment string without the comment delimiters
const directive = commentParser.parseDirective(
"eslint-disable prefer-const, semi -- I don't want to use these.",
);
// will be undefined when a directive can't be parsed
if (directive) {
console.log(directive.label); // "eslint-disable"
console.log(directive.value); // "prefer-const, semi"
console.log(directive.justification); // "I don't want to use these"
}
```
There are different styles of directive values that you'll need to parse separately to get the correct format:
```js
import { ConfigCommentParser } from "@eslint/plugin-kit";
// create a new instance
const commentParser = new ConfigCommentParser();
// list format
const list = commentParser.parseListConfig("prefer-const, semi");
console.log(Object.entries(list)); // [["prefer-const", true], ["semi", true]]
// string format
const strings = commentParser.parseStringConfig("foo:off, bar");
console.log(Object.entries(strings)); // [["foo", "off"], ["bar", null]]
// JSON-like config format
const jsonLike = commentParser.parseJSONLikeConfig(
"semi:[error, never], prefer-const: warn",
);
console.log(Object.entries(jsonLike.config)); // [["semi", ["error", "never"]], ["prefer-const", "warn"]]
```
### `VisitNodeStep` and `CallMethodStep`
The `VisitNodeStep` and `CallMethodStep` classes represent steps in the traversal of source code. They implement the correct interfaces to return from the `SourceCode#traverse()` method.
The `VisitNodeStep` class is the more common of the two, where you are describing a visit to a particular node during the traversal. The constructor accepts three arguments:
- `target` - the node being visited. This is used to determine the method to call inside of a rule. For instance, if the node's type is `Literal` then ESLint will call a method named `Literal()` on the rule (if present).
- `phase` - either 1 for enter or 2 for exit.
- `args` - an array of arguments to pass into the visitor method of a rule.
For example:
```js
import { VisitNodeStep } from "@eslint/plugin-kit";
class MySourceCode {
traverse() {
const steps = [];
for (const { node, parent, phase } of iterator(this.ast)) {
steps.push(
new VisitNodeStep({
target: node,
phase: phase === "enter" ? 1 : 2,
args: [node, parent],
}),
);
}
return steps;
}
}
```
The `CallMethodStep` class is less common and is used to tell ESLint to call a specific method on the rule. The constructor accepts two arguments:
- `target` - the name of the method to call, frequently beginning with `"on"` such as `"onCodePathStart"`.
- `args` - an array of arguments to pass to the method.
For example:
```js
import { VisitNodeStep, CallMethodStep } from "@eslint/plugin-kit";
class MySourceCode {
traverse() {
const steps = [];
for (const { node, parent, phase } of iterator(this.ast)) {
steps.push(
new VisitNodeStep({
target: node,
phase: phase === "enter" ? 1 : 2,
args: [node, parent],
}),
);
// call a method indicating how many times we've been through the loop
steps.push(
new CallMethodStep({
target: "onIteration",
args: [steps.length]
});
)
}
return steps;
}
}
```
### `Directive`
The `Directive` class represents a disable directive in the source code and implements the `Directive` interface from `@eslint/core`. You can tell ESLint about disable directives using the `SourceCode#getDisableDirectives()` method, where part of the return value is an array of `Directive` objects. Here's an example:
```js
import { Directive, ConfigCommentParser } from "@eslint/plugin-kit";
class MySourceCode {
getDisableDirectives() {
const directives = [];
const problems = [];
const commentParser = new ConfigCommentParser();
// read in the inline config nodes to check each one
this.getInlineConfigNodes().forEach(comment => {
// Step 1: Parse the directive
const { label, value, justification } =
commentParser.parseDirective(comment.value);
// Step 2: Extract the directive value and create the `Directive` object
switch (label) {
case "eslint-disable":
case "eslint-enable":
case "eslint-disable-next-line":
case "eslint-disable-line": {
const directiveType = label.slice("eslint-".length);
directives.push(
new Directive({
type: directiveType,
node: comment,
value,
justification,
}),
);
}
// ignore any comments that don't begin with known labels
}
});
return {
directives,
problems,
};
}
}
```
### `TextSourceCodeBase`
The `TextSourceCodeBase` class is intended to be a base class that has several of the common members found in `SourceCode` objects already implemented. Those members are:
- `lines` - an array of text lines that is created automatically when the constructor is called.
- `getLoc(node)` - gets the location of a node. Works for nodes that have the ESLint-style `loc` property and nodes that have the Unist-style [`position` property](https://github.com/syntax-tree/unist?tab=readme-ov-file#position). If you're using an AST with a different location format, you'll still need to implement this method yourself.
- `getRange(node)` - gets the range of a node within the source text. Works for nodes that have the ESLint-style `range` property and nodes that have the Unist-style [`position` property](https://github.com/syntax-tree/unist?tab=readme-ov-file#position). If you're using an AST with a different range format, you'll still need to implement this method yourself.
- `getText(nodeOrToken, charsBefore, charsAfter)` - gets the source text for the given node or token that has range information attached. Optionally, can return additional characters before and after the given node or token. As long as `getRange()` is properly implemented, this method will just work.
- `getAncestors(node)` - returns the ancestry of the node. In order for this to work, you must implement the `getParent()` method yourself.
Here's an example:
```js
import { TextSourceCodeBase } from "@eslint/plugin-kit";
export class MySourceCode extends TextSourceCodeBase {
#parents = new Map();
constructor({ ast, text }) {
super({ ast, text });
}
getParent(node) {
return this.#parents.get(node);
}
traverse() {
const steps = [];
for (const { node, parent, phase } of iterator(this.ast)) {
//save the parent information
this.#parent.set(node, parent);
steps.push(
new VisitNodeStep({
target: node,
phase: phase === "enter" ? 1 : 2,
args: [node, parent],
}),
);
}
return steps;
}
}
```
In general, it's safe to collect the parent information during the `traverse()` method as `getParent()` and `getAncestor()` will only be called from rules once the AST has been traversed at least once.
## License
Apache 2.0
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a> <a href="https://trunk.io/"><img src="https://images.opencollective.com/trunkio/fb92d60/avatar.png" alt="trunk.io" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/e6d15e1/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://nolebase.ayaka.io"><img src="https://avatars.githubusercontent.com/u/11081491" alt="Neko" height="32"></a> <a href="https://nx.dev"><img src="https://avatars.githubusercontent.com/u/23692104" alt="Nx" height="32"></a> <a href="https://opensource.mercedes-benz.com/"><img src="https://avatars.githubusercontent.com/u/34240465" alt="Mercedes-Benz Group" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="LambdaTest" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->

64
node_modules/@eslint/plugin-kit/package.json generated vendored Normal file
View File

@ -0,0 +1,64 @@
{
"name": "@eslint/plugin-kit",
"version": "0.2.8",
"description": "Utilities for building ESLint plugins.",
"author": "Nicholas C. Zakas",
"type": "module",
"main": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
"exports": {
"require": {
"types": "./dist/cjs/index.d.cts",
"default": "./dist/cjs/index.cjs"
},
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
}
},
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/eslint/rewrite.git"
},
"bugs": {
"url": "https://github.com/eslint/rewrite/issues"
},
"homepage": "https://github.com/eslint/rewrite#readme",
"scripts": {
"build:dedupe-types": "node ../../tools/dedupe-types.js dist/cjs/index.cjs dist/esm/index.js",
"build:cts": "node ../../tools/build-cts.js dist/esm/index.d.ts dist/cjs/index.d.cts",
"build": "rollup -c && npm run build:dedupe-types && tsc -p tsconfig.esm.json && npm run build:cts",
"pretest": "npm run build",
"test": "mocha tests/",
"test:coverage": "c8 npm test",
"test:jsr": "npx jsr@latest publish --dry-run",
"test:types": "tsc -p tests/types/tsconfig.json"
},
"keywords": [
"eslint",
"eslintplugin",
"eslint-plugin"
],
"license": "Apache-2.0",
"dependencies": {
"@eslint/core": "^0.13.0",
"levn": "^0.4.1"
},
"devDependencies": {
"@types/levn": "^0.4.0",
"c8": "^9.1.0",
"mocha": "^10.4.0",
"rollup": "^4.16.2",
"rollup-plugin-copy": "^3.5.0",
"typescript": "^5.4.5"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
}

201
node_modules/@humanfs/core/LICENSE generated vendored Normal file
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 [yyyy] [name of copyright owner]
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.

Some files were not shown because too many files have changed in this diff Show More