@@ -268,16 +268,16 @@ tester.run("require-selector-used-inside", rule as any, {
}
}
`,
- options: [
- {
- captureClassesFromDoc: [
- "/(\\.[a-z-]+)(?::[a-z-]+)?\\s+-\\s*[^\\r\\n]+/i",
- ],
- },
- ],
- },
+ options: [
{
- code: `
+ captureClassesFromDoc: [
+ "/(\\.[a-z-]+)(?::[a-z-]+)?\\s+-\\s*[^\\r\\n]+/i",
+ ],
+ },
+ ],
+ },
+ {
+ code: `
@@ -290,17 +290,17 @@ tester.run("require-selector-used-inside", rule as any, {
color: red;
}
`,
- options: [
- {
- ignoreBEMModifier: true,
- captureClassesFromDoc: [
- "/(\\.[a-z-]+)(?::[a-z-]+)?\\s+-\\s*[^\\r\\n]+/i",
- ],
- },
- ],
+ options: [
+ {
+ ignoreBEMModifier: true,
+ captureClassesFromDoc: [
+ "/(\\.[a-z-]+)(?::[a-z-]+)?\\s+-\\s*[^\\r\\n]+/i",
+ ],
},
- // ignore nodes
- `
+ ],
+ },
+ // ignore nodes
+ `
@@ -311,8 +311,8 @@ tester.run("require-selector-used-inside", rule as any, {
}
`,
- // not scoped
- `
+ // not scoped
+ `
@@ -321,8 +321,8 @@ tester.run("require-selector-used-inside", rule as any, {
`,
- // deep
- `
+ // deep
+ `
@@ -330,7 +330,7 @@ tester.run("require-selector-used-inside", rule as any, {
.foo ::v-deep #a {}
`,
- `
+ `
@@ -339,8 +339,8 @@ tester.run("require-selector-used-inside", rule as any, {
`,
- // Vue.js 3.x
- `
+ // Vue.js 3.x
+ `
@@ -348,7 +348,7 @@ tester.run("require-selector-used-inside", rule as any, {
.foo ::v-deep(#a) {}
`,
- `
+ `
@@ -356,7 +356,7 @@ tester.run("require-selector-used-inside", rule as any, {
.foo ::v-slotted(.bar > .baz) {}
`,
- `
+ `
@@ -364,7 +364,7 @@ tester.run("require-selector-used-inside", rule as any, {
.foo ::v-slotted(.bar > .baz) .qux {}
`,
- `
+ `
@@ -372,8 +372,8 @@ tester.run("require-selector-used-inside", rule as any, {
.unknown ::v-global(.bar > .baz) .qux {}
`,
- // with v-for
- `
+ // with v-for
+ `
{{ item }}
@@ -385,7 +385,7 @@ tester.run("require-selector-used-inside", rule as any, {
}
`,
- `
+ `
@@ -400,10 +400,10 @@ tester.run("require-selector-used-inside", rule as any, {
}
`,
- ],
- invalid: [
- {
- code: `
+ ],
+ invalid: [
+ {
+ code: `
@@ -412,27 +412,27 @@ tester.run("require-selector-used-inside", rule as any, {
div {}
`,
- errors: [
- {
- messageId: "unused",
- data: { selector: ".foo" },
- line: 6,
- column: 13,
- endLine: 6,
- endColumn: 17,
- },
- {
- messageId: "unused",
- data: { selector: "div" },
- line: 7,
- column: 13,
- endLine: 7,
- endColumn: 16,
- },
- ],
+ errors: [
+ {
+ messageId: "unused",
+ data: { selector: ".foo" },
+ line: 6,
+ column: 13,
+ endLine: 6,
+ endColumn: 17,
},
{
- code: `
+ messageId: "unused",
+ data: { selector: "div" },
+ line: 7,
+ column: 13,
+ endLine: 7,
+ endColumn: 16,
+ },
+ ],
+ },
+ {
+ code: `
@@ -440,27 +440,27 @@ tester.run("require-selector-used-inside", rule as any, {
.foo, /* comment */ div {}
`,
- errors: [
- {
- messageId: "unused",
- data: { selector: ".foo" },
- line: 6,
- column: 13,
- endLine: 6,
- endColumn: 17,
- },
- {
- messageId: "unused",
- data: { selector: "div" },
- line: 6,
- column: 33,
- endLine: 6,
- endColumn: 36,
- },
- ],
+ errors: [
+ {
+ messageId: "unused",
+ data: { selector: ".foo" },
+ line: 6,
+ column: 13,
+ endLine: 6,
+ endColumn: 17,
},
{
- code: `
+ messageId: "unused",
+ data: { selector: "div" },
+ line: 6,
+ column: 33,
+ endLine: 6,
+ endColumn: 36,
+ },
+ ],
+ },
+ {
+ code: `
@@ -472,35 +472,35 @@ tester.run("require-selector-used-inside", rule as any, {
div > li.bar {}
`,
- errors: [
- {
- messageId: "unused",
- data: { selector: "div>.foo" },
- line: 8,
- column: 13,
- endLine: 8,
- endColumn: 23,
- },
- {
- messageId: "unused",
- data: { selector: "div>li" },
- line: 9,
- column: 13,
- endLine: 9,
- endColumn: 21,
- },
- {
- messageId: "unused",
- data: { selector: "div>li" },
- line: 10,
- column: 13,
- endLine: 10,
- endColumn: 21,
- },
- ],
+ errors: [
+ {
+ messageId: "unused",
+ data: { selector: "div>.foo" },
+ line: 8,
+ column: 13,
+ endLine: 8,
+ endColumn: 23,
+ },
+ {
+ messageId: "unused",
+ data: { selector: "div>li" },
+ line: 9,
+ column: 13,
+ endLine: 9,
+ endColumn: 21,
},
{
- code: `
+ messageId: "unused",
+ data: { selector: "div>li" },
+ line: 10,
+ column: 13,
+ endLine: 10,
+ endColumn: 21,
+ },
+ ],
+ },
+ {
+ code: `
@@ -508,19 +508,19 @@ tester.run("require-selector-used-inside", rule as any, {
.foo.bar {}
`,
- errors: [
- {
- messageId: "unused",
- data: { selector: ".foo.bar" },
- line: 6,
- column: 13,
- endLine: 6,
- endColumn: 21,
- },
- ],
- },
+ errors: [
{
- code: `
+ messageId: "unused",
+ data: { selector: ".foo.bar" },
+ line: 6,
+ column: 13,
+ endLine: 6,
+ endColumn: 21,
+ },
+ ],
+ },
+ {
+ code: `
@@ -534,35 +534,35 @@ tester.run("require-selector-used-inside", rule as any, {
}
`,
- errors: [
- {
- messageId: "unused",
- data: { selector: "div>.foo" },
- line: 8,
- column: 13,
- endLine: 9,
- endColumn: 25,
- },
- {
- messageId: "unused",
- data: { selector: "div>li" },
- line: 8,
- column: 13,
- endLine: 10,
- endColumn: 23,
- },
- {
- messageId: "unused",
- data: { selector: "div>li" },
- line: 8,
- column: 13,
- endLine: 11,
- endColumn: 23,
- },
- ],
+ errors: [
+ {
+ messageId: "unused",
+ data: { selector: "div>.foo" },
+ line: 8,
+ column: 13,
+ endLine: 9,
+ endColumn: 25,
},
{
- code: `
+ messageId: "unused",
+ data: { selector: "div>li" },
+ line: 8,
+ column: 13,
+ endLine: 10,
+ endColumn: 23,
+ },
+ {
+ messageId: "unused",
+ data: { selector: "div>li" },
+ line: 8,
+ column: 13,
+ endLine: 11,
+ endColumn: 23,
+ },
+ ],
+ },
+ {
+ code: `
@@ -574,19 +574,19 @@ tester.run("require-selector-used-inside", rule as any, {
.foo { @nest .bar&-baz {} }
`,
- errors: [
- {
- messageId: "unused",
- data: { selector: ".bar.foo-baz" },
- line: 10,
- column: 26,
- endLine: 10,
- endColumn: 35,
- },
- ],
- },
+ errors: [
{
- code: `
+ messageId: "unused",
+ data: { selector: ".bar.foo-baz" },
+ line: 10,
+ column: 26,
+ endLine: 10,
+ endColumn: 35,
+ },
+ ],
+ },
+ {
+ code: `
@@ -597,21 +597,21 @@ tester.run("require-selector-used-inside", rule as any, {
}
`,
- errors: [
- {
- messageId: "unused",
- data: { selector: "div>div.b" },
- line: 8,
- column: 13,
- endLine: 8,
- endColumn: 24,
- },
- ],
- },
- // options
- // ignoreBEMModifier
+ errors: [
{
- code: `
+ messageId: "unused",
+ data: { selector: "div>div.b" },
+ line: 8,
+ column: 13,
+ endLine: 8,
+ endColumn: 24,
+ },
+ ],
+ },
+ // options
+ // ignoreBEMModifier
+ {
+ code: `
@@ -621,21 +621,21 @@ tester.run("require-selector-used-inside", rule as any, {
.foo--bar--baz {}
`,
- options: [{ ignoreBEMModifier: true }],
- errors: [
- {
- messageId: "unused",
- data: { selector: ".foo--bar--baz" },
- line: 8,
- column: 13,
- endLine: 8,
- endColumn: 27,
- },
- ],
- },
- // captureClassesFromDoc
+ options: [{ ignoreBEMModifier: true }],
+ errors: [
{
- code: `
+ messageId: "unused",
+ data: { selector: ".foo--bar--baz" },
+ line: 8,
+ column: 13,
+ endLine: 8,
+ endColumn: 27,
+ },
+ ],
+ },
+ // captureClassesFromDoc
+ {
+ code: `
@@ -661,27 +661,27 @@ tester.run("require-selector-used-inside", rule as any, {
}
}
`,
- options: [
- {
- captureClassesFromDoc: [
- "/(\\.[a-z-]+)(?::[a-z-]+)?\\s+-\\s*[^\\r\\n]+/i",
- ],
- },
- ],
- errors: [
- {
- message:
- "The selector `a.button.star.unknown` is unused in the template.",
- line: 18,
- column: 13,
- endLine: 23,
- endColumn: 26,
- },
- ],
+ options: [
+ {
+ captureClassesFromDoc: [
+ "/(\\.[a-z-]+)(?::[a-z-]+)?\\s+-\\s*[^\\r\\n]+/i",
+ ],
},
- // deep
+ ],
+ errors: [
{
- code: `
+ message:
+ "The selector `a.button.star.unknown` is unused in the template.",
+ line: 18,
+ column: 13,
+ endLine: 23,
+ endColumn: 26,
+ },
+ ],
+ },
+ // deep
+ {
+ code: `
@@ -696,27 +696,27 @@ tester.run("require-selector-used-inside", rule as any, {
div > .item >>> .a {}
`,
- errors: [
- {
- messageId: "unused",
- data: { selector: "div>li" },
- line: 11,
- column: 13,
- endLine: 11,
- endColumn: 21,
- },
- {
- messageId: "unused",
- data: { selector: "div>.item" },
- line: 13,
- column: 13,
- endLine: 13,
- endColumn: 24,
- },
- ],
+ errors: [
+ {
+ messageId: "unused",
+ data: { selector: "div>li" },
+ line: 11,
+ column: 13,
+ endLine: 11,
+ endColumn: 21,
},
{
- code: `
+ messageId: "unused",
+ data: { selector: "div>.item" },
+ line: 13,
+ column: 13,
+ endLine: 13,
+ endColumn: 24,
+ },
+ ],
+ },
+ {
+ code: `
@@ -731,27 +731,27 @@ tester.run("require-selector-used-inside", rule as any, {
div > .item /deep/ .a {}
`,
- errors: [
- {
- messageId: "unused",
- data: { selector: "div>li" },
- line: 11,
- column: 13,
- endLine: 11,
- endColumn: 21,
- },
- {
- messageId: "unused",
- data: { selector: "div>.item" },
- line: 13,
- column: 13,
- endLine: 13,
- endColumn: 24,
- },
- ],
+ errors: [
+ {
+ messageId: "unused",
+ data: { selector: "div>li" },
+ line: 11,
+ column: 13,
+ endLine: 11,
+ endColumn: 21,
},
{
- code: `
+ messageId: "unused",
+ data: { selector: "div>.item" },
+ line: 13,
+ column: 13,
+ endLine: 13,
+ endColumn: 24,
+ },
+ ],
+ },
+ {
+ code: `
@@ -766,29 +766,29 @@ tester.run("require-selector-used-inside", rule as any, {
div > .item ::v-deep .a {}
`,
- errors: [
- {
- messageId: "unused",
- data: { selector: "div>li" },
- line: 11,
- column: 13,
- endLine: 11,
- endColumn: 21,
- },
- {
- messageId: "unused",
- data: { selector: "div>.item" },
- line: 13,
- column: 13,
- endLine: 13,
- endColumn: 24,
- },
- ],
+ errors: [
+ {
+ messageId: "unused",
+ data: { selector: "div>li" },
+ line: 11,
+ column: 13,
+ endLine: 11,
+ endColumn: 21,
},
-
- // multiple parents children
{
- code: `
+ messageId: "unused",
+ data: { selector: "div>.item" },
+ line: 13,
+ column: 13,
+ endLine: 13,
+ endColumn: 24,
+ },
+ ],
+ },
+
+ // multiple parents children
+ {
+ code: `
@@ -810,21 +810,21 @@ tester.run("require-selector-used-inside", rule as any, {
}
`,
- errors: [
- {
- messageId: "unused",
- data: { selector: ".foo>.unknown" },
- line: 17,
- column: 13,
- endLine: 19,
- endColumn: 29,
- },
- ],
+ errors: [
+ {
+ messageId: "unused",
+ data: { selector: ".foo>.unknown" },
+ line: 17,
+ column: 13,
+ endLine: 19,
+ endColumn: 29,
},
+ ],
+ },
- // Vue.js 3.x
- {
- code: `
+ // Vue.js 3.x
+ {
+ code: `
@@ -839,13 +839,13 @@ tester.run("require-selector-used-inside", rule as any, {
div > .item ::v-deep(.a) {}
`,
- errors: [
- "The selector `div>li` is unused in the template.",
- "The selector `div>.item` is unused in the template.",
- ],
- },
- {
- code: `
+ errors: [
+ "The selector `div>li` is unused in the template.",
+ "The selector `div>.item` is unused in the template.",
+ ],
+ },
+ {
+ code: `
@@ -857,12 +857,12 @@ tester.run("require-selector-used-inside", rule as any, {
div > ul > ::v-slotted(.a) {}
`,
- errors: [
- "The selector `div>ul>::v-slotted(.a)` is unused in the template.",
- ],
- },
- {
- code: `
+ errors: [
+ "The selector `div>ul>::v-slotted(.a)` is unused in the template.",
+ ],
+ },
+ {
+ code: `
@@ -879,14 +879,14 @@ tester.run("require-selector-used-inside", rule as any, {
div > h3 > ::v-slotted(.a) {}
`,
- errors: [
- "The selector `div>li` is unused in the template.",
- "The selector `div>.item` is unused in the template.",
- "The selector `div>h3>::v-slotted(.a)` is unused in the template.",
- ],
- },
- {
- code: `
+ errors: [
+ "The selector `div>li` is unused in the template.",
+ "The selector `div>.item` is unused in the template.",
+ "The selector `div>h3>::v-slotted(.a)` is unused in the template.",
+ ],
+ },
+ {
+ code: `
@@ -903,11 +903,11 @@ tester.run("require-selector-used-inside", rule as any, {
div > h3 > ::v-slotted(.a) .bar {}
`,
- errors: [
- "The selector `div>li` is unused in the template.",
- "The selector `div>.item` is unused in the template.",
- "The selector `div>h3>` is unused in the template.",
- ],
- },
- ],
-})
+ errors: [
+ "The selector `div>li` is unused in the template.",
+ "The selector `div>.item` is unused in the template.",
+ "The selector `div>h3>` is unused in the template.",
+ ],
+ },
+ ],
+});
diff --git a/tests/lib/rules/require-v-deep-argument.ts b/tests/lib/rules/require-v-deep-argument.ts
index 5e5791f8..a2f02c0e 100644
--- a/tests/lib/rules/require-v-deep-argument.ts
+++ b/tests/lib/rules/require-v-deep-argument.ts
@@ -1,57 +1,55 @@
-import { RuleTester } from "eslint"
-import rule = require("../../../lib/rules/require-v-deep-argument")
+import { RuleTester } from "eslint";
+import rule = require("../../../lib/rules/require-v-deep-argument");
const tester = new RuleTester({
- parser: require.resolve("vue-eslint-parser"),
- parserOptions: {
- ecmaVersion: 2019,
- sourceType: "module",
- },
-})
+ parser: require.resolve("vue-eslint-parser"),
+ parserOptions: {
+ ecmaVersion: 2019,
+ sourceType: "module",
+ },
+});
tester.run("require-v-deep-argument", rule as any, {
- valid: [
- `
+ valid: [
+ `
sample
`,
- ],
- invalid: [
- {
- code: `
+ ],
+ invalid: [
+ {
+ code: `
sample
`,
- output: `
+ output: `
sample
`,
- errors: [
- {
- message:
- "Need to pass argument to the `::v-deep` pseudo-element.",
- line: 4,
- column: 23,
- endLine: 4,
- endColumn: 31,
- },
- {
- message:
- "Need to pass argument to the `::v-deep` pseudo-element.",
- line: 5,
- column: 23,
- endLine: 5,
- endColumn: 33,
- },
- ],
+ errors: [
+ {
+ message: "Need to pass argument to the `::v-deep` pseudo-element.",
+ line: 4,
+ column: 23,
+ endLine: 4,
+ endColumn: 31,
},
- ],
-})
+ {
+ message: "Need to pass argument to the `::v-deep` pseudo-element.",
+ line: 5,
+ column: 23,
+ endLine: 5,
+ endColumn: 33,
+ },
+ ],
+ },
+ ],
+});
diff --git a/tests/lib/rules/require-v-global-argument.ts b/tests/lib/rules/require-v-global-argument.ts
index 7bd83553..2e0204e5 100644
--- a/tests/lib/rules/require-v-global-argument.ts
+++ b/tests/lib/rules/require-v-global-argument.ts
@@ -1,50 +1,48 @@
-import { RuleTester } from "eslint"
-import rule = require("../../../lib/rules/require-v-global-argument")
+import { RuleTester } from "eslint";
+import rule = require("../../../lib/rules/require-v-global-argument");
const tester = new RuleTester({
- parser: require.resolve("vue-eslint-parser"),
- parserOptions: {
- ecmaVersion: 2019,
- sourceType: "module",
- },
-})
+ parser: require.resolve("vue-eslint-parser"),
+ parserOptions: {
+ ecmaVersion: 2019,
+ sourceType: "module",
+ },
+});
tester.run("require-v-global-argument", rule as any, {
- valid: [
- `
+ valid: [
+ `
sample
`,
- ],
- invalid: [
- {
- code: `
+ ],
+ invalid: [
+ {
+ code: `
sample
`,
- errors: [
- {
- message:
- "Need to pass argument to the `::v-global` pseudo-element.",
- line: 4,
- column: 13,
- endLine: 4,
- endColumn: 23,
- },
- {
- message:
- "Need to pass argument to the `::v-global` pseudo-element.",
- line: 5,
- column: 13,
- endLine: 5,
- endColumn: 25,
- },
- ],
+ errors: [
+ {
+ message: "Need to pass argument to the `::v-global` pseudo-element.",
+ line: 4,
+ column: 13,
+ endLine: 4,
+ endColumn: 23,
},
- ],
-})
+ {
+ message: "Need to pass argument to the `::v-global` pseudo-element.",
+ line: 5,
+ column: 13,
+ endLine: 5,
+ endColumn: 25,
+ },
+ ],
+ },
+ ],
+});
diff --git a/tests/lib/rules/require-v-slotted-argument.ts b/tests/lib/rules/require-v-slotted-argument.ts
index 34b2da5d..c16236fb 100644
--- a/tests/lib/rules/require-v-slotted-argument.ts
+++ b/tests/lib/rules/require-v-slotted-argument.ts
@@ -1,50 +1,48 @@
-import { RuleTester } from "eslint"
-import rule = require("../../../lib/rules/require-v-slotted-argument")
+import { RuleTester } from "eslint";
+import rule = require("../../../lib/rules/require-v-slotted-argument");
const tester = new RuleTester({
- parser: require.resolve("vue-eslint-parser"),
- parserOptions: {
- ecmaVersion: 2019,
- sourceType: "module",
- },
-})
+ parser: require.resolve("vue-eslint-parser"),
+ parserOptions: {
+ ecmaVersion: 2019,
+ sourceType: "module",
+ },
+});
tester.run("require-v-slotted-argument", rule as any, {
- valid: [
- `
+ valid: [
+ `
sample
`,
- ],
- invalid: [
- {
- code: `
+ ],
+ invalid: [
+ {
+ code: `
sample
`,
- errors: [
- {
- message:
- "Need to pass argument to the `::v-slotted` pseudo-element.",
- line: 4,
- column: 23,
- endLine: 4,
- endColumn: 34,
- },
- {
- message:
- "Need to pass argument to the `::v-slotted` pseudo-element.",
- line: 5,
- column: 23,
- endLine: 5,
- endColumn: 36,
- },
- ],
+ errors: [
+ {
+ message: "Need to pass argument to the `::v-slotted` pseudo-element.",
+ line: 4,
+ column: 23,
+ endLine: 4,
+ endColumn: 34,
},
- ],
-})
+ {
+ message: "Need to pass argument to the `::v-slotted` pseudo-element.",
+ line: 5,
+ column: 23,
+ endLine: 5,
+ endColumn: 36,
+ },
+ ],
+ },
+ ],
+});
diff --git a/tests/lib/styles/parser/index.ts b/tests/lib/styles/parser/index.ts
index c30250e3..23667eac 100644
--- a/tests/lib/styles/parser/index.ts
+++ b/tests/lib/styles/parser/index.ts
@@ -1,18 +1,18 @@
-import assert from "assert"
+import assert from "assert";
-import fs from "fs"
-import path from "path"
+import fs from "fs";
+import path from "path";
-import css from "postcss"
-import scss from "postcss-scss"
-import stylus from "postcss-styl"
+import css from "postcss";
+import scss from "postcss-scss";
+import stylus from "postcss-styl";
-import { getStyleFixtureResults, writeFixture } from "../test-utils"
+import { getStyleFixtureResults, writeFixture } from "../test-utils";
import type {
- VCSSNode,
- VCSSSelectorNode,
- VCSSAtRule,
-} from "../../../../lib/styles/ast"
+ VCSSNode,
+ VCSSSelectorNode,
+ VCSSAtRule,
+} from "../../../../lib/styles/ast";
// function stringify(node: any, stringifier: any) {
// let semicolon = true
@@ -27,16 +27,16 @@ import type {
// }
const STRINGIFYS = {
- scss(node: any, builder: any) {
- scss.stringify(node, builder)
- },
- css(node: any, builder: any) {
- css.stringify(node, builder)
- },
- stylus(node: any, builder: any) {
- stylus.stringify(node, builder)
- },
-}
+ scss(node: any, builder: any) {
+ scss.stringify(node, builder);
+ },
+ css(node: any, builder: any) {
+ css.stringify(node, builder);
+ },
+ stylus(node: any, builder: any) {
+ stylus.stringify(node, builder);
+ },
+};
/**
* Remove `parent` proeprties from the given AST.
@@ -45,256 +45,241 @@ const STRINGIFYS = {
* @returns {any} The value of the key to output.
*/
function replacer(key: string, value: any): any {
- if (key === "parent" || key === "node" || key === "lang") {
- return undefined
- }
- return value
+ if (key === "parent" || key === "node" || key === "lang") {
+ return undefined;
+ }
+ return value;
}
function simpleReplacer(key: string, value: any): any {
- if (key === "parent" || key === "node" || key === "lang") {
- return undefined
- }
- if (key === "loc" || key === "range" || key === "start" || key === "end") {
- return undefined
- }
- return value
+ if (key === "parent" || key === "node" || key === "lang") {
+ return undefined;
+ }
+ if (key === "loc" || key === "range" || key === "start" || key === "end") {
+ return undefined;
+ }
+ return value;
}
describe("CSS Nodes Test.", () => {
- for (const { name, style, source, dir } of getStyleFixtureResults()) {
- describe(`'styles/fixtures/${name}/source.vue'`, () => {
- it("should be parsed to valid location.", () => {
- if (!style.cssNode) {
- throw new Error("invalid")
- }
- if (style.cssNode.errors.length) {
- return
- }
- checkCSSNodeLocations(source, style.cssNode, style.lang)
- })
- it("should be parsed to valid AST.", () => {
- const resultPath = path.join(dir, "ast.json")
+ for (const { name, style, source, dir } of getStyleFixtureResults()) {
+ describe(`'styles/fixtures/${name}/source.vue'`, () => {
+ it("should be parsed to valid location.", () => {
+ if (!style.cssNode) {
+ throw new Error("invalid");
+ }
+ if (style.cssNode.errors.length) {
+ return;
+ }
+ checkCSSNodeLocations(source, style.cssNode, style.lang);
+ });
+ it("should be parsed to valid AST.", () => {
+ const resultPath = path.join(dir, "ast.json");
- const actual = JSON.stringify(style.cssNode, replacer, 4)
+ const actual = JSON.stringify(style.cssNode, replacer, 4);
- try {
- const expected = fs.readFileSync(resultPath, "utf8")
+ try {
+ const expected = fs.readFileSync(resultPath, "utf8");
- assert.strictEqual(actual, expected)
- } catch (e) {
- writeFixture(resultPath, actual)
- throw e
- }
- })
- it("should be parsed to valid simple AST.", () => {
- const resultPath = path.join(dir, "ast.json")
+ assert.strictEqual(actual, expected);
+ } catch (e) {
+ writeFixture(resultPath, actual);
+ throw e;
+ }
+ });
+ it("should be parsed to valid simple AST.", () => {
+ const resultPath = path.join(dir, "ast.json");
- const actual = JSON.stringify(style.cssNode, simpleReplacer, 4)
+ const actual = JSON.stringify(style.cssNode, simpleReplacer, 4);
- const expected = JSON.stringify(
- JSON.parse(fs.readFileSync(resultPath, "utf8")),
- simpleReplacer,
- 4,
- )
+ const expected = JSON.stringify(
+ JSON.parse(fs.readFileSync(resultPath, "utf8")),
+ simpleReplacer,
+ 4
+ );
- assert.strictEqual(actual, expected)
- })
- it("should be copied to valid AST.", () => {
- const resultPath = path.join(dir, "ast.json")
+ assert.strictEqual(actual, expected);
+ });
+ it("should be copied to valid AST.", () => {
+ const resultPath = path.join(dir, "ast.json");
- const actual = JSON.stringify(
- deepCopy(style.cssNode),
- replacer,
- 4,
- )
+ const actual = JSON.stringify(deepCopy(style.cssNode), replacer, 4);
- const expected = fs.readFileSync(resultPath, "utf8")
+ const expected = fs.readFileSync(resultPath, "utf8");
- assert.strictEqual(actual, expected)
- })
- })
- }
-})
+ assert.strictEqual(actual, expected);
+ });
+ });
+ }
+});
// eslint-disable-next-line complexity -- test
function checkCSSNodeLocations(
- code: string,
- node: VCSSNode | VCSSSelectorNode,
- lang: string,
+ code: string,
+ node: VCSSNode | VCSSSelectorNode,
+ lang: string
) {
- if (node.node) {
- let rangeText = code.slice(...node.range)
- let postcssText = (node.node as any).toString((STRINGIFYS as any)[lang])
- if (node.type === "VCSSSelector" || node.type === "VCSSClassSelector") {
- postcssText = postcssText.replace(
- /\s*\/\*(?![\s\S]*\*\/[\s\S]*\/\*)([\s\S]*?)\*\/\s*$/u,
- "",
- )
- postcssText = postcssText.replace(/^\s*\/\*([\s\S]*?)\*\/\s*/u, "")
- postcssText = postcssText.replace(/^\s*\/\/([^\n]*)\s*/u, "")
- // eslint-disable-next-line regexp/no-super-linear-backtracking -- for test
- postcssText = postcssText.replace(/\s*\/\/([^\n]*)\s*$/u, "")
- } else if (node.type === "VCSSSelectorCombinator") {
- postcssText = postcssText.replace(
- /\/\*(?![\s\S]*\*\/[\s\S]*\/\*)([\s\S]*?)\*\/\s*$/u,
- "",
- )
- postcssText = postcssText.replace(/^\s*\/\*([\s\S]*?)\*\//u, "")
- // eslint-disable-next-line regexp/no-super-linear-backtracking -- for test
- postcssText = postcssText.replace(/\/\/([^\n]*)\s*$/u, "")
- // eslint-disable-next-line regexp/no-super-linear-backtracking -- for test
- postcssText = postcssText.replace(/\s*\/\/([^\n]*)\s*$/u, "")
- }
- if (
- node.type === "VCSSSelectorCombinator" &&
- postcssText.trim() === ""
- ) {
- // noop
- } else if (node.type === "VCSSNestingSelector") {
- rangeText = rangeText.trim()
- postcssText = postcssText.trim()
- } else if (node.type === "VCSSStyleSheet") {
- // noop
- } else if (node.type === "VCSSDeclarationProperty") {
- rangeText = rangeText.replace(/^\*|\s*;\s*$/g, "")
- postcssText = postcssText.trim()
- } else if (node.type === "VCSSAtRule") {
- rangeText = rangeText.replace(/\s*;\s*$/g, "")
- postcssText = postcssText.trim()
- } else {
- postcssText = postcssText.trim()
- }
- assert.strictEqual(
- `${node.type}:\n${rangeText}`,
- `${node.type}:\n${postcssText}`,
- )
+ if (node.node) {
+ let rangeText = code.slice(...node.range);
+ let postcssText = (node.node as any).toString((STRINGIFYS as any)[lang]);
+ if (node.type === "VCSSSelector" || node.type === "VCSSClassSelector") {
+ postcssText = postcssText.replace(
+ /\s*\/\*(?![\s\S]*\*\/[\s\S]*\/\*)([\s\S]*?)\*\/\s*$/u,
+ ""
+ );
+ postcssText = postcssText.replace(/^\s*\/\*([\s\S]*?)\*\/\s*/u, "");
+ postcssText = postcssText.replace(/^\s*\/\/([^\n]*)\s*/u, "");
+ // eslint-disable-next-line regexp/no-super-linear-backtracking -- for test
+ postcssText = postcssText.replace(/\s*\/\/([^\n]*)\s*$/u, "");
+ } else if (node.type === "VCSSSelectorCombinator") {
+ postcssText = postcssText.replace(
+ /\/\*(?![\s\S]*\*\/[\s\S]*\/\*)([\s\S]*?)\*\/\s*$/u,
+ ""
+ );
+ postcssText = postcssText.replace(/^\s*\/\*([\s\S]*?)\*\//u, "");
+ // eslint-disable-next-line regexp/no-super-linear-backtracking -- for test
+ postcssText = postcssText.replace(/\/\/([^\n]*)\s*$/u, "");
+ // eslint-disable-next-line regexp/no-super-linear-backtracking -- for test
+ postcssText = postcssText.replace(/\s*\/\/([^\n]*)\s*$/u, "");
}
- if (node.type === "VCSSStyleSheet") {
- if (node.errors.length) {
- return
- }
- const text = code.slice(...node.range)
- assert.strictEqual(text, (node.node as any).source.input.css)
- } else if (node.type === "VCSSStyleRule") {
- const text = code.slice(...node.range)
- assert.strictEqual(
- text.slice(0, node.rawSelectorText.length),
- node.rawSelectorText,
- )
- if (lang !== "stylus") {
- assert.strictEqual(text[text.length - 1], "}")
- }
- for (const n of node.selectors) {
- checkCSSNodeLocations(code, n, lang)
- }
+ if (node.type === "VCSSSelectorCombinator" && postcssText.trim() === "") {
+ // noop
+ } else if (node.type === "VCSSNestingSelector") {
+ rangeText = rangeText.trim();
+ postcssText = postcssText.trim();
+ } else if (node.type === "VCSSStyleSheet") {
+ // noop
} else if (node.type === "VCSSDeclarationProperty") {
- const text = code.slice(...node.range)
- assert.ok(text.includes(node.property), "node.property")
- assert.ok(text.includes(node.value), "node.value")
- if (text.indexOf(node.value) !== text.length - node.value.length) {
- assert.strictEqual(text[text.length - 1], ";")
- }
+ rangeText = rangeText.replace(/^\*|\s*;\s*$/g, "");
+ postcssText = postcssText.trim();
} else if (node.type === "VCSSAtRule") {
- const text = code.slice(...node.range)
- const expected =
- lang !== "stylus"
- ? `@${node.name}`
- : `${(node.node as any).raws.identifier ?? "@"}${node.name}`
- assert.strictEqual(text.slice(0, expected.length), expected)
- if (lang !== "stylus") {
- const last = text[text.length - 1]
- assert.ok(
- last === "}" || last === ";",
- `act:${text[text.length - 1]}`,
- )
- }
- } else if (node.type === "VCSSSelector") {
- const parent = node.parent as VCSSAtRule
-
- if (parent.selectors) {
- // parent===VCSSStyleRule
- const selectorTexts = parent.selectors.map((s) =>
- code.slice(...s.range),
- )
- const rawSelectorText = parent.rawSelectorText as string
- let index = 0
- for (const selectorText of selectorTexts) {
- const idx = rawSelectorText.indexOf(selectorText, index)
- if (idx >= 0) {
- assert.strictEqual(
- selectorText,
- rawSelectorText.slice(idx, idx + selectorText.length),
- )
- index = idx + selectorText.length
- } else {
- assert.strictEqual(
- selectorText,
- rawSelectorText.slice(
- index,
- index + selectorText.length,
- ),
- )
- }
- }
- }
- } else if (
- node.type === "VCSSTypeSelector" ||
- node.type === "VCSSIDSelector" ||
- node.type === "VCSSClassSelector" ||
- node.type === "VCSSUniversalSelector" ||
- node.type === "VCSSAttributeSelector" ||
- node.type === "VCSSSelectorCombinator"
- ) {
- const text = code.slice(...node.range)
+ rangeText = rangeText.replace(/\s*;\s*$/g, "");
+ postcssText = postcssText.trim();
+ } else {
+ postcssText = postcssText.trim();
+ }
+ assert.strictEqual(
+ `${node.type}:\n${rangeText}`,
+ `${node.type}:\n${postcssText}`
+ );
+ }
+ if (node.type === "VCSSStyleSheet") {
+ if (node.errors.length) {
+ return;
+ }
+ const text = code.slice(...node.range);
+ assert.strictEqual(text, (node.node as any).source.input.css);
+ } else if (node.type === "VCSSStyleRule") {
+ const text = code.slice(...node.range);
+ assert.strictEqual(
+ text.slice(0, node.rawSelectorText.length),
+ node.rawSelectorText
+ );
+ if (lang !== "stylus") {
+ assert.strictEqual(text[text.length - 1], "}");
+ }
+ for (const n of node.selectors) {
+ checkCSSNodeLocations(code, n, lang);
+ }
+ } else if (node.type === "VCSSDeclarationProperty") {
+ const text = code.slice(...node.range);
+ assert.ok(text.includes(node.property), "node.property");
+ assert.ok(text.includes(node.value), "node.value");
+ if (text.indexOf(node.value) !== text.length - node.value.length) {
+ assert.strictEqual(text[text.length - 1], ";");
+ }
+ } else if (node.type === "VCSSAtRule") {
+ const text = code.slice(...node.range);
+ const expected =
+ lang !== "stylus"
+ ? `@${node.name}`
+ : `${(node.node as any).raws.identifier ?? "@"}${node.name}`;
+ assert.strictEqual(text.slice(0, expected.length), expected);
+ if (lang !== "stylus") {
+ const last = text[text.length - 1];
+ assert.ok(last === "}" || last === ";", `act:${text[text.length - 1]}`);
+ }
+ } else if (node.type === "VCSSSelector") {
+ const parent = node.parent as VCSSAtRule;
- if (text.trim()) {
- assert.strictEqual(text, node.selector)
+ if (parent.selectors) {
+ // parent===VCSSStyleRule
+ const selectorTexts = parent.selectors.map((s) => code.slice(...s.range));
+ const rawSelectorText = parent.rawSelectorText as string;
+ let index = 0;
+ for (const selectorText of selectorTexts) {
+ const idx = rawSelectorText.indexOf(selectorText, index);
+ if (idx >= 0) {
+ assert.strictEqual(
+ selectorText,
+ rawSelectorText.slice(idx, idx + selectorText.length)
+ );
+ index = idx + selectorText.length;
} else {
- assert.strictEqual(text.trim(), node.selector.trim())
+ assert.strictEqual(
+ selectorText,
+ rawSelectorText.slice(index, index + selectorText.length)
+ );
}
- } else if (node.type === "VCSSNestingSelector") {
- const text = code.slice(...node.range)
- assert.strictEqual(text.trim(), node.selector.trim())
- } else if (node.type === "VCSSSelectorPseudo") {
- const text = code.slice(...node.range)
-
- assert.strictEqual(text.slice(0, node.value.length), node.value)
- } else if (node.type === "VCSSUnknownSelector") {
- const text = code.slice(...node.range)
+ }
+ }
+ } else if (
+ node.type === "VCSSTypeSelector" ||
+ node.type === "VCSSIDSelector" ||
+ node.type === "VCSSClassSelector" ||
+ node.type === "VCSSUniversalSelector" ||
+ node.type === "VCSSAttributeSelector" ||
+ node.type === "VCSSSelectorCombinator"
+ ) {
+ const text = code.slice(...node.range);
- assert.strictEqual(text, node.value)
+ if (text.trim()) {
+ assert.strictEqual(text, node.selector);
} else {
- // Need to add testcase
- console.log(node)
+ assert.strictEqual(text.trim(), node.selector.trim());
}
- if ((node as any).nodes) {
- for (const n of (node as any).nodes) {
- checkCSSNodeLocations(code, n, lang)
- }
+ } else if (node.type === "VCSSNestingSelector") {
+ const text = code.slice(...node.range);
+ assert.strictEqual(text.trim(), node.selector.trim());
+ } else if (node.type === "VCSSSelectorPseudo") {
+ const text = code.slice(...node.range);
+
+ assert.strictEqual(text.slice(0, node.value.length), node.value);
+ } else if (node.type === "VCSSUnknownSelector") {
+ const text = code.slice(...node.range);
+
+ assert.strictEqual(text, node.value);
+ } else {
+ // Need to add testcase
+ console.log(node);
+ }
+ if ((node as any).nodes) {
+ for (const n of (node as any).nodes) {
+ checkCSSNodeLocations(code, n, lang);
}
+ }
}
function deepCopy(node: any) {
- const newNode = node.copy()
- if (newNode.nodes) {
- newNode.nodes = newNode.nodes.map(deepCopy).map((c: any) => {
- c.parent = newNode
- return c
- })
- }
- if (newNode.comments) {
- newNode.comments = newNode.comments.map(deepCopy).map((c: any) => {
- c.parent = newNode
- return c
- })
- }
- if (newNode.selectors) {
- newNode.selectors = newNode.selectors.map(deepCopy).map((c: any) => {
- c.parent = newNode
- return c
- })
- }
+ const newNode = node.copy();
+ if (newNode.nodes) {
+ newNode.nodes = newNode.nodes.map(deepCopy).map((c: any) => {
+ c.parent = newNode;
+ return c;
+ });
+ }
+ if (newNode.comments) {
+ newNode.comments = newNode.comments.map(deepCopy).map((c: any) => {
+ c.parent = newNode;
+ return c;
+ });
+ }
+ if (newNode.selectors) {
+ newNode.selectors = newNode.selectors.map(deepCopy).map((c: any) => {
+ c.parent = newNode;
+ return c;
+ });
+ }
- return newNode
+ return newNode;
}
diff --git a/tests/lib/styles/selectors/index.ts b/tests/lib/styles/selectors/index.ts
index 83fcbb4b..980239c3 100644
--- a/tests/lib/styles/selectors/index.ts
+++ b/tests/lib/styles/selectors/index.ts
@@ -1,11 +1,11 @@
-import assert from "assert"
+import assert from "assert";
-import fs from "fs"
-import path from "path"
+import fs from "fs";
+import path from "path";
-import { getStyleFixtureResults, writeFixture } from "../test-utils"
-import { getResolvedSelectors } from "../../../../lib/styles/selectors"
-import type { ValidStyleContext } from "../../../../lib/styles/context"
+import { getStyleFixtureResults, writeFixture } from "../test-utils";
+import { getResolvedSelectors } from "../../../../lib/styles/selectors";
+import type { ValidStyleContext } from "../../../../lib/styles/context";
/**
* Remove `parent` proeprties from the given AST.
@@ -14,65 +14,65 @@ import type { ValidStyleContext } from "../../../../lib/styles/context"
* @returns {any} The value of the key to output.
*/
function replacer(key: string, value: any): any {
- if (key === "parent" || key === "node" || key === "lang") {
- return undefined
- }
- return value
+ if (key === "parent" || key === "node" || key === "lang") {
+ return undefined;
+ }
+ return value;
}
describe("CSS Selectors Test.", () => {
- for (const { name, style, dir } of getStyleFixtureResults()) {
- describe(`'styles/fixtures/${name}/source.vue'`, () => {
- it("should be parsed to valid selectors.", () => {
- const resultPath = path.join(dir, "selectors.json")
+ for (const { name, style, dir } of getStyleFixtureResults()) {
+ describe(`'styles/fixtures/${name}/source.vue'`, () => {
+ it("should be parsed to valid selectors.", () => {
+ const resultPath = path.join(dir, "selectors.json");
- const actual = JSON.stringify(
- getResolvedSelectors(style as ValidStyleContext).map(
- (r) => r.selector,
- ),
- replacer,
- 4,
- )
+ const actual = JSON.stringify(
+ getResolvedSelectors(style as ValidStyleContext).map(
+ (r) => r.selector
+ ),
+ replacer,
+ 4
+ );
- try {
- const expected = fs.readFileSync(resultPath, "utf8")
+ try {
+ const expected = fs.readFileSync(resultPath, "utf8");
- assert.strictEqual(actual, expected)
- } catch (e) {
- writeFixture(resultPath, actual)
- throw e
- }
- })
- it("should be parsed to valid selectors text.", () => {
- const resultPath = path.join(dir, "selectors-text.json")
+ assert.strictEqual(actual, expected);
+ } catch (e) {
+ writeFixture(resultPath, actual);
+ throw e;
+ }
+ });
+ it("should be parsed to valid selectors text.", () => {
+ const resultPath = path.join(dir, "selectors-text.json");
- const actual = JSON.stringify(
- getResolvedSelectors(style as ValidStyleContext).map((r) =>
- // eslint-disable-next-line max-nested-callbacks -- test
- r.selector.map((s) => s.selector),
- ),
- replacer,
- 4,
- )
+ const actual = JSON.stringify(
+ getResolvedSelectors(style as ValidStyleContext).map((r) =>
+ // eslint-disable-next-line max-nested-callbacks -- test
+ r.selector.map((s) => s.selector)
+ ),
+ replacer,
+ 4
+ );
- try {
- const expected = fs.readFileSync(resultPath, "utf8")
+ try {
+ const expected = fs.readFileSync(resultPath, "utf8");
- assert.strictEqual(actual, expected)
- } catch (e) {
- writeFixture(resultPath, actual)
- throw e
- }
- })
- it("AST should not be changed.", () => {
- const resultPath = path.join(dir, "ast.json")
+ assert.strictEqual(actual, expected);
+ } catch (e) {
+ writeFixture(resultPath, actual);
+ throw e;
+ }
+ });
+ it("AST should not be changed.", () => {
+ const resultPath = path.join(dir, "ast.json");
- const actual = JSON.stringify(style.cssNode, replacer, 4)
+ const actual = JSON.stringify(style.cssNode, replacer, 4);
- const expected = fs.readFileSync(resultPath, "utf8")
+ const expected = fs.readFileSync(resultPath, "utf8");
- assert.strictEqual(actual, expected)
- })
- })
- }
-})
+ assert.strictEqual(actual, expected);
+ });
+ });
+ }
+});
diff --git a/tests/lib/styles/selectors/query.ts b/tests/lib/styles/selectors/query.ts
index 89e95386..e79dd5ca 100644
--- a/tests/lib/styles/selectors/query.ts
+++ b/tests/lib/styles/selectors/query.ts
@@ -1,29 +1,29 @@
-import assert from "assert"
+import assert from "assert";
-import fs from "fs"
-import path from "path"
+import fs from "fs";
+import path from "path";
-import { createQueryContext } from "../../../../lib/styles/selectors/query"
-import { getResolvedSelectors } from "../../../../lib/styles/selectors"
+import { createQueryContext } from "../../../../lib/styles/selectors/query";
+import { getResolvedSelectors } from "../../../../lib/styles/selectors";
import {
- getStyleFixtureResults,
- writeFixture,
- deleteFixture,
- isExistsPath,
-} from "../test-utils"
-import type { AST, RuleContext, VDirectiveKey } from "../../../../lib/types"
+ getStyleFixtureResults,
+ writeFixture,
+ deleteFixture,
+ isExistsPath,
+} from "../test-utils";
+import type { AST, RuleContext, VDirectiveKey } from "../../../../lib/types";
import type {
- StyleContext,
- ValidStyleContext,
-} from "../../../../lib/styles/context"
-import { parseQueryOptions } from "../../../../lib/options"
+ StyleContext,
+ ValidStyleContext,
+} from "../../../../lib/styles/context";
+import { parseQueryOptions } from "../../../../lib/options";
import {
- isVDirective,
- isVDirectiveKeyV6,
-} from "../../../../lib/utils/templates"
+ isVDirective,
+ isVDirectiveKeyV6,
+} from "../../../../lib/utils/templates";
-const ROOT = path.join(__dirname, "../fixtures/selectors/query")
+const ROOT = path.join(__dirname, "../fixtures/selectors/query");
/**
* Remove `parent` properties from the given AST.
@@ -32,210 +32,193 @@ const ROOT = path.join(__dirname, "../fixtures/selectors/query")
* @returns {any} The value of the key to output.
*/
function replacer(key: string, value: any): any {
- if (key === "parent" || key === "node" || key === "lang") {
- return undefined
- }
- return value
+ if (key === "parent" || key === "node" || key === "lang") {
+ return undefined;
+ }
+ return value;
}
function queries(style: StyleContext, context: RuleContext) {
- const selectors = getResolvedSelectors(style as ValidStyleContext)
- return selectors
- .map((r) => r.selector)
- .reduce((result, selector) => {
- let q = createQueryContext(context, parseQueryOptions({}))
- for (const node of selector) {
- q = q.queryStep(node)
- }
- const elementsTexts = q.elements.map((e) =>
- buildElementText(e, context),
- )
- const selectorText = selector.map((s) => s.selector).join("")
- result[selectorText] = elementsTexts
- return result
- }, {} as { [key: string]: string[] })
+ const selectors = getResolvedSelectors(style as ValidStyleContext);
+ return selectors
+ .map((r) => r.selector)
+ .reduce((result, selector) => {
+ let q = createQueryContext(context, parseQueryOptions({}));
+ for (const node of selector) {
+ q = q.queryStep(node);
+ }
+ const elementsTexts = q.elements.map((e) => buildElementText(e, context));
+ const selectorText = selector.map((s) => s.selector).join("");
+ result[selectorText] = elementsTexts;
+ return result;
+ }, {} as { [key: string]: string[] });
}
function reverseQueries(style: StyleContext, context: RuleContext) {
- const selectors = getResolvedSelectors(style as ValidStyleContext)
- return selectors
- .map((r) => r.selector)
- .reduce((result, selector) => {
- const document = createQueryContext(context, parseQueryOptions({}))
- const elementQueries = document.split()
- const elementsTexts = elementQueries
- .filter((elementQuery) => {
- // Set dummy document
- ;(elementQuery as any).document = elementQuery
- ;(elementQuery as any).context = (document as any).context
- ;(elementQuery as any).options = (document as any).options
- ;(elementQuery as any).docsModifiers = (
- document as any
- ).docsModifiers
- let q = elementQuery
- for (let index = selector.length - 1; index >= 0; index--) {
- q = q.reverseQueryStep(selector[index])
- }
- return Boolean(q.elements.length)
- })
- .map((elementQuery) => elementQuery.elements[0])
- .map((e) => buildElementText(e, context))
- const selectorText = selector.map((s) => s.selector).join("")
- result[selectorText] = elementsTexts
- return result
- }, {} as { [key: string]: string[] })
+ const selectors = getResolvedSelectors(style as ValidStyleContext);
+ return selectors
+ .map((r) => r.selector)
+ .reduce((result, selector) => {
+ const document = createQueryContext(context, parseQueryOptions({}));
+ const elementQueries = document.split();
+ const elementsTexts = elementQueries
+ .filter((elementQuery) => {
+ // Set dummy document
+ (elementQuery as any).document = elementQuery;
+ (elementQuery as any).context = (document as any).context;
+ (elementQuery as any).options = (document as any).options;
+ (elementQuery as any).docsModifiers = (document as any).docsModifiers;
+ let q = elementQuery;
+ for (let index = selector.length - 1; index >= 0; index--) {
+ q = q.reverseQueryStep(selector[index]);
+ }
+ return Boolean(q.elements.length);
+ })
+ .map((elementQuery) => elementQuery.elements[0])
+ .map((e) => buildElementText(e, context));
+ const selectorText = selector.map((s) => s.selector).join("");
+ result[selectorText] = elementsTexts;
+ return result;
+ }, {} as { [key: string]: string[] });
}
function buildElementText(e: AST.VElement, context: RuleContext): string {
- const id = getAttrText(e, "id", context)
- const className = getAttrText(e, "class", context)
- const idText = id
- ? `#${id.type === "value" ? id.value : `{${id.value}}`}`
- : ""
- const classText = className
- ? `.${
- className.type === "value"
- ? className.value.split(/\s+/u).join(".")
- : `{${className.value}}`
- }`
- : ""
- const text = `${e.name}${idText}${classText}`
- if (
- e.parent &&
- e.parent.parent &&
- e.parent.parent.parent // e.parent.parent === tempalte
- ) {
- return `${buildElementText(e.parent, context)}>${text}`
- }
- return text
+ const id = getAttrText(e, "id", context);
+ const className = getAttrText(e, "class", context);
+ const idText = id
+ ? `#${id.type === "value" ? id.value : `{${id.value}}`}`
+ : "";
+ const classText = className
+ ? `.${
+ className.type === "value"
+ ? className.value.split(/\s+/u).join(".")
+ : `{${className.value}}`
+ }`
+ : "";
+ const text = `${e.name}${idText}${classText}`;
+ if (
+ e.parent &&
+ e.parent.parent &&
+ e.parent.parent.parent // e.parent.parent === tempalte
+ ) {
+ return `${buildElementText(e.parent, context)}>${text}`;
+ }
+ return text;
}
// eslint-disable-next-line complexity -- test
function getAttrText(
- element: AST.VElement,
- name: string,
- context: RuleContext,
+ element: AST.VElement,
+ name: string,
+ context: RuleContext
) {
- const { startTag } = element
- for (const attr of startTag.attributes) {
- if (!isVDirective(attr)) {
- const { key, value } = attr
- if (key.name === name) {
- return {
- type: "value",
- value: (value && value.value) || "",
- }
- }
- } else {
- const key = attr.key as VDirectiveKey
- const { value } = attr
- if (isVDirectiveKeyV6(key)) {
- if (key.name.name !== "bind") {
- continue
- }
- if (
- key.argument &&
- (key.argument.type !== "VIdentifier" ||
- key.argument.name !== name)
- ) {
- continue
- }
- return {
- type: "expr",
- value:
- (value &&
- value.expression &&
- context
- .getSourceCode()
- .getText(value.expression)) ||
- "",
- }
- }
- // vue-eslint-parser@<6.0.0
- if (key.name !== "bind") {
- continue
- }
- if (key.argument !== name) {
- continue
- }
- return {
- type: "expr",
- value:
- (value &&
- value.expression &&
- context.getSourceCode().getText(value.expression)) ||
- "",
- }
+ const { startTag } = element;
+ for (const attr of startTag.attributes) {
+ if (!isVDirective(attr)) {
+ const { key, value } = attr;
+ if (key.name === name) {
+ return {
+ type: "value",
+ value: (value && value.value) || "",
+ };
+ }
+ } else {
+ const key = attr.key as VDirectiveKey;
+ const { value } = attr;
+ if (isVDirectiveKeyV6(key)) {
+ if (key.name.name !== "bind") {
+ continue;
}
+ if (
+ key.argument &&
+ (key.argument.type !== "VIdentifier" || key.argument.name !== name)
+ ) {
+ continue;
+ }
+ return {
+ type: "expr",
+ value:
+ (value &&
+ value.expression &&
+ context.getSourceCode().getText(value.expression)) ||
+ "",
+ };
+ }
+ // vue-eslint-parser@<6.0.0
+ if (key.name !== "bind") {
+ continue;
+ }
+ if (key.argument !== name) {
+ continue;
+ }
+ return {
+ type: "expr",
+ value:
+ (value &&
+ value.expression &&
+ context.getSourceCode().getText(value.expression)) ||
+ "",
+ };
}
- return null
+ }
+ return null;
}
describe("CSS Query Test.", () => {
- for (const { name, style, context, dir } of getStyleFixtureResults(ROOT)) {
- describe(`'styles/selectors/query/fixtures/${name}/source.vue'`, () => {
- it("should be query results to valid ressults.", () => {
- const resultPath = path.join(dir, "query-result.json")
-
- const actual = JSON.stringify(
- queries(style, context),
- replacer,
- 4,
- )
-
- try {
- const expected = fs.readFileSync(resultPath, "utf8")
-
- assert.strictEqual(actual, expected)
- } catch (e) {
- writeFixture(resultPath, actual)
- throw e
- }
- })
-
- it("should be reverse query results to valid ressults.", () => {
- const resultPathNormal = path.join(dir, "query-result.json")
- const resultPathReverse = path.join(
- dir,
- "reverse-query-result.json",
- )
-
- const actual = JSON.stringify(
- reverseQueries(style, context),
- replacer,
- 4,
- )
- const expectedNormal = fs.readFileSync(resultPathNormal, "utf8")
- if (isExistsPath(resultPathReverse)) {
- let expectedReverse = null
- try {
- expectedReverse = fs.readFileSync(
- resultPathReverse,
- "utf8",
- )
- assert.strictEqual(actual, expectedReverse)
- } catch (e) {
- writeFixture(resultPathReverse, actual)
- throw e
- }
-
- try {
- assert.notStrictEqual(expectedReverse, expectedNormal)
- } catch (e) {
- if (expectedReverse) {
- deleteFixture(resultPathReverse)
- }
- throw e
- }
- } else {
- try {
- assert.strictEqual(actual, expectedNormal)
- } catch (e) {
- writeFixture(resultPathReverse, actual)
- throw e
- }
- }
- })
- })
- }
-})
+ for (const { name, style, context, dir } of getStyleFixtureResults(ROOT)) {
+ describe(`'styles/selectors/query/fixtures/${name}/source.vue'`, () => {
+ it("should be query results to valid ressults.", () => {
+ const resultPath = path.join(dir, "query-result.json");
+
+ const actual = JSON.stringify(queries(style, context), replacer, 4);
+
+ try {
+ const expected = fs.readFileSync(resultPath, "utf8");
+
+ assert.strictEqual(actual, expected);
+ } catch (e) {
+ writeFixture(resultPath, actual);
+ throw e;
+ }
+ });
+
+ it("should be reverse query results to valid ressults.", () => {
+ const resultPathNormal = path.join(dir, "query-result.json");
+ const resultPathReverse = path.join(dir, "reverse-query-result.json");
+
+ const actual = JSON.stringify(
+ reverseQueries(style, context),
+ replacer,
+ 4
+ );
+ const expectedNormal = fs.readFileSync(resultPathNormal, "utf8");
+ if (isExistsPath(resultPathReverse)) {
+ let expectedReverse = null;
+ try {
+ expectedReverse = fs.readFileSync(resultPathReverse, "utf8");
+ assert.strictEqual(actual, expectedReverse);
+ } catch (e) {
+ writeFixture(resultPathReverse, actual);
+ throw e;
+ }
+
+ try {
+ assert.notStrictEqual(expectedReverse, expectedNormal);
+ } catch (e) {
+ if (expectedReverse) {
+ deleteFixture(resultPathReverse);
+ }
+ throw e;
+ }
+ } else {
+ try {
+ assert.strictEqual(actual, expectedNormal);
+ } catch (e) {
+ writeFixture(resultPathReverse, actual);
+ throw e;
+ }
+ }
+ });
+ });
+ }
+});
diff --git a/tests/lib/styles/test-utils.ts b/tests/lib/styles/test-utils.ts
index 851d6c86..354ab9dd 100644
--- a/tests/lib/styles/test-utils.ts
+++ b/tests/lib/styles/test-utils.ts
@@ -1,104 +1,104 @@
-import eslint from "eslint"
+import eslint from "eslint";
-import fs from "fs"
-import path from "path"
+import fs from "fs";
+import path from "path";
-import type { RuleContext } from "../../../lib/types"
-import type { StyleContext } from "../../../lib/styles/context"
-import { getStyleContexts } from "../../../lib/styles/context"
+import type { RuleContext } from "../../../lib/types";
+import type { StyleContext } from "../../../lib/styles/context";
+import { getStyleContexts } from "../../../lib/styles/context";
-const ROOT = path.join(__dirname, "./fixtures/index")
+const ROOT = path.join(__dirname, "./fixtures/index");
-const ruleId = "test"
+const ruleId = "test";
const config = {
- parser: "vue-eslint-parser",
- parserOptions: { ecmaVersion: 2019, sourceType: "module" },
- rules: {
- [ruleId]: "error",
- },
-}
+ parser: "vue-eslint-parser",
+ parserOptions: { ecmaVersion: 2019, sourceType: "module" },
+ rules: {
+ [ruleId]: "error",
+ },
+};
/**
* Execute eslint
* @param {string} source the source code
*/
function executeLint(
- source: string,
- sourcePath: string,
- _name: string,
+ source: string,
+ sourcePath: string,
+ _name: string
): { style: StyleContext; context: RuleContext } {
- const linter = new eslint.Linter()
- let style: StyleContext | null = null
- let context: RuleContext | null = null
- let err = null
- linter.defineParser("vue-eslint-parser", require("vue-eslint-parser"))
- linter.defineRule(ruleId, {
- create(ctx: RuleContext) {
- try {
- context = ctx
- style = getStyleContexts(ctx)[0]
- } catch (e) {
- err = e
- }
- return {}
- },
- } as any)
- linter.verifyAndFix(source, config as any, sourcePath)
- if (err) {
- throw err
- }
- if (!style || !context) {
- throw new Error("invalid state")
- }
- return { style, context }
+ const linter = new eslint.Linter();
+ let style: StyleContext | null = null;
+ let context: RuleContext | null = null;
+ let err = null;
+ linter.defineParser("vue-eslint-parser", require("vue-eslint-parser"));
+ linter.defineRule(ruleId, {
+ create(ctx: RuleContext) {
+ try {
+ context = ctx;
+ style = getStyleContexts(ctx)[0];
+ } catch (e) {
+ err = e;
+ }
+ return {};
+ },
+ } as any);
+ linter.verifyAndFix(source, config as any, sourcePath);
+ if (err) {
+ throw err;
+ }
+ if (!style || !context) {
+ throw new Error("invalid state");
+ }
+ return { style, context };
}
export function* getStyleFixtureResults(rootDir = ROOT): IterableIterator<{
- name: string
- style: StyleContext
- source: string
- context: RuleContext
- dir: string
+ name: string;
+ style: StyleContext;
+ source: string;
+ context: RuleContext;
+ dir: string;
}> {
- for (const name of fs.readdirSync(rootDir)) {
- if (name === ".DS_Store") {
- continue
- }
- const sourcePath = path.join(rootDir, `${name}/source.vue`)
- const source = fs.readFileSync(sourcePath, "utf8")
-
- const { style, context } = executeLint(source, sourcePath, name)
- yield {
- name,
- style,
- source,
- context,
- dir: path.join(rootDir, `${name}`),
- }
+ for (const name of fs.readdirSync(rootDir)) {
+ if (name === ".DS_Store") {
+ continue;
}
+ const sourcePath = path.join(rootDir, `${name}/source.vue`);
+ const source = fs.readFileSync(sourcePath, "utf8");
+
+ const { style, context } = executeLint(source, sourcePath, name);
+ yield {
+ name,
+ style,
+ source,
+ context,
+ dir: path.join(rootDir, `${name}`),
+ };
+ }
}
export function writeFixture(expectFilepath: string, content: string): void {
- // eslint-disable-next-line no-process-env -- test
- if (process.env.UPDATE_FIXTURE) {
- fs.writeFileSync(expectFilepath, content, "utf8")
- }
+ // eslint-disable-next-line no-process-env -- test
+ if (process.env.UPDATE_FIXTURE) {
+ fs.writeFileSync(expectFilepath, content, "utf8");
+ }
}
export function deleteFixture(filepath: string): void {
- // eslint-disable-next-line no-process-env -- test
- if (process.env.UPDATE_FIXTURE) {
- fs.unlinkSync(filepath)
- }
+ // eslint-disable-next-line no-process-env -- test
+ if (process.env.UPDATE_FIXTURE) {
+ fs.unlinkSync(filepath);
+ }
}
export function isExistsPath(filepath: string): boolean {
- try {
- fs.statSync(filepath)
- return true
- } catch (error: any) {
- if (error.code === "ENOENT") {
- return false
- }
- throw error
+ try {
+ fs.statSync(filepath);
+ return true;
+ } catch (error: any) {
+ if (error.code === "ENOENT") {
+ return false;
}
+ throw error;
+ }
}
diff --git a/tests/lib/utils/rules.ts b/tests/lib/utils/rules.ts
index 70b154c3..548e7082 100644
--- a/tests/lib/utils/rules.ts
+++ b/tests/lib/utils/rules.ts
@@ -1,60 +1,57 @@
-import assert from "assert"
-import path from "path"
-import fs from "fs"
+import assert from "assert";
+import path from "path";
+import fs from "fs";
-import { collectRules, rules as allRules } from "../../../lib/utils/rules"
+import { collectRules, rules as allRules } from "../../../lib/utils/rules";
/**
* @returns {Array} Get the list of rules placed in the directory.
*/
function getDirRules() {
- const rulesRoot = path.resolve(__dirname, "../../../lib/rules")
- const result = fs.readdirSync(rulesRoot)
- const rules: { [key: string]: any } = {}
- for (const name of result) {
- const ruleName = name.replace(/\.ts$/u, "")
- const ruleId = `vue-scoped-css/${ruleName}`
- const rule = require(path.join(rulesRoot, name))
- rules[ruleId] = rule
- }
- return rules
+ const rulesRoot = path.resolve(__dirname, "../../../lib/rules");
+ const result = fs.readdirSync(rulesRoot);
+ const rules: { [key: string]: any } = {};
+ for (const name of result) {
+ const ruleName = name.replace(/\.ts$/u, "");
+ const ruleId = `vue-scoped-css/${ruleName}`;
+ const rule = require(path.join(rulesRoot, name));
+ rules[ruleId] = rule;
+ }
+ return rules;
}
-const dirRules = getDirRules()
+const dirRules = getDirRules();
describe("Check if the struct of all rules is correct", () => {
- it("rule count equals (collectRules)", () => {
- const collect = collectRules()
+ it("rule count equals (collectRules)", () => {
+ const collect = collectRules();
- const deprecatedRules = allRules.filter((r) => r.meta.deprecated)
- assert.ok(
- Object.keys(collect).length + deprecatedRules.length ===
- Object.keys(dirRules).length,
- `Did not equal the number of rules. expect:${
- Object.keys(dirRules).length
- } actual:${Object.keys(collect).length}`,
- )
- })
- it("rule count equals (rules)", () => {
- assert.ok(
- allRules.length === Object.keys(dirRules).length,
- `Did not equal the number of rules. expect:${
- Object.keys(dirRules).length
- } actual:${allRules.length}`,
- )
- })
+ const deprecatedRules = allRules.filter((r) => r.meta.deprecated);
+ assert.ok(
+ Object.keys(collect).length + deprecatedRules.length ===
+ Object.keys(dirRules).length,
+ `Did not equal the number of rules. expect:${
+ Object.keys(dirRules).length
+ } actual:${Object.keys(collect).length}`
+ );
+ });
+ it("rule count equals (rules)", () => {
+ assert.ok(
+ allRules.length === Object.keys(dirRules).length,
+ `Did not equal the number of rules. expect:${
+ Object.keys(dirRules).length
+ } actual:${allRules.length}`
+ );
+ });
- for (const rule of allRules) {
- it(rule.meta.docs?.ruleId || "", () => {
- assert.ok(Boolean(rule.meta.docs.ruleId), "Did not set `ruleId`")
- assert.ok(
- Boolean(rule.meta.docs.ruleName),
- "Did not set `ruleName`",
- )
- assert.ok(
- Boolean(dirRules[rule.meta.docs?.ruleId || ""]),
- "Did not exist rule",
- )
- })
- }
-})
+ for (const rule of allRules) {
+ it(rule.meta.docs?.ruleId || "", () => {
+ assert.ok(Boolean(rule.meta.docs.ruleId), "Did not set `ruleId`");
+ assert.ok(Boolean(rule.meta.docs.ruleName), "Did not set `ruleName`");
+ assert.ok(
+ Boolean(dirRules[rule.meta.docs?.ruleId || ""]),
+ "Did not exist rule"
+ );
+ });
+ }
+});
diff --git a/tests/regressions/reporter.ts b/tests/regressions/reporter.ts
index 3a91a831..1c0c8590 100644
--- a/tests/regressions/reporter.ts
+++ b/tests/regressions/reporter.ts
@@ -1,8 +1,8 @@
-import assert from "assert"
-import plugin from "../../lib/index"
-import eslint from "eslint"
+import assert from "assert";
+import plugin from "../../lib/index";
+import eslint from "eslint";
-type LinterMessages = Partial
+type LinterMessages = Partial;
/**
* Assert the messages
@@ -11,62 +11,62 @@ type LinterMessages = Partial
* @returns {void}
*/
function assertMessages(actual: LinterMessages[], expected: LinterMessages[]) {
- const length = Math.max(actual.length, expected.length)
- const expected2: LinterMessages[] = []
- for (let i = 0; i < length; i++) {
- expected2.push(
- expected[i] ? { ...actual[i], ...expected[i] } : expected[i],
- )
- }
+ const length = Math.max(actual.length, expected.length);
+ const expected2: LinterMessages[] = [];
+ for (let i = 0; i < length; i++) {
+ expected2.push(
+ expected[i] ? { ...actual[i], ...expected[i] } : expected[i]
+ );
+ }
- assert.deepStrictEqual(actual, expected2)
- assert.strictEqual(actual.length, expected.length)
+ assert.deepStrictEqual(actual, expected2);
+ assert.strictEqual(actual.length, expected.length);
}
describe("reporter test", () => {
- it("The report must be valid.", () => {
- const linter = new eslint.Linter()
- const config = {
- parser: "vue-eslint-parser",
- parserOptions: { ecmaVersion: 2015 },
- rules: {
- "vue-scoped-css/no-unused-selector": "error",
- "vue-scoped-css/require-selector-used-inside": "error",
- },
- }
- linter.defineParser("vue-eslint-parser", require("vue-eslint-parser"))
- linter.defineRule(
- "vue-scoped-css/no-unused-selector",
- plugin.rules["no-unused-selector"] as any,
- )
- linter.defineRule(
- "vue-scoped-css/require-selector-used-inside",
- plugin.rules["require-selector-used-inside"] as any,
- )
+ it("The report must be valid.", () => {
+ const linter = new eslint.Linter();
+ const config = {
+ parser: "vue-eslint-parser",
+ parserOptions: { ecmaVersion: 2015 },
+ rules: {
+ "vue-scoped-css/no-unused-selector": "error",
+ "vue-scoped-css/require-selector-used-inside": "error",
+ },
+ };
+ linter.defineParser("vue-eslint-parser", require("vue-eslint-parser"));
+ linter.defineRule(
+ "vue-scoped-css/no-unused-selector",
+ plugin.rules["no-unused-selector"] as any
+ );
+ linter.defineRule(
+ "vue-scoped-css/require-selector-used-inside",
+ plugin.rules["require-selector-used-inside"] as any
+ );
- const messages = linter.verify(
- " ",
- config as any,
- {
- filename: "test.vue",
- },
- )
+ const messages = linter.verify(
+ " ",
+ config as any,
+ {
+ filename: "test.vue",
+ }
+ );
- assertMessages(messages, [
- {
- ruleId: "vue-scoped-css/no-unused-selector",
- column: 44,
- endColumn: 46,
- endLine: 1,
- line: 1,
- },
- {
- ruleId: "vue-scoped-css/require-selector-used-inside",
- column: 44,
- endColumn: 46,
- endLine: 1,
- line: 1,
- },
- ])
- })
-})
+ assertMessages(messages, [
+ {
+ ruleId: "vue-scoped-css/no-unused-selector",
+ column: 44,
+ endColumn: 46,
+ endLine: 1,
+ line: 1,
+ },
+ {
+ ruleId: "vue-scoped-css/require-selector-used-inside",
+ column: 44,
+ endColumn: 46,
+ endLine: 1,
+ line: 1,
+ },
+ ]);
+ });
+});
diff --git a/tools/lib/categories.ts b/tools/lib/categories.ts
index 1001f64a..ca6e1579 100644
--- a/tools/lib/categories.ts
+++ b/tools/lib/categories.ts
@@ -1,45 +1,43 @@
-import { rules } from "../../lib/utils/rules"
-import type { Rule } from "../../lib/types"
+import { rules } from "../../lib/utils/rules";
+import type { Rule } from "../../lib/types";
const categoryTitles = {
- base: "Base Rules (Enabling Plugin)",
- "vue3-recommended": "Recommended for Vue.js 3.x",
- recommended: "Recommended for Vue.js 2.x",
-} as { [key: string]: string }
+ base: "Base Rules (Enabling Plugin)",
+ "vue3-recommended": "Recommended for Vue.js 3.x",
+ recommended: "Recommended for Vue.js 2.x",
+} as { [key: string]: string };
const categoryConfigDescriptions = {
- base: "Enable this plugin using with:",
- "vue3-recommended": "Enforce all the rules in this category with:",
- recommended: "Enforce all the rules in this category with:",
-} as { [key: string]: string }
+ base: "Enable this plugin using with:",
+ "vue3-recommended": "Enforce all the rules in this category with:",
+ recommended: "Enforce all the rules in this category with:",
+} as { [key: string]: string };
-const categoryIds = Object.keys(categoryTitles)
+const categoryIds = Object.keys(categoryTitles);
const categoryRules: { [key: string]: Rule[] } = rules.reduce((obj, rule) => {
- const categoryNames = rule.meta.docs.categories.length
- ? rule.meta.docs.categories
- : ["uncategorized"]
- for (const cat of categoryNames) {
- const categories = obj[cat] || (obj[cat] = [])
- categories.push(rule)
- }
- return obj
-}, {} as { [key: string]: Rule[] })
+ const categoryNames = rule.meta.docs.categories.length
+ ? rule.meta.docs.categories
+ : ["uncategorized"];
+ for (const cat of categoryNames) {
+ const categories = obj[cat] || (obj[cat] = []);
+ categories.push(rule);
+ }
+ return obj;
+}, {} as { [key: string]: Rule[] });
// Throw if no title is defined for a category
for (const categoryId of Object.keys(categoryRules)) {
- if (categoryId !== "uncategorized" && !categoryTitles[categoryId]) {
- throw new Error(
- `Category "${categoryId}" does not have a title defined.`,
- )
- }
+ if (categoryId !== "uncategorized" && !categoryTitles[categoryId]) {
+ throw new Error(`Category "${categoryId}" does not have a title defined.`);
+ }
}
export default categoryIds.map((categoryId) => ({
- categoryId,
- title: categoryTitles[categoryId],
- configDescription: categoryConfigDescriptions[categoryId],
- rules: (categoryRules[categoryId] || []).filter(
- (rule) => !rule.meta.deprecated,
- ),
-}))
+ categoryId,
+ title: categoryTitles[categoryId],
+ configDescription: categoryConfigDescriptions[categoryId],
+ rules: (categoryRules[categoryId] || []).filter(
+ (rule) => !rule.meta.deprecated
+ ),
+}));
// .filter(category => category.rules.length >= 1)
diff --git a/tools/lib/load-configs.ts b/tools/lib/load-configs.ts
index 94bdd9b2..c498de7f 100644
--- a/tools/lib/load-configs.ts
+++ b/tools/lib/load-configs.ts
@@ -1,50 +1,50 @@
-import path from "path"
-import fs from "fs"
-import { isDefined } from "../../lib/utils/utils"
+import path from "path";
+import fs from "fs";
+import { isDefined } from "../../lib/utils/utils";
type Config = {
- name: string
- configId: string
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- tools
- config: any
- path: string
- extends: Config[]
-}
+ name: string;
+ configId: string;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- tools
+ config: any;
+ path: string;
+ extends: Config[];
+};
/**
* Get the all configs
* @returns {Array} The all configs
*/
function readConfigs(): Config[] {
- const configsRoot = path.resolve(__dirname, "../../lib/configs")
- const result = fs.readdirSync(configsRoot)
- const configs = []
- for (const name of result) {
- const configName = name.replace(/\.ts$/u, "")
- const configId = `plugin:vue-scoped-css/${configName}`
- const configPath = require.resolve(path.join(configsRoot, name))
+ const configsRoot = path.resolve(__dirname, "../../lib/configs");
+ const result = fs.readdirSync(configsRoot);
+ const configs = [];
+ for (const name of result) {
+ const configName = name.replace(/\.ts$/u, "");
+ const configId = `plugin:vue-scoped-css/${configName}`;
+ const configPath = require.resolve(path.join(configsRoot, name));
- const config = require(configPath)
- configs.push({
- name: configName,
- configId,
- config,
- path: configPath,
- extends: [],
- })
- }
- return configs
+ const config = require(configPath);
+ configs.push({
+ name: configName,
+ configId,
+ config,
+ path: configPath,
+ extends: [],
+ });
+ }
+ return configs;
}
-export const configs = readConfigs()
+export const configs = readConfigs();
for (const config of configs) {
- const extendsList: string[] = !config.config.extends
- ? []
- : Array.isArray(config.config.extends)
- ? config.config.extends
- : [config.config.extends]
- config.extends = extendsList
- .map((p) => configs.find((c) => c.path === p))
- .filter(isDefined)
+ const extendsList: string[] = !config.config.extends
+ ? []
+ : Array.isArray(config.config.extends)
+ ? config.config.extends
+ : [config.config.extends];
+ config.extends = extendsList
+ .map((p) => configs.find((c) => c.path === p))
+ .filter(isDefined);
}
diff --git a/tools/lib/load-rules.ts b/tools/lib/load-rules.ts
index b4551c2f..bbe5a296 100644
--- a/tools/lib/load-rules.ts
+++ b/tools/lib/load-rules.ts
@@ -1,26 +1,26 @@
-import path from "path"
-import fs from "fs"
+import path from "path";
+import fs from "fs";
/**
* Get the all rules
* @returns {Array} The all rules
*/
function readRules() {
- // const rulesDistRoot = path.resolve(__dirname, "../../dist/rules")
- const rulesLibRoot = path.resolve(__dirname, "../../lib/rules")
- const result = fs.readdirSync(rulesLibRoot)
- const rules = []
- for (const name of result) {
- const ruleName = name.replace(/\.ts$/u, "")
- const ruleId = `vue-scoped-css/${ruleName}`
- const rule = require(path.join(rulesLibRoot, name))
+ // const rulesDistRoot = path.resolve(__dirname, "../../dist/rules")
+ const rulesLibRoot = path.resolve(__dirname, "../../lib/rules");
+ const result = fs.readdirSync(rulesLibRoot);
+ const rules = [];
+ for (const name of result) {
+ const ruleName = name.replace(/\.ts$/u, "");
+ const ruleId = `vue-scoped-css/${ruleName}`;
+ const rule = require(path.join(rulesLibRoot, name));
- rule.meta.docs.ruleName = ruleName
- rule.meta.docs.ruleId = ruleId
+ rule.meta.docs.ruleName = ruleName;
+ rule.meta.docs.ruleId = ruleId;
- rules.push(rule)
- }
- return rules
+ rules.push(rule);
+ }
+ return rules;
}
-export const rules = readRules()
+export const rules = readRules();
diff --git a/tools/new-rule.ts b/tools/new-rule.ts
index 07a0cdb5..9ff1bed6 100644
--- a/tools/new-rule.ts
+++ b/tools/new-rule.ts
@@ -1,28 +1,28 @@
-import path from "path"
-import fs from "fs"
-import cp from "child_process"
-const logger = console
+import path from "path";
+import fs from "fs";
+import cp from "child_process";
+const logger = console;
// main
-;((ruleId) => {
- if (ruleId == null) {
- logger.error("Usage: npm run new ")
- process.exitCode = 1
- return
- }
- if (!/^[\w-]+$/u.test(ruleId)) {
- logger.error("Invalid RuleID '%s'.", ruleId)
- process.exitCode = 1
- return
- }
-
- const ruleFile = path.resolve(__dirname, `../lib/rules/${ruleId}.ts`)
- const testFile = path.resolve(__dirname, `../tests/lib/rules/${ruleId}.ts`)
- const docFile = path.resolve(__dirname, `../docs/rules/${ruleId}.md`)
-
- fs.writeFileSync(
- ruleFile,
- `
+((ruleId) => {
+ if (ruleId == null) {
+ logger.error("Usage: npm run new ");
+ process.exitCode = 1;
+ return;
+ }
+ if (!/^[\w-]+$/u.test(ruleId)) {
+ logger.error("Invalid RuleID '%s'.", ruleId);
+ process.exitCode = 1;
+ return;
+ }
+
+ const ruleFile = path.resolve(__dirname, `../lib/rules/${ruleId}.ts`);
+ const testFile = path.resolve(__dirname, `../tests/lib/rules/${ruleId}.ts`);
+ const docFile = path.resolve(__dirname, `../docs/rules/${ruleId}.md`);
+
+ fs.writeFileSync(
+ ruleFile,
+ `
import {
getStyleContexts,
getCommentDirectivesReporter,
@@ -89,11 +89,11 @@ module.exports = {
}
},
}
-`,
- )
- fs.writeFileSync(
- testFile,
- `import { RuleTester } from "eslint"
+`
+ );
+ fs.writeFileSync(
+ testFile,
+ `import { RuleTester } from "eslint"
import rule = require("../../../lib/rules/${ruleId}")
const tester = new RuleTester({
@@ -138,11 +138,11 @@ tester.run("${ruleId}", rule as any, {
},
],
})
-`,
- )
- fs.writeFileSync(
- docFile,
- `# (vue-scoped-css/${ruleId})
+`
+ );
+ fs.writeFileSync(
+ docFile,
+ `# (vue-scoped-css/${ruleId})
> foo
@@ -183,9 +183,9 @@ This rule reports ??? as errors.
- None
-`,
- )
- cp.execSync(`code "${ruleFile}"`)
- cp.execSync(`code "${testFile}"`)
- cp.execSync(`code "${docFile}"`)
-})(process.argv[2])
+`
+ );
+ cp.execSync(`code "${ruleFile}"`);
+ cp.execSync(`code "${testFile}"`);
+ cp.execSync(`code "${docFile}"`);
+})(process.argv[2]);
diff --git a/tools/render-rules.ts b/tools/render-rules.ts
index ad329103..9a6f898d 100644
--- a/tools/render-rules.ts
+++ b/tools/render-rules.ts
@@ -1,51 +1,49 @@
-import categories from "./lib/categories"
-import type { Rule } from "../lib/types"
-import { rules } from "../lib/utils/rules"
+import categories from "./lib/categories";
+import type { Rule } from "../lib/types";
+import { rules } from "../lib/utils/rules";
//eslint-disable-next-line require-jsdoc -- tools
export default function renderRulesTableContent(
- buildRulePath = (ruleName: string) => `./${ruleName}.md`,
+ buildRulePath = (ruleName: string) => `./${ruleName}.md`
): string {
- const uncategorizedRules = rules.filter(
- (rule) => !rule.meta.docs.categories.length && !rule.meta.deprecated,
- )
- const deprecatedRules = rules.filter((rule) => rule.meta.deprecated)
-
- // -----------------------------------------------------------------------------
-
- //eslint-disable-next-line require-jsdoc -- tools
- function toRuleRow(rule: Rule) {
- const mark = `${rule.meta.fixable ? ":wrench:" : ""}${
- rule.meta.deprecated ? ":warning:" : ""
- }`
- const link = `[${rule.meta.docs.ruleId}](${buildRulePath(
- rule.meta.docs.ruleName || "",
- )})`
- const description = rule.meta.docs.description || "(no description)"
-
- return `| ${link} | ${description} | ${mark} |`
- }
-
- //eslint-disable-next-line require-jsdoc -- tools
- function toDeprecatedRuleRow(rule: Rule) {
- const link = `[${rule.meta.docs.ruleId}](${buildRulePath(
- rule.meta.docs.ruleName || "",
- )})`
- const replacedRules = rule.meta.docs.replacedBy || []
- const replacedBy = replacedRules
- .map(
- (name) => `[vue-scoped-css/${name}](${buildRulePath(name)}.md)`,
- )
- .join(", ")
-
- return `| ${link} | ${replacedBy || "(no replacement)"} |`
- }
-
- // -----------------------------------------------------------------------------
- let rulesTableContent = categories
- .map((category) =>
- category.rules.length
- ? `
+ const uncategorizedRules = rules.filter(
+ (rule) => !rule.meta.docs.categories.length && !rule.meta.deprecated
+ );
+ const deprecatedRules = rules.filter((rule) => rule.meta.deprecated);
+
+ // -----------------------------------------------------------------------------
+
+ //eslint-disable-next-line require-jsdoc -- tools
+ function toRuleRow(rule: Rule) {
+ const mark = `${rule.meta.fixable ? ":wrench:" : ""}${
+ rule.meta.deprecated ? ":warning:" : ""
+ }`;
+ const link = `[${rule.meta.docs.ruleId}](${buildRulePath(
+ rule.meta.docs.ruleName || ""
+ )})`;
+ const description = rule.meta.docs.description || "(no description)";
+
+ return `| ${link} | ${description} | ${mark} |`;
+ }
+
+ //eslint-disable-next-line require-jsdoc -- tools
+ function toDeprecatedRuleRow(rule: Rule) {
+ const link = `[${rule.meta.docs.ruleId}](${buildRulePath(
+ rule.meta.docs.ruleName || ""
+ )})`;
+ const replacedRules = rule.meta.docs.replacedBy || [];
+ const replacedBy = replacedRules
+ .map((name) => `[vue-scoped-css/${name}](${buildRulePath(name)}.md)`)
+ .join(", ");
+
+ return `| ${link} | ${replacedBy || "(no replacement)"} |`;
+ }
+
+ // -----------------------------------------------------------------------------
+ let rulesTableContent = categories
+ .map((category) =>
+ category.rules.length
+ ? `
## ${category.title}
${category.configDescription}
@@ -60,13 +58,13 @@ ${category.configDescription}
|:--------|:------------|:---|
${category.rules.map(toRuleRow).join("\n")}
`
- : "",
- )
- .join("")
+ : ""
+ )
+ .join("");
- // -----------------------------------------------------------------------------
- if (uncategorizedRules.length >= 1) {
- rulesTableContent += `
+ // -----------------------------------------------------------------------------
+ if (uncategorizedRules.length >= 1) {
+ rulesTableContent += `
## Uncategorized
No preset enables the rules in this category.
@@ -85,12 +83,12 @@ For example:
| Rule ID | Description | |
|:--------|:------------|:---|
${uncategorizedRules.map(toRuleRow).join("\n")}
-`
- }
+`;
+ }
- // -----------------------------------------------------------------------------
- if (deprecatedRules.length >= 1) {
- rulesTableContent += `
+ // -----------------------------------------------------------------------------
+ if (deprecatedRules.length >= 1) {
+ rulesTableContent += `
## Deprecated
- :warning: We're going to remove deprecated rules in the next major release. Please migrate to successor/new rules.
@@ -99,7 +97,7 @@ ${uncategorizedRules.map(toRuleRow).join("\n")}
| Rule ID | Replaced by |
|:--------|:------------|
${deprecatedRules.map(toDeprecatedRuleRow).join("\n")}
-`
- }
- return rulesTableContent
+`;
+ }
+ return rulesTableContent;
}
diff --git a/tools/update-docs-rules-index.ts b/tools/update-docs-rules-index.ts
index b77168df..a5111803 100644
--- a/tools/update-docs-rules-index.ts
+++ b/tools/update-docs-rules-index.ts
@@ -1,17 +1,17 @@
-import path from "path"
-import fs from "fs"
-import renderRulesTableContent from "./render-rules"
+import path from "path";
+import fs from "fs";
+import renderRulesTableContent from "./render-rules";
// -----------------------------------------------------------------------------
-const readmeFilePath = path.resolve(__dirname, "../docs/rules/README.md")
+const readmeFilePath = path.resolve(__dirname, "../docs/rules/README.md");
fs.writeFileSync(
- readmeFilePath,
- `---
+ readmeFilePath,
+ `---
sidebarDepth: 0
---
# Available Rules
-${renderRulesTableContent()}`,
-)
+${renderRulesTableContent()}`
+);
diff --git a/tools/update-docs.ts b/tools/update-docs.ts
index cff9dab5..49538d95 100644
--- a/tools/update-docs.ts
+++ b/tools/update-docs.ts
@@ -1,214 +1,210 @@
-import path from "path"
-import fs from "fs"
-import { rules } from "../lib/utils/rules"
-import { configs } from "./lib/load-configs"
-import type { Rule } from "../lib/types"
+import path from "path";
+import fs from "fs";
+import { rules } from "../lib/utils/rules";
+import { configs } from "./lib/load-configs";
+import type { Rule } from "../lib/types";
//eslint-disable-next-line require-jsdoc -- tools
function formatItems(items: string[]) {
- if (items.length <= 2) {
- return items.join(" and ")
- }
- return `all of ${items.slice(0, -1).join(", ")} and ${
- items[items.length - 1]
- }`
+ if (items.length <= 2) {
+ return items.join(" and ");
+ }
+ return `all of ${items.slice(0, -1).join(", ")} and ${
+ items[items.length - 1]
+ }`;
}
//eslint-disable-next-line require-jsdoc -- tools
function getPresets(categories: string[]) {
- const categoryConfigs = configs.filter((conf) =>
- categories.includes(conf.name),
- )
- if (!categoryConfigs.length) {
- return []
- }
-
- const presets = new Set(categoryConfigs.map((cat) => cat.configId))
- const subTargets = configs.filter((conf) =>
- conf.extends.find((ext) => categories.includes(ext.name)),
- )
- for (const name of getPresets(subTargets.map((s) => s.name))) {
- presets.add(name)
- }
- return [...presets]
+ const categoryConfigs = configs.filter((conf) =>
+ categories.includes(conf.name)
+ );
+ if (!categoryConfigs.length) {
+ return [];
+ }
+
+ const presets = new Set(categoryConfigs.map((cat) => cat.configId));
+ const subTargets = configs.filter((conf) =>
+ conf.extends.find((ext) => categories.includes(ext.name))
+ );
+ for (const name of getPresets(subTargets.map((s) => s.name))) {
+ presets.add(name);
+ }
+ return [...presets];
}
//eslint-disable-next-line require-jsdoc, @typescript-eslint/no-explicit-any -- tools
function yamlValue(val: any) {
- if (typeof val === "string") {
- return `"${val.replace(/"/gu, '\\"')}"`
- }
- return val
+ if (typeof val === "string") {
+ return `"${val.replace(/"/gu, '\\"')}"`;
+ }
+ return val;
}
-const ROOT = path.resolve(__dirname, "../docs/rules")
+const ROOT = path.resolve(__dirname, "../docs/rules");
class DocFile {
- private readonly rule: Rule
-
- private readonly filePath: string
-
- private content: string
-
- public constructor(rule: Rule) {
- this.rule = rule
- this.filePath = path.join(ROOT, `${rule.meta.docs.ruleName}.md`)
- this.content = fs.readFileSync(this.filePath, "utf8")
+ private readonly rule: Rule;
+
+ private readonly filePath: string;
+
+ private content: string;
+
+ public constructor(rule: Rule) {
+ this.rule = rule;
+ this.filePath = path.join(ROOT, `${rule.meta.docs.ruleName}.md`);
+ this.content = fs.readFileSync(this.filePath, "utf8");
+ }
+
+ public static read(rule: Rule) {
+ return new DocFile(rule);
+ }
+
+ public updateHeader() {
+ const {
+ meta: {
+ fixable,
+ deprecated,
+ docs: { ruleId, description, categories, replacedBy },
+ },
+ } = this.rule;
+ const title = `# ${ruleId}\n\n> ${description}`;
+ const notes = [];
+
+ if (deprecated) {
+ if (replacedBy) {
+ const replacedRules = replacedBy.map(
+ (name) => `[vue-scoped-css/${name}](${name}.md) rule`
+ );
+ notes.push(
+ `- :warning: This rule was **deprecated** and replaced by ${formatItems(
+ replacedRules
+ )}.`
+ );
+ } else {
+ notes.push("- :warning: This rule was **deprecated**.");
+ }
+ } else {
+ const presets = Array.from(
+ new Set(getPresets(categories).concat(["plugin:vue-scoped-css/all"]))
+ );
+
+ if (presets.length) {
+ notes.push(
+ `- :gear: This rule is included in ${formatItems(
+ presets.map((c) => `\`"${c}"\``)
+ )}.`
+ );
+ }
+ // const presets = categories
+ // .slice(categoryIndex)
+ // .map(category => `\`"plugin:vue/${category.categoryId}"\``)
+ // notes.push(
+ // `- :gear: This rule is included in ${formatItems(presets)}.`
+ // )
+ }
+ if (fixable) {
+ notes.push(
+ "- :wrench: The `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the problems reported by this rule."
+ );
}
- public static read(rule: Rule) {
- return new DocFile(rule)
+ // Add an empty line after notes.
+ if (notes.length >= 1) {
+ notes.push("", "");
}
- public updateHeader() {
- const {
- meta: {
- fixable,
- deprecated,
- docs: { ruleId, description, categories, replacedBy },
- },
- } = this.rule
- const title = `# ${ruleId}\n\n> ${description}`
- const notes = []
-
- if (deprecated) {
- if (replacedBy) {
- const replacedRules = replacedBy.map(
- (name) => `[vue-scoped-css/${name}](${name}.md) rule`,
- )
- notes.push(
- `- :warning: This rule was **deprecated** and replaced by ${formatItems(
- replacedRules,
- )}.`,
- )
- } else {
- notes.push("- :warning: This rule was **deprecated**.")
- }
- } else {
- const presets = Array.from(
- new Set(
- getPresets(categories).concat([
- "plugin:vue-scoped-css/all",
- ]),
- ),
- )
-
- if (presets.length) {
- notes.push(
- `- :gear: This rule is included in ${formatItems(
- presets.map((c) => `\`"${c}"\``),
- )}.`,
- )
- }
- // const presets = categories
- // .slice(categoryIndex)
- // .map(category => `\`"plugin:vue/${category.categoryId}"\``)
- // notes.push(
- // `- :gear: This rule is included in ${formatItems(presets)}.`
- // )
- }
- if (fixable) {
- notes.push(
- "- :wrench: The `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the problems reported by this rule.",
- )
- }
-
- // Add an empty line after notes.
- if (notes.length >= 1) {
- notes.push("", "")
- }
-
- const headerPattern = /#.+\n+[^\n]*\n+(?:- .+\n+)*\n*/u
- const header = `${title}\n\n${notes.join("\n")}`
- if (headerPattern.test(this.content)) {
- this.content = this.content.replace(headerPattern, header)
- } else {
- this.content = `${header}${this.content.trim()}\n`
- }
-
- return this
+ const headerPattern = /#.+\n+[^\n]*\n+(?:- .+\n+)*\n*/u;
+ const header = `${title}\n\n${notes.join("\n")}`;
+ if (headerPattern.test(this.content)) {
+ this.content = this.content.replace(headerPattern, header);
+ } else {
+ this.content = `${header}${this.content.trim()}\n`;
}
- public updateFooter() {
- const { ruleName } = this.rule.meta.docs
- const footerPattern = /## Implementation[\s\S]+$/u
- const footer = `## Implementation
+ return this;
+ }
+
+ public updateFooter() {
+ const { ruleName } = this.rule.meta.docs;
+ const footerPattern = /## Implementation[\s\S]+$/u;
+ const footer = `## Implementation
- [Rule source](https://github.com/future-architect/eslint-plugin-vue-scoped-css/blob/master/lib/rules/${ruleName}.ts)
- [Test source](https://github.com/future-architect/eslint-plugin-vue-scoped-css/blob/master/tests/lib/rules/${ruleName}.js)
-`
- if (footerPattern.test(this.content)) {
- this.content = this.content.replace(footerPattern, footer)
- } else {
- this.content = `${this.content.trim()}\n\n${footer}`
- }
-
- return this
+`;
+ if (footerPattern.test(this.content)) {
+ this.content = this.content.replace(footerPattern, footer);
+ } else {
+ this.content = `${this.content.trim()}\n\n${footer}`;
}
- public updateCodeBlocks() {
- const { meta } = this.rule
-
- this.content = this.content.replace(
- /)\n+```/gu,
+ "$1\n\n```"
+ );
+ this.content = this.content.replace(
+ /```\n+<\/eslint-code-block>/gu,
+ "```\n\n "
+ );
+ return this;
+ }
+
+ public updateFileIntro() {
+ const { ruleId, description } = this.rule.meta.docs;
+
+ const fileIntro = {
+ pageClass: "rule-details",
+ sidebarDepth: 0,
+ title: ruleId,
+ description,
+ };
+ const computed = `---\n${Object.keys(fileIntro)
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- tools
+ .map((key) => `${key}: ${yamlValue((fileIntro as any)[key])}`)
+ .join("\n")}\n---\n`;
+
+ const fileIntroPattern = /^---\n(.*\n)+---\n*/gu;
+
+ if (fileIntroPattern.test(this.content)) {
+ this.content = this.content.replace(fileIntroPattern, computed);
+ } else {
+ this.content = `${computed}${this.content.trim()}\n`;
}
- public adjustCodeBlocks() {
- // Adjust the necessary blank lines before and after the code block so that GitHub can recognize `.md`.
- this.content = this.content.replace(
- /()\n+```/gu,
- "$1\n\n```",
- )
- this.content = this.content.replace(
- /```\n+<\/eslint-code-block>/gu,
- "```\n\n ",
- )
- return this
- }
+ return this;
+ }
- public updateFileIntro() {
- const { ruleId, description } = this.rule.meta.docs
-
- const fileIntro = {
- pageClass: "rule-details",
- sidebarDepth: 0,
- title: ruleId,
- description,
- }
- const computed = `---\n${Object.keys(fileIntro)
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- tools
- .map((key) => `${key}: ${yamlValue((fileIntro as any)[key])}`)
- .join("\n")}\n---\n`
-
- const fileIntroPattern = /^---\n(.*\n)+---\n*/gu
-
- if (fileIntroPattern.test(this.content)) {
- this.content = this.content.replace(fileIntroPattern, computed)
- } else {
- this.content = `${computed}${this.content.trim()}\n`
- }
-
- return this
- }
-
- public write() {
- const isWin = require("os").platform().startsWith("win")
+ public write() {
+ const isWin = require("os").platform().startsWith("win");
- this.content = this.content.replace(/\r?\n/gu, isWin ? "\r\n" : "\n")
+ this.content = this.content.replace(/\r?\n/gu, isWin ? "\r\n" : "\n");
- fs.writeFileSync(this.filePath, this.content)
- }
+ fs.writeFileSync(this.filePath, this.content);
+ }
}
for (const rule of rules) {
- DocFile.read(rule)
- .updateHeader()
- .updateFooter()
- .updateCodeBlocks()
- .updateFileIntro()
- .adjustCodeBlocks()
- .write()
+ DocFile.read(rule)
+ .updateHeader()
+ .updateFooter()
+ .updateCodeBlocks()
+ .updateFileIntro()
+ .adjustCodeBlocks()
+ .write();
}
diff --git a/tools/update-readme.ts b/tools/update-readme.ts
index 4af252ad..587b431e 100644
--- a/tools/update-readme.ts
+++ b/tools/update-readme.ts
@@ -1,47 +1,47 @@
-import path from "path"
-import fs from "fs"
-import os from "os"
-import renderRulesTableContent from "./render-rules"
-const isWin = os.platform().startsWith("win")
+import path from "path";
+import fs from "fs";
+import os from "os";
+import renderRulesTableContent from "./render-rules";
+const isWin = os.platform().startsWith("win");
let insertText = `\n${renderRulesTableContent(
- (name) =>
- `https://future-architect.github.io/eslint-plugin-vue-scoped-css/rules/${name}.html`,
-)}\n`
+ (name) =>
+ `https://future-architect.github.io/eslint-plugin-vue-scoped-css/rules/${name}.html`
+)}\n`;
if (isWin) {
- insertText = insertText
- .replace(/\r?\n/gu, "\n")
- .replace(/\r/gu, "\n")
- .replace(/\n/gu, "\r\n")
+ insertText = insertText
+ .replace(/\r?\n/gu, "\n")
+ .replace(/\r/gu, "\n")
+ .replace(/\n/gu, "\r\n");
}
-const readmeFilePath = path.resolve(__dirname, "../README.md")
+const readmeFilePath = path.resolve(__dirname, "../README.md");
const newReadme = fs
- .readFileSync(readmeFilePath, "utf8")
- .replace(
- /[\s\S]*/u,
- `${insertText}`,
- )
-fs.writeFileSync(readmeFilePath, newReadme)
+ .readFileSync(readmeFilePath, "utf8")
+ .replace(
+ /[\s\S]*/u,
+ `${insertText}`
+ );
+fs.writeFileSync(readmeFilePath, newReadme);
-const docsReadmeFilePath = path.resolve(__dirname, "../docs/README.md")
+const docsReadmeFilePath = path.resolve(__dirname, "../docs/README.md");
fs.writeFileSync(
- docsReadmeFilePath,
- newReadme
- .replace("# eslint-plugin-vue-scoped-css\n", "# Introduction\n")
- .replace(
- /[\s\S]*/u,
- "See [Available Rules](./rules/README.md).",
- )
- .replace(
- /[\s\S]*/u,
- "See [User Guide](./user-guide/README.md).",
- )
- .replace(/[\s\S]*?/gu, "")
- .replace(
- /\(https:\/\/future-architect.github.io\/eslint-plugin-vue-scoped-css/gu,
- "(.",
- )
- .replace(/\n{3,}/gu, "\n\n"),
-)
+ docsReadmeFilePath,
+ newReadme
+ .replace("# eslint-plugin-vue-scoped-css\n", "# Introduction\n")
+ .replace(
+ /[\s\S]*/u,
+ "See [Available Rules](./rules/README.md)."
+ )
+ .replace(
+ /[\s\S]*/u,
+ "See [User Guide](./user-guide/README.md)."
+ )
+ .replace(/[\s\S]*?/gu, "")
+ .replace(
+ /\(https:\/\/future-architect.github.io\/eslint-plugin-vue-scoped-css/gu,
+ "(."
+ )
+ .replace(/\n{3,}/gu, "\n\n")
+);
diff --git a/tools/update-rules.ts b/tools/update-rules.ts
index 684ac183..a303adca 100644
--- a/tools/update-rules.ts
+++ b/tools/update-rules.ts
@@ -1,24 +1,24 @@
-import path from "path"
-import fs from "fs"
-import os from "os"
+import path from "path";
+import fs from "fs";
+import os from "os";
// import eslint from "eslint"
-import { rules } from "./lib/load-rules"
-const isWin = os.platform().startsWith("win")
+import { rules } from "./lib/load-rules";
+const isWin = os.platform().startsWith("win");
let content = `
import type { Rule } from "../types"
const baseRules = [
${rules
- .map(
- (rule) => `{
+ .map(
+ (rule) => `{
rule: require("../rules/${rule.meta.docs.ruleName}"),
ruleName: "${rule.meta.docs.ruleName}",
ruleId: "${rule.meta.docs.ruleId}",
},
- `,
- )
- .join("")}
+ `
+ )
+ .join("")}
]
export const rules = baseRules.map(obj => {
@@ -46,19 +46,19 @@ export function collectRules(
return obj
}, {} as { [key: string]: string })
}
-`
+`;
-const filePath = path.resolve(__dirname, "../lib/utils/rules.ts")
+const filePath = path.resolve(__dirname, "../lib/utils/rules.ts");
if (isWin) {
- content = content
- .replace(/\r?\n/gu, "\n")
- .replace(/\r/gu, "\n")
- .replace(/\n/gu, "\r\n")
+ content = content
+ .replace(/\r?\n/gu, "\n")
+ .replace(/\r/gu, "\n")
+ .replace(/\n/gu, "\r\n");
}
// Update file.
-fs.writeFileSync(filePath, content)
+fs.writeFileSync(filePath, content);
// Format files.
// const linter = new eslint.CLIEngine({ fix: true })
diff --git a/tools/update.ts b/tools/update.ts
index 9aa00379..8ee77012 100644
--- a/tools/update.ts
+++ b/tools/update.ts
@@ -1,4 +1,4 @@
-import "./update-rules"
-import "./update-docs"
-import "./update-readme"
-import "./update-docs-rules-index"
+import "./update-rules";
+import "./update-docs";
+import "./update-readme";
+import "./update-docs-rules-index";
diff --git a/typings/eslint-scope/index.d.ts b/typings/eslint-scope/index.d.ts
index 873a5d53..d9f54fca 100644
--- a/typings/eslint-scope/index.d.ts
+++ b/typings/eslint-scope/index.d.ts
@@ -1,74 +1,74 @@
-import type * as estree from "estree"
+import type * as estree from "estree";
export interface AnalysisOptions {
- optimistic?: boolean
- directive?: boolean
- ignoreEval?: boolean
- nodejsScope?: boolean
- impliedStrict?: boolean
- // fallback?: string | Function
- sourceType?: "script" | "module"
- ecmaVersion?: number
+ optimistic?: boolean;
+ directive?: boolean;
+ ignoreEval?: boolean;
+ nodejsScope?: boolean;
+ impliedStrict?: boolean;
+ // fallback?: string | Function
+ sourceType?: "script" | "module";
+ ecmaVersion?: number;
}
export interface ScopeManager {
- scopes: Scope[]
- globalScope: Scope
- acquire(node: estree.Node, inner: boolean): Scope | null
- acquireAll(node: estree.Node): Scope[]
+ scopes: Scope[];
+ globalScope: Scope;
+ acquire(node: estree.Node, inner: boolean): Scope | null;
+ acquireAll(node: estree.Node): Scope[];
}
export interface Scope {
- block: estree.Node
- childScopes: Scope[]
- directCallToEcalScope: boolean
- dynamic: boolean
- functionExpressionScope: boolean
- isStrict: boolean
- references: Reference[]
- set: Map
- taints: Map
- thisFound: boolean
- through: Reference[]
- type: string
- upper: Scope | null
- variables: Variable[]
- variableScope: Scope
+ block: estree.Node;
+ childScopes: Scope[];
+ directCallToEcalScope: boolean;
+ dynamic: boolean;
+ functionExpressionScope: boolean;
+ isStrict: boolean;
+ references: Reference[];
+ set: Map;
+ taints: Map;
+ thisFound: boolean;
+ through: Reference[];
+ type: string;
+ upper: Scope | null;
+ variables: Variable[];
+ variableScope: Scope;
}
export interface Variable {
- defs: VariableDefinition[]
- identifiers: estree.Identifier[]
- name: string
- references: Reference[]
- scope: Scope
- stack: boolean
+ defs: VariableDefinition[];
+ identifiers: estree.Identifier[];
+ name: string;
+ references: Reference[];
+ scope: Scope;
+ stack: boolean;
}
export interface VariableDefinition {
- type: string
- name: estree.Identifier
- node: estree.Node
- parent?: estree.Node
+ type: string;
+ name: estree.Identifier;
+ node: estree.Node;
+ parent?: estree.Node;
}
export interface Reference {
- from: Scope
- identifier: estree.Identifier
- partial: boolean
- resolved: Variable | null
- tainted: boolean
- writeExpr: estree.Expression
+ from: Scope;
+ identifier: estree.Identifier;
+ partial: boolean;
+ resolved: Variable | null;
+ tainted: boolean;
+ writeExpr: estree.Expression;
- isRead(): boolean
- isReadOnly(): boolean
- isReadWrite(): boolean
- isStatic(): boolean
- isWrite(): boolean
- isWriteOnly(): boolean
+ isRead(): boolean;
+ isReadOnly(): boolean;
+ isReadWrite(): boolean;
+ isStatic(): boolean;
+ isWrite(): boolean;
+ isWriteOnly(): boolean;
}
declare const eslintScope: {
- analyze(ast: unknown, options?: AnalysisOptions): ScopeManager
-}
-export default eslintScope
+ analyze(ast: unknown, options?: AnalysisOptions): ScopeManager;
+};
+export default eslintScope;
diff --git a/typings/eslint-utils/index.d.ts b/typings/eslint-utils/index.d.ts
index 63e93944..998bf0a6 100644
--- a/typings/eslint-utils/index.d.ts
+++ b/typings/eslint-utils/index.d.ts
@@ -1,13 +1,13 @@
-import type { AST } from "../../lib/types"
-import type { Scope } from "eslint-scope"
+import type { AST } from "../../lib/types";
+import type { Scope } from "eslint-scope";
declare const utils: {
- getStaticValue: (
- node: AST.ESLintExpression,
- scope: Scope,
- ) => null | {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore
- value: any
- }
-}
-export default utils
+ getStaticValue: (
+ node: AST.ESLintExpression,
+ scope: Scope
+ ) => null | {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ignore
+ value: any;
+ };
+};
+export default utils;
diff --git a/typings/postcss-safe-parser/index.d.ts b/typings/postcss-safe-parser/index.d.ts
index 94eb55ed..b340c57c 100644
--- a/typings/postcss-safe-parser/index.d.ts
+++ b/typings/postcss-safe-parser/index.d.ts
@@ -1,3 +1,3 @@
-import postcss from "postcss"
+import postcss from "postcss";
-export default postcss.parse
+export default postcss.parse;
diff --git a/typings/postcss-scss/index.d.ts b/typings/postcss-scss/index.d.ts
index 7a9d284e..0f6873cd 100644
--- a/typings/postcss-scss/index.d.ts
+++ b/typings/postcss-scss/index.d.ts
@@ -1,5 +1,5 @@
-import type * as postcss from "postcss"
+import type * as postcss from "postcss";
declare module "postcss-scss" {
- const parse: postcss.Parser, stringify: postcss.Stringifier
+ const parse: postcss.Parser, stringify: postcss.Stringifier;
}
diff --git a/typings/postcss-styl/index.d.ts b/typings/postcss-styl/index.d.ts
index 0b4471d7..787edc90 100644
--- a/typings/postcss-styl/index.d.ts
+++ b/typings/postcss-styl/index.d.ts
@@ -1,5 +1,5 @@
-import type * as postcss from "postcss"
+import type * as postcss from "postcss";
declare module "postcss-styl" {
- const parse: postcss.Parser, stringify: postcss.Stringifier
+ const parse: postcss.Parser, stringify: postcss.Stringifier;
}