diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml index 76efca3..99f194d 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.yml +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -19,6 +19,8 @@ body: required: false - label: "`@eslint/object-schema`" required: false + - label: "`@eslint/plugin-kit`" + required: false - type: textarea attributes: label: Environment diff --git a/.github/ISSUE_TEMPLATE/change.yml b/.github/ISSUE_TEMPLATE/change.yml index 0956a93..a77de3e 100644 --- a/.github/ISSUE_TEMPLATE/change.yml +++ b/.github/ISSUE_TEMPLATE/change.yml @@ -18,6 +18,8 @@ body: required: false - label: "`@eslint/object-schema`" required: false + - label: "`@eslint/plugin-kit`" + required: false - type: textarea attributes: label: What problem do you want to solve? diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index 787ad92..d5733d9 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -204,3 +204,34 @@ jobs: env: MASTODON_ACCESS_TOKEN: ${{ secrets.MASTODON_ACCESS_TOKEN }} MASTODON_HOST: ${{ secrets.MASTODON_HOST }} + + #----------------------------------------------------------------------------- + # @eslint/plugin-kit + #----------------------------------------------------------------------------- + + - name: Publish @eslint/plugin-kit package to npm + run: npm publish -w packages/plugin-kit --provenance + if: ${{ steps.release.outputs['packages/plugin-kit--release_created'] }} + env: + NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} + + - name: Publish @eslint/plugin-kit package to JSR + run: npx jsr publish + working-directory: packages/plugin-kit + if: ${{ steps.release.outputs['packages/plugin-kit--release_created'] }} + + - name: Tweet Release Announcement + run: npx @humanwhocodes/tweet "eslint/plugin-kit v${{ steps.release.outputs['packages/plugin-kit--major'] }}.${{ steps.release.outputs['packages/plugin-kit--minor'] }}.${{ steps.release.outputs['packages/plugin-kit--patch'] }} has been released!\n\n${{ github.event.repository.html_url }}/releases/tag/${{ steps.release.outputs['packages/plugin-kit--tag_name'] }}" + if: ${{ steps.release.outputs['packages/plugin-kit--release_created'] }} + env: + TWITTER_CONSUMER_KEY: ${{ secrets.TWITTER_CONSUMER_KEY }} + TWITTER_CONSUMER_SECRET: ${{ secrets.TWITTER_CONSUMER_SECRET }} + TWITTER_ACCESS_TOKEN_KEY: ${{ secrets.TWITTER_ACCESS_TOKEN_KEY }} + TWITTER_ACCESS_TOKEN_SECRET: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }} + + - name: Toot Release Announcement + run: npx @humanwhocodes/toot "eslint/plugin-kit v${{ steps.release.outputs['packages/plugin-kit--major'] }}.${{ steps.release.outputs['packages/plugin-kit--minor'] }}.${{ steps.release.outputs['packages/plugin-kit--patch'] }} has been released!\n\n${{ github.event.repository.html_url }}/releases/tag/${{ steps.release.outputs['packages/plugin-kit--tag_name'] }}" + if: ${{ steps.release.outputs['packages/plugin-kit--release_created'] }} + env: + MASTODON_ACCESS_TOKEN: ${{ secrets.MASTODON_ACCESS_TOKEN }} + MASTODON_HOST: ${{ secrets.MASTODON_HOST }} diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 77240a0..ba4be35 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -3,5 +3,6 @@ "packages/config-array": "0.17.1", "packages/core": "0.3.0", "packages/migrate-config": "1.2.0", - "packages/object-schema": "2.1.4" + "packages/object-schema": "2.1.4", + "packages/plugin-kit": "0.0.0" } diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 25a8663..129fa39 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -402,7 +402,7 @@ export type SourceCode = TextSourceCode | BinarySourceCode; */ export interface VisitTraversalStep { kind: 1; - target: object; + target: unknown; phase: 1 /* enter */ | 2 /* exit */; args: Array; } diff --git a/packages/plugin-kit/CHANGELOG.md b/packages/plugin-kit/CHANGELOG.md new file mode 100644 index 0000000..e69de29 diff --git a/packages/plugin-kit/LICENSE b/packages/plugin-kit/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/packages/plugin-kit/LICENSE @@ -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. diff --git a/packages/plugin-kit/README.md b/packages/plugin-kit/README.md new file mode 100644 index 0000000..3c820b8 --- /dev/null +++ b/packages/plugin-kit/README.md @@ -0,0 +1,224 @@ +# 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()` +- `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; + } +} +``` + +### `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 + +## 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 README and website. + + + +

Platinum Sponsors

+

Automattic Airbnb

Gold Sponsors

+

Eli Schleifer

Silver Sponsors

+

JetBrains Liftoff American Express Workleap

Bronze Sponsors

+

notion Anagram Solver Icons8 Discord Ignition Nx HeroCoders Nextbase Starter Kit

+ + + +

Technology Sponsors

+

Netlify Algolia 1Password +

+ diff --git a/packages/plugin-kit/jsr.json b/packages/plugin-kit/jsr.json new file mode 100644 index 0000000..ba76e05 --- /dev/null +++ b/packages/plugin-kit/jsr.json @@ -0,0 +1,16 @@ +{ + "name": "@eslint/plugin-kit", + "version": "0.0.0", + "exports": "./dist/esm/index.js", + "publish": { + "include": [ + "dist/esm/index.js", + "dist/esm/index.d.ts", + "dist/esm/types.ts", + "dist/esm/types.d.ts", + "README.md", + "jsr.json", + "LICENSE" + ] + } +} diff --git a/packages/plugin-kit/package.json b/packages/plugin-kit/package.json new file mode 100644 index 0000000..ef10fbb --- /dev/null +++ b/packages/plugin-kit/package.json @@ -0,0 +1,62 @@ +{ + "name": "@eslint/plugin-kit", + "version": "0.0.0", + "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 -e \"fs.copyFileSync('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", + "pretest": "npm run build", + "test": "mocha tests/", + "test:coverage": "c8 npm test" + }, + "keywords": [ + "eslint", + "eslintplugin", + "eslint-plugin" + ], + "license": "Apache-2.0", + "devDependencies": { + "@eslint/core": "^0.3.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" + }, + "dependencies": { + "levn": "^0.4.1" + } +} diff --git a/packages/plugin-kit/rollup.config.js b/packages/plugin-kit/rollup.config.js new file mode 100644 index 0000000..03a11e1 --- /dev/null +++ b/packages/plugin-kit/rollup.config.js @@ -0,0 +1,24 @@ +import copy from "rollup-plugin-copy"; + +export default { + input: "src/index.js", + output: [ + { + file: "dist/cjs/index.cjs", + format: "cjs", + }, + { + file: "dist/esm/index.js", + format: "esm", + banner: '// @ts-self-types="./index.d.ts"', + }, + ], + plugins: [ + copy({ + targets: [ + { src: "src/types.ts", dest: "dist/cjs" }, + { src: "src/types.ts", dest: "dist/esm" }, + ], + }), + ], +}; diff --git a/packages/plugin-kit/src/@types/levn.d.ts b/packages/plugin-kit/src/@types/levn.d.ts new file mode 100644 index 0000000..94414cc --- /dev/null +++ b/packages/plugin-kit/src/@types/levn.d.ts @@ -0,0 +1,8 @@ +declare module "levn" { + interface ParseOptions { + explicit?: boolean; + customTypes: Record; + } + + function parse(type: string, input: string, options?: ParseOptions): object; +} diff --git a/packages/plugin-kit/src/config-comment-parser.js b/packages/plugin-kit/src/config-comment-parser.js new file mode 100644 index 0000000..f22f97a --- /dev/null +++ b/packages/plugin-kit/src/config-comment-parser.js @@ -0,0 +1,244 @@ +/** + * @fileoverview Config Comment Parser + * @author Nicholas C. Zakas + */ + +/* eslint class-methods-use-this: off -- Methods desired on instance */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +// @ts-ignore -- don't feel like fighting with TypeScript right now +import levn from "levn"; + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("@eslint/core").RuleConfig} RuleConfig */ +/** @typedef {import("@eslint/core").RulesConfig} RulesConfig */ +/** @typedef {import("./types.ts").StringConfig} StringConfig */ +/** @typedef {import("./types.ts").BooleanConfig} BooleanConfig */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const directivesPattern = /^([a-z]+(?:-[a-z]+)*)(?:\s|$)/u; +const validSeverities = new Set([0, 1, 2, "off", "warn", "error"]); + +/** + * Determines if the severity in the rule configuration is valid. + * @param {RuleConfig} ruleConfig A rule's configuration. + */ +function isSeverityValid(ruleConfig) { + const severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + return validSeverities.has(severity); +} + +/** + * Determines if all severities in the rules configuration are valid. + * @param {RulesConfig} rulesConfig The rules configuration to check. + * @returns {boolean} `true` if all severities are valid, otherwise `false`. + */ +function isEverySeverityValid(rulesConfig) { + return Object.values(rulesConfig).every(isSeverityValid); +} + +/** + * Represents a directive comment. + */ +export class DirectiveComment { + /** + * The label of the directive, such as "eslint", "eslint-disable", etc. + * @type {string} + */ + label = ""; + + /** + * The value of the directive (the string after the label). + * @type {string} + */ + value = ""; + + /** + * The justification of the directive (the string after the --). + * @type {string} + */ + justification = ""; + + /** + * Creates a new directive comment. + * @param {string} label The label of the directive. + * @param {string} value The value of the directive. + * @param {string} justification The justification of the directive. + */ + constructor(label, value, justification) { + this.label = label; + this.value = value; + this.justification = justification; + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Object to parse ESLint configuration comments. + */ +export class ConfigCommentParser { + /** + * Parses a list of "name:string_value" or/and "name" options divided by comma or + * whitespace. Used for "global" comments. + * @param {string} string The string to parse. + * @returns {StringConfig} Result map object of names and string values, or null values if no value was provided. + */ + parseStringConfig(string) { + const items = /** @type {StringConfig} */ ({}); + + // Collapse whitespace around `:` and `,` to make parsing easier + const trimmedString = string.replace(/\s*([:,])\s*/gu, "$1"); + + trimmedString.split(/\s|,+/u).forEach(name => { + if (!name) { + return; + } + + // value defaults to null (if not provided), e.g: "foo" => ["foo", null] + const [key, value = null] = name.split(":"); + + items[key] = value; + }); + + return items; + } + + /** + * Parses a JSON-like config. + * @param {string} string The string to parse. + * @returns {({ok: true, config: RulesConfig}|{ok: false, error: {message: string}})} Result map object + */ + parseJSONLikeConfig(string) { + // Parses a JSON-like comment by the same way as parsing CLI option. + try { + const items = levn.parse("Object", string) || {}; + + /* + * When the configuration has any invalid severities, it should be completely + * ignored. This is because the configuration is not valid and should not be + * applied. + * + * For example, the following configuration is invalid: + * + * "no-alert: 2 no-console: 2" + * + * This results in a configuration of { "no-alert": "2 no-console: 2" }, which is + * not valid. In this case, the configuration should be ignored. + */ + if (isEverySeverityValid(items)) { + return { + ok: true, + config: items, + }; + } + } catch { + // levn parsing error: ignore to parse the string by a fallback. + } + + /* + * Optionator cannot parse commaless notations. + * But we are supporting that. So this is a fallback for that. + */ + const normalizedString = string + .replace(/([-a-zA-Z0-9/]+):/gu, '"$1":') + .replace(/(\]|[0-9])\s+(?=")/u, "$1,"); + + try { + const items = JSON.parse(`{${normalizedString}}`); + + return { + ok: true, + config: items, + }; + } catch (ex) { + const errorMessage = ex instanceof Error ? ex.message : String(ex); + + return { + ok: false, + error: { + message: `Failed to parse JSON from '${normalizedString}': ${errorMessage}`, + }, + }; + } + } + + /** + * Parses a config of values separated by comma. + * @param {string} string The string to parse. + * @returns {BooleanConfig} Result map of values and true values + */ + parseListConfig(string) { + const items = /** @type {BooleanConfig} */ ({}); + + string.split(",").forEach(name => { + const trimmedName = name + .trim() + .replace( + /^(?['"]?)(?.*)\k$/su, + "$", + ); + + if (trimmedName) { + items[trimmedName] = true; + } + }); + + return items; + } + + /** + * Extract the directive and the justification from a given directive comment and trim them. + * @param {string} value The comment text to extract. + * @returns {{directivePart: string, justificationPart: string}} The extracted directive and justification. + */ + #extractDirectiveComment(value) { + const match = /\s-{2,}\s/u.exec(value); + + if (!match) { + return { directivePart: value.trim(), justificationPart: "" }; + } + + const directive = value.slice(0, match.index).trim(); + const justification = value.slice(match.index + match[0].length).trim(); + + return { directivePart: directive, justificationPart: justification }; + } + + /** + * Parses a directive comment into directive text and value. + * @param {string} string The string with the directive to be parsed. + * @returns {DirectiveComment|undefined} The parsed directive or `undefined` if the directive is invalid. + */ + parseDirective(string) { + const { directivePart, justificationPart } = + this.#extractDirectiveComment(string); + const match = directivesPattern.exec(directivePart); + + if (!match) { + return undefined; + } + + const directiveText = match[1]; + const directiveValue = directivePart.slice( + match.index + directiveText.length, + ); + + return new DirectiveComment( + directiveText, + directiveValue.trim(), + justificationPart, + ); + } +} diff --git a/packages/plugin-kit/src/index.js b/packages/plugin-kit/src/index.js new file mode 100644 index 0000000..908fa32 --- /dev/null +++ b/packages/plugin-kit/src/index.js @@ -0,0 +1,11 @@ +/** + * @fileoverview Package API + * @author Nicholas C. Zakas + */ + +export { ConfigCommentParser } from "./config-comment-parser.js"; +export { + CallMethodStep, + VisitNodeStep, + TextSourceCodeBase, +} from "./source-code.js"; diff --git a/packages/plugin-kit/src/source-code.js b/packages/plugin-kit/src/source-code.js new file mode 100644 index 0000000..a198534 --- /dev/null +++ b/packages/plugin-kit/src/source-code.js @@ -0,0 +1,309 @@ +/** + * @fileoverview A collection of helper classes for implementing `SourceCode`. + * @author Nicholas C. Zakas + */ + +/* eslint class-methods-use-this: off -- Required to complete interface. */ + +//----------------------------------------------------------------------------- +// Type Definitions +//----------------------------------------------------------------------------- + +/** @typedef {import("@eslint/core").VisitTraversalStep} VisitTraversalStep */ +/** @typedef {import("@eslint/core").CallTraversalStep} CallTraversalStep */ +/** @typedef {import("@eslint/core").TextSourceCode} TextSourceCode */ +/** @typedef {import("@eslint/core").TraversalStep} TraversalStep */ +/** @typedef {import("@eslint/core").SourceLocation} SourceLocation */ +/** @typedef {import("@eslint/core").SourceLocationWithOffset} SourceLocationWithOffset */ +/** @typedef {import("@eslint/core").SourceRange} SourceRange */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** + * Determines if a node has ESTree-style loc information. + * @param {object} node The node to check. + * @returns {node is {loc:SourceLocation}} `true` if the node has ESTree-style loc information, `false` if not. + */ +function hasESTreeStyleLoc(node) { + return "loc" in node; +} + +/** + * Determines if a node has position-style loc information. + * @param {object} node The node to check. + * @returns {node is {position:SourceLocation}} `true` if the node has position-style range information, `false` if not. + */ +function hasPosStyleLoc(node) { + return "position" in node; +} + +/** + * Determines if a node has ESTree-style range information. + * @param {object} node The node to check. + * @returns {node is {range:SourceRange}} `true` if the node has ESTree-style range information, `false` if not. + */ +function hasESTreeStyleRange(node) { + return "range" in node; +} + +/** + * Determines if a node has position-style range information. + * @param {object} node The node to check. + * @returns {node is {position:SourceLocationWithOffset}} `true` if the node has position-style range information, `false` if not. + */ +function hasPosStyleRange(node) { + return "position" in node; +} + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A class to represent a step in the traversal process where a node is visited. + * @implements {VisitTraversalStep} + */ +export class VisitNodeStep { + /** + * The type of the step. + * @type {"visit"} + * @readonly + */ + type = "visit"; + + /** + * The kind of the step. Represents the same data as the `type` property + * but it's a number for performance. + * @type {1} + * @readonly + */ + kind = 1; + + /** + * The target of the step. + * @type {object} + */ + target; + + /** + * The phase of the step. + * @type {1|2} + */ + phase; + + /** + * The arguments of the step. + * @type {Array} + */ + args; + + /** + * Creates a new instance. + * @param {Object} options The options for the step. + * @param {object} options.target The target of the step. + * @param {1|2} options.phase The phase of the step. + * @param {Array} options.args The arguments of the step. + */ + constructor({ target, phase, args }) { + this.target = target; + this.phase = phase; + this.args = args; + } +} + +/** + * A class to represent a step in the traversal process where a + * method is called. + * @implements {CallTraversalStep} + */ +export class CallMethodStep { + /** + * The type of the step. + * @type {"call"} + * @readonly + */ + type = "call"; + + /** + * The kind of the step. Represents the same data as the `type` property + * but it's a number for performance. + * @type {2} + * @readonly + */ + kind = 2; + + /** + * The name of the method to call. + * @type {string} + */ + target; + + /** + * The arguments to pass to the method. + * @type {Array} + */ + args; + + /** + * Creates a new instance. + * @param {Object} options The options for the step. + * @param {string} options.target The target of the step. + * @param {Array} options.args The arguments of the step. + */ + constructor({ target, args }) { + this.target = target; + this.args = args; + } +} + +/** + * Source Code Base Object + * @implements {TextSourceCode} + */ +export class TextSourceCodeBase { + /** + * The lines of text in the source code. + * @type {Array} + */ + #lines; + + /** + * The AST of the source code. + * @type {object} + */ + ast; + + /** + * The text of the source code. + * @type {string} + */ + text; + + /** + * Creates a new instance. + * @param {Object} options The options for the instance. + * @param {string} options.text The source code text. + * @param {object} options.ast The root AST node. + * @param {RegExp} [options.lineEndingPattern] The pattern to match lineEndings in the source code. + */ + constructor({ text, ast, lineEndingPattern = /\r?\n/u }) { + this.ast = ast; + this.text = text; + this.#lines = text.split(lineEndingPattern); + } + + /** + * Returns the loc information for the given node or token. + * @param {object} nodeOrToken The node or token to get the loc information for. + * @returns {SourceLocation} The loc information for the node or token. + */ + getLoc(nodeOrToken) { + if (hasESTreeStyleLoc(nodeOrToken)) { + return nodeOrToken.loc; + } + + if (hasPosStyleLoc(nodeOrToken)) { + return nodeOrToken.position; + } + + throw new Error( + "Custom getLoc() method must be implemented in the subclass.", + ); + } + + /** + * Returns the range information for the given node or token. + * @param {object} nodeOrToken The node or token to get the range information for. + * @returns {SourceRange} The range information for the node or token. + */ + getRange(nodeOrToken) { + if (hasESTreeStyleRange(nodeOrToken)) { + return nodeOrToken.range; + } + + if (hasPosStyleRange(nodeOrToken)) { + return [ + nodeOrToken.position.start.offset, + nodeOrToken.position.end.offset, + ]; + } + + throw new Error( + "Custom getRange() method must be implemented in the subclass.", + ); + } + + /* eslint-disable no-unused-vars -- Required to complete interface. */ + /** + * Returns the parent of the given node. + * @param {object} node The node to get the parent of. + * @returns {object|undefined} The parent of the node. + */ + getParent(node) { + throw new Error("Not implemented."); + } + /* eslint-enable no-unused-vars -- Required to complete interface. */ + + /** + * Gets all the ancestors of a given node + * @param {object} node The node + * @returns {Array} All the ancestor nodes in the AST, not including the provided node, starting + * from the root node at index 0 and going inwards to the parent node. + * @throws {TypeError} When `node` is missing. + */ + getAncestors(node) { + if (!node) { + throw new TypeError("Missing required argument: node."); + } + + const ancestorsStartingAtParent = []; + + for ( + let ancestor = this.getParent(node); + ancestor; + ancestor = this.getParent(ancestor) + ) { + ancestorsStartingAtParent.push(ancestor); + } + + return ancestorsStartingAtParent.reverse(); + } + + /** + * Gets the source code for the given node. + * @param {object} [node] The AST node to get the text for. + * @param {number} [beforeCount] The number of characters before the node to retrieve. + * @param {number} [afterCount] The number of characters after the node to retrieve. + * @returns {string} The text representing the AST node. + * @public + */ + getText(node, beforeCount, afterCount) { + if (node) { + const range = this.getRange(node); + return this.text.slice( + Math.max(range[0] - (beforeCount || 0), 0), + range[1] + (afterCount || 0), + ); + } + return this.text; + } + + /** + * Gets the entire source text split into an array of lines. + * @returns {Array} The source text as an array of lines. + * @public + */ + get lines() { + return this.#lines; + } + + /** + * Traverse the source code and return the steps that were taken. + * @returns {Iterable} The steps that were taken while traversing the source code. + */ + traverse() { + throw new Error("Not implemented."); + } +} diff --git a/packages/plugin-kit/src/types.ts b/packages/plugin-kit/src/types.ts new file mode 100644 index 0000000..d3f6a88 --- /dev/null +++ b/packages/plugin-kit/src/types.ts @@ -0,0 +1,7 @@ +/** + * @fileoverview Types for the plugin-kit package. + * @author Nicholas C. Zakas + */ + +export type StringConfig = Record; +export type BooleanConfig = Record; diff --git a/packages/plugin-kit/tests/config-comment-parser.test.js b/packages/plugin-kit/tests/config-comment-parser.test.js new file mode 100644 index 0000000..e9895dc --- /dev/null +++ b/packages/plugin-kit/tests/config-comment-parser.test.js @@ -0,0 +1,284 @@ +/** + * @fileoverview Tests for ConfigCommentParser object. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import assert from "node:assert"; +import { + ConfigCommentParser, + DirectiveComment, +} from "../src/config-comment-parser.js"; + +//------------------------------------------------------------------------------ +// Tests +//------------------------------------------------------------------------------ + +describe("ConfigCommentParser", () => { + let commentParser; + + beforeEach(() => { + commentParser = new ConfigCommentParser(); + }); + + describe("parseStringConfig", () => { + const comment = {}; + + it("should parse String config with one item", () => { + const code = "a: true"; + const result = commentParser.parseStringConfig(code, comment); + + assert.deepStrictEqual(result, { + a: "true", + }); + }); + + it("should parse String config with one item and no value", () => { + const code = "a"; + const result = commentParser.parseStringConfig(code, comment); + + assert.deepStrictEqual(result, { + a: null, + }); + }); + + it("should parse String config with two items", () => { + const code = "a: five b:three"; + const result = commentParser.parseStringConfig(code, comment); + + assert.deepStrictEqual(result, { + a: "five", + b: "three", + }); + }); + + it("should parse String config with two comma-separated items", () => { + const code = "a: seventy, b:ELEVENTEEN"; + const result = commentParser.parseStringConfig(code, comment); + + assert.deepStrictEqual(result, { + a: "seventy", + b: "ELEVENTEEN", + }); + }); + + it("should parse String config with two comma-separated items and no values", () => { + const code = "a , b"; + const result = commentParser.parseStringConfig(code, comment); + + assert.deepStrictEqual(result, { + a: null, + b: null, + }); + }); + }); + + describe("parseListConfig", () => { + it("should parse list config with one item", () => { + const code = "a"; + const result = commentParser.parseListConfig(code); + + assert.deepStrictEqual(result, { + a: true, + }); + }); + + it("should parse list config with two items", () => { + const code = "a, b"; + const result = commentParser.parseListConfig(code); + + assert.deepStrictEqual(result, { + a: true, + b: true, + }); + }); + + it("should parse list config with two items and extra whitespace", () => { + const code = " a , b "; + const result = commentParser.parseListConfig(code); + + assert.deepStrictEqual(result, { + a: true, + b: true, + }); + }); + + it("should parse list config with quoted items", () => { + const code = "'a', \"b\", 'c\", \"d'"; + const result = commentParser.parseListConfig(code); + + assert.deepStrictEqual(result, { + a: true, + b: true, + "\"d'": true, // This result is correct because used mismatched quotes. + "'c\"": true, // This result is correct because used mismatched quotes. + }); + }); + it("should parse list config with spaced items", () => { + const code = " a b , 'c d' , \"e f\" "; + const result = commentParser.parseListConfig(code); + + assert.deepStrictEqual(result, { + "a b": true, + "c d": true, + "e f": true, + }); + }); + }); + + describe("parseJSONLikeConfig()", () => { + it("should parse JSON config with one item", () => { + const code = "no-alert:0"; + const result = commentParser.parseJSONLikeConfig(code); + + assert.deepStrictEqual(result, { + ok: true, + config: { + "no-alert": 0, + }, + }); + }); + + it("should parse JSON config with two items", () => { + const code = "no-alert:0 semi: 2"; + const result = commentParser.parseJSONLikeConfig(code); + + assert.deepStrictEqual(result, { + ok: true, + config: { + "no-alert": 0, + semi: 2, + }, + }); + }); + + it("should parse JSON config with two comma-separated items", () => { + const code = "no-alert:0,semi: 2"; + const result = commentParser.parseJSONLikeConfig(code); + + assert.deepStrictEqual(result, { + ok: true, + config: { + "no-alert": 0, + semi: 2, + }, + }); + }); + + it("should parse JSON config with two items and a string severity", () => { + const code = "no-alert:off,semi: 2"; + const result = commentParser.parseJSONLikeConfig(code); + + assert.deepStrictEqual(result, { + ok: true, + config: { + "no-alert": "off", + semi: 2, + }, + }); + }); + + it("should parse JSON config with two items and options", () => { + const code = "no-alert:off, semi: [2, always]"; + const result = commentParser.parseJSONLikeConfig(code); + + assert.deepStrictEqual(result, { + ok: true, + config: { + "no-alert": "off", + semi: [2, "always"], + }, + }); + }); + + it("should parse JSON config with two items and options from plugins", () => { + const code = "plugin/no-alert:off, plugin/semi: [2, always]"; + const result = commentParser.parseJSONLikeConfig(code); + + assert.deepStrictEqual(result, { + ok: true, + config: { + "plugin/no-alert": "off", + "plugin/semi": [2, "always"], + }, + }); + }); + }); + + describe("parseDirective", () => { + it("should parse a directive comment with a justification", () => { + const comment = "eslint no-unused-vars: error -- test "; + const result = commentParser.parseDirective(comment); + + assert.deepStrictEqual( + result, + new DirectiveComment("eslint", "no-unused-vars: error", "test"), + ); + }); + + it("should parse a directive comment without a justification", () => { + const comment = "global foo"; + const result = commentParser.parseDirective(comment); + + assert.deepStrictEqual( + result, + new DirectiveComment("global", "foo", ""), + ); + }); + + it("should parse a directive comment with one dash and a justification", () => { + const comment = "eslint-disable foo -- not needed"; + const result = commentParser.parseDirective(comment); + + assert.deepStrictEqual( + result, + new DirectiveComment("eslint-disable", "foo", "not needed"), + ); + }); + + it("should parse a directive comment with dashes and a justification", () => { + const comment = "eslint-disable-next-line foo -- not needed"; + const result = commentParser.parseDirective(comment); + + assert.deepStrictEqual( + result, + new DirectiveComment( + "eslint-disable-next-line", + "foo", + "not needed", + ), + ); + }); + + it("should parse a directive comment with dashes and commas and a justification with leading space", () => { + const comment = " eslint-disable no-alert, no-console -- j1"; + const result = commentParser.parseDirective(comment); + + assert.deepStrictEqual( + result, + new DirectiveComment( + "eslint-disable", + "no-alert, no-console", + "j1", + ), + ); + }); + + it("should return undefined for an empty string", () => { + const comment = ""; + const result = commentParser.parseDirective(comment); + + assert.deepStrictEqual(result, undefined); + }); + + it("should return undefined for a string with only whitespace", () => { + const comment = " "; + const result = commentParser.parseDirective(comment); + + assert.deepStrictEqual(result, undefined); + }); + }); +}); diff --git a/packages/plugin-kit/tests/source-code.test.js b/packages/plugin-kit/tests/source-code.test.js new file mode 100644 index 0000000..369f5e3 --- /dev/null +++ b/packages/plugin-kit/tests/source-code.test.js @@ -0,0 +1,231 @@ +/** + * @fileoverview Tests for ConfigCommentParser object. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import assert from "node:assert"; +import { + CallMethodStep, + VisitNodeStep, + TextSourceCodeBase, +} from "../src/source-code.js"; + +//------------------------------------------------------------------------------ +// Tests +//------------------------------------------------------------------------------ + +describe("source-code", () => { + describe("CallMethodStep", () => { + it("should create a CallMethodStep instance", () => { + const step = new CallMethodStep({ + target: "foo", + args: ["bar"], + }); + + assert.strictEqual(step.type, "call"); + assert.strictEqual(step.kind, 2); + assert.strictEqual(step.target, "foo"); + assert.deepStrictEqual(step.args, ["bar"]); + }); + }); + + describe("VisitNodeStep", () => { + it("should create a VisitNodeStep instance", () => { + const step = new VisitNodeStep({ + target: "foo", + phase: 1, + args: ["bar"], + }); + + assert.strictEqual(step.type, "visit"); + assert.strictEqual(step.kind, 1); + assert.strictEqual(step.target, "foo"); + assert.strictEqual(step.phase, 1); + assert.deepStrictEqual(step.args, ["bar"]); + }); + + it("should create a VisitNodeStep instance in phase 2", () => { + const step = new VisitNodeStep({ + target: "foo", + phase: 2, + args: ["bar"], + }); + + assert.strictEqual(step.type, "visit"); + assert.strictEqual(step.kind, 1); + assert.strictEqual(step.target, "foo"); + assert.strictEqual(step.phase, 2); + assert.deepStrictEqual(step.args, ["bar"]); + }); + }); + + describe("TextSourceCodeBase", () => { + describe("new TextSourceCodeBase", () => { + it("should create a new instance", () => { + const ast = {}; + const text = "foo"; + const sourceCode = new TextSourceCodeBase({ ast, text }); + + assert.strictEqual(sourceCode.ast, ast); + assert.strictEqual(sourceCode.text, "foo"); + }); + + it("should automatically split text into lines", () => { + const ast = {}; + const text = "foo\nbar\nbaz"; + const sourceCode = new TextSourceCodeBase({ ast, text }); + + assert.deepStrictEqual(sourceCode.lines, ["foo", "bar", "baz"]); + }); + + it("should automatically split text into lines with different lineEndingPattern", () => { + const ast = {}; + const text = "foo\u2028bar\u2029baz"; + const sourceCode = new TextSourceCodeBase({ + ast, + text, + lineEndingPattern: /\u2028|\u2029/gu, + }); + + assert.deepStrictEqual(sourceCode.lines, ["foo", "bar", "baz"]); + }); + }); + + describe("getLoc()", () => { + it("should return a location object when a loc property is present", () => { + const ast = { + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 }, + }, + }; + const text = "foo"; + const sourceCode = new TextSourceCodeBase({ ast, text }); + + assert.deepStrictEqual(sourceCode.getLoc(ast), ast.loc); + }); + + it("should return a location object when a position property is present", () => { + const ast = { + position: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 }, + }, + }; + const text = "foo"; + const sourceCode = new TextSourceCodeBase({ ast, text }); + + assert.deepStrictEqual(sourceCode.getLoc(ast), ast.position); + }); + + it("should throw an error when neither loc nor position property is present", () => { + const ast = {}; + const text = "foo"; + const sourceCode = new TextSourceCodeBase({ ast, text }); + + assert.throws(() => { + sourceCode.getLoc(ast); + }, /Custom getLoc\(\) method must be implemented in the subclass\./u); + }); + }); + + describe("getRange()", () => { + it("should return a range object when a range property is present", () => { + const ast = { + range: [0, 3], + }; + const text = "foo"; + const sourceCode = new TextSourceCodeBase({ ast, text }); + + assert.deepStrictEqual(sourceCode.getRange(ast), ast.range); + }); + + it("should return a range object when a position property is present", () => { + const ast = { + position: { + start: { offset: 0 }, + end: { offset: 3 }, + }, + }; + const text = "foo"; + const sourceCode = new TextSourceCodeBase({ ast, text }); + + assert.deepStrictEqual(sourceCode.getRange(ast), [0, 3]); + }); + + it("should throw an error when neither range nor position property is present", () => { + const ast = {}; + const text = "foo"; + const sourceCode = new TextSourceCodeBase({ ast, text }); + + assert.throws(() => { + sourceCode.getRange(ast); + }, /Custom getRange\(\) method must be implemented in the subclass\./u); + }); + }); + + describe("getText()", () => { + it("should return the text of the source code", () => { + const ast = {}; + const text = "foo"; + const sourceCode = new TextSourceCodeBase({ ast, text }); + + assert.strictEqual(sourceCode.getText(), "foo"); + }); + + it("should return the text of the given node", () => { + const ast = { + range: [0, 3], + }; + const text = "foo-bar"; + const sourceCode = new TextSourceCodeBase({ ast, text }); + + assert.strictEqual(sourceCode.getText(ast), "foo"); + }); + + it("should return the text of the given node plus one character before and after", () => { + const ast = { + range: [2, 5], + }; + const text = "foo-bar"; + const sourceCode = new TextSourceCodeBase({ ast, text }); + + assert.strictEqual(sourceCode.getText(ast, 1, 1), "oo-ba"); + }); + }); + + describe("getAncestors()", () => { + it("should return an array of ancestors", () => { + const node3 = {}; + const node2 = { child: node3 }; + const node1 = { child: node2 }; + + const parents = new Map([ + [node3, node2], + [node2, node1], + [node1, undefined], + ]); + + class TextSourceCode extends TextSourceCodeBase { + // eslint-disable-next-line class-methods-use-this -- Testing purposes + getParent(node) { + return parents.get(node); + } + } + + const ast = node1; + const text = "foo"; + const sourceCode = new TextSourceCode({ ast, text }); + + assert.deepStrictEqual(sourceCode.getAncestors(node3), [ + node1, + node2, + ]); + }); + }); + }); +}); diff --git a/packages/plugin-kit/tsconfig.esm.json b/packages/plugin-kit/tsconfig.esm.json new file mode 100644 index 0000000..7ce1092 --- /dev/null +++ b/packages/plugin-kit/tsconfig.esm.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "files": ["dist/esm/index.js"], + "compilerOptions": { + "strict": false + } +} diff --git a/packages/plugin-kit/tsconfig.json b/packages/plugin-kit/tsconfig.json new file mode 100644 index 0000000..960debf --- /dev/null +++ b/packages/plugin-kit/tsconfig.json @@ -0,0 +1,15 @@ +{ + "files": ["src/index.js"], + "compilerOptions": { + "declaration": true, + "emitDeclarationOnly": true, + "allowJs": true, + "checkJs": true, + "outDir": "dist/esm", + "target": "ES2022", + "moduleResolution": "NodeNext", + "module": "NodeNext", + "strict": true, + "typeRoots": ["node_modules/@types", "src/@types"] + } +} diff --git a/release-please-config.json b/release-please-config.json index b57e21c..324ab09 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -45,6 +45,17 @@ }, "packages/migrate-config": { "release-type": "node" + }, + "packages/plugin-kit": { + "release-type": "node", + "release-as": "0.1.0", + "extra-files": [ + { + "type": "json", + "path": "jsr.json", + "jsonpath": "$.version" + } + ] } } }