@tai-kun/vp-lint-plugins 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/src/index.d.ts +2 -6
  2. package/dist/src/index.d.ts.map +1 -1
  3. package/dist/src/index.js +2 -6
  4. package/dist/src/plugin.js +4 -12
  5. package/dist/src/rules/blank-line-utils.d.ts +30 -0
  6. package/dist/src/rules/blank-line-utils.d.ts.map +1 -0
  7. package/dist/src/rules/blank-line-utils.js +103 -0
  8. package/dist/src/rules/blank-line.d.ts +5 -14
  9. package/dist/src/rules/blank-line.d.ts.map +1 -1
  10. package/dist/src/rules/blank-line.js +426 -66
  11. package/dist/src/rules/merge-imports.d.ts +8 -0
  12. package/dist/src/rules/merge-imports.d.ts.map +1 -0
  13. package/dist/src/rules/merge-imports.js +199 -0
  14. package/dist/src/rules/overload-signatures-adjacent.js +1 -1
  15. package/package.json +1 -1
  16. package/src/index.ts +2 -6
  17. package/src/plugin.ts +4 -12
  18. package/src/rules/blank-line-utils.ts +165 -0
  19. package/src/rules/blank-line.ts +555 -97
  20. package/src/rules/merge-imports.ts +301 -0
  21. package/src/rules/overload-signatures-adjacent.ts +1 -1
  22. package/dist/src/rules/blank-line-after-control-block.d.ts +0 -7
  23. package/dist/src/rules/blank-line-after-control-block.d.ts.map +0 -1
  24. package/dist/src/rules/blank-line-after-control-block.js +0 -54
  25. package/dist/src/rules/blank-line-after-declaration.d.ts +0 -7
  26. package/dist/src/rules/blank-line-after-declaration.d.ts.map +0 -1
  27. package/dist/src/rules/blank-line-after-declaration.js +0 -79
  28. package/dist/src/rules/blank-line-after-variable-declaration.d.ts +0 -9
  29. package/dist/src/rules/blank-line-after-variable-declaration.d.ts.map +0 -1
  30. package/dist/src/rules/blank-line-after-variable-declaration.js +0 -118
  31. package/dist/src/rules/blank-line-before-return.d.ts +0 -7
  32. package/dist/src/rules/blank-line-before-return.d.ts.map +0 -1
  33. package/dist/src/rules/blank-line-before-return.js +0 -81
  34. package/dist/src/rules/blank-line-between-class-members.d.ts +0 -8
  35. package/dist/src/rules/blank-line-between-class-members.d.ts.map +0 -1
  36. package/dist/src/rules/blank-line-between-class-members.js +0 -85
  37. package/dist/src/rules/blank-line-between-switch-cases.d.ts +0 -8
  38. package/dist/src/rules/blank-line-between-switch-cases.d.ts.map +0 -1
  39. package/dist/src/rules/blank-line-between-switch-cases.js +0 -45
  40. package/src/rules/blank-line-after-control-block.ts +0 -82
  41. package/src/rules/blank-line-after-declaration.ts +0 -106
  42. package/src/rules/blank-line-after-variable-declaration.ts +0 -165
  43. package/src/rules/blank-line-before-return.ts +0 -101
  44. package/src/rules/blank-line-between-class-members.ts +0 -112
  45. package/src/rules/blank-line-between-switch-cases.ts +0 -53
@@ -0,0 +1,199 @@
1
+ import { defineRule } from "vite-plus/lint/plugins";
2
+ function getModuleName(node) {
3
+ return node.source.value;
4
+ }
5
+ function getAttributeKey(attribute) {
6
+ const key = attribute.key.type === "Identifier" ? attribute.key.name : attribute.key.value;
7
+ return `${key}:${attribute.value.value}`;
8
+ }
9
+ function getAttributesKey(node) {
10
+ return node.attributes.map(getAttributeKey).join(",");
11
+ }
12
+ function getLineIndent(source, offset) {
13
+ const lineStart = source.lastIndexOf("\n", offset) + 1;
14
+ const match = /^[ \t]*/u.exec(source.slice(lineStart, offset));
15
+ return match?.[0] ?? "";
16
+ }
17
+ function isMergeableDeclaration(node) {
18
+ return (node.type === "ImportDeclaration" &&
19
+ node.phase === null &&
20
+ node.specifiers.length > 0 &&
21
+ node.specifiers.every((specifier) => specifier.type !== "ImportNamespaceSpecifier"));
22
+ }
23
+ function hasUnsafeComment(declarations, comments) {
24
+ const first = declarations[0];
25
+ const last = declarations.at(-1);
26
+ if (first === undefined || last === undefined) {
27
+ return true;
28
+ }
29
+ const specifierRanges = declarations.flatMap((declaration) => declaration.specifiers.map((specifier) => specifier.range));
30
+ return comments.some((comment) => comment.range[0] >= first.range[0] &&
31
+ comment.range[1] <= last.range[1] &&
32
+ !specifierRanges.some((range) => comment.range[0] >= range[0] && comment.range[1] <= range[1]));
33
+ }
34
+ function buildNamedClause(declarations, specifiers, sourceCode) {
35
+ const texts = specifiers.map((specifier) => specifier.text);
36
+ const multiline = declarations.find((declaration) => {
37
+ const firstSpecifier = declaration.specifiers.find((specifier) => specifier.type === "ImportSpecifier");
38
+ return (firstSpecifier !== undefined && firstSpecifier.loc.start.line > declaration.loc.start.line);
39
+ });
40
+ if (multiline === undefined) {
41
+ return `{ ${texts.join(", ")} }`;
42
+ }
43
+ const firstNamed = multiline.specifiers.find((specifier) => specifier.type === "ImportSpecifier");
44
+ const lastNamed = multiline.specifiers.findLast((specifier) => specifier.type === "ImportSpecifier");
45
+ const firstDeclaration = declarations[0];
46
+ if (firstNamed === undefined || lastNamed === undefined || firstDeclaration === undefined) {
47
+ return `{ ${texts.join(", ")} }`;
48
+ }
49
+ const indent = getLineIndent(sourceCode.text, firstNamed.range[0]);
50
+ const closingIndent = getLineIndent(sourceCode.text, firstDeclaration.range[0]);
51
+ const beforeSource = sourceCode.text.slice(lastNamed.range[1], multiline.source.range[0]);
52
+ const trailingComma = /,\s*\}/u.test(beforeSource);
53
+ return `{\n${indent}${texts.join(`,\n${indent}`)}${trailingComma ? "," : ""}\n${closingIndent}}`;
54
+ }
55
+ function buildReplacement(declarations, sourceCode) {
56
+ const first = declarations[0];
57
+ if (first === undefined) {
58
+ return null;
59
+ }
60
+ const defaultSpecifiers = declarations.flatMap((declaration) => declaration.specifiers
61
+ .filter((specifier) => specifier.type === "ImportDefaultSpecifier")
62
+ .map((specifier) => ({
63
+ local: specifier.local.name,
64
+ typeOnly: declaration.importKind === "type",
65
+ })));
66
+ const hasNamed = declarations.some((declaration) => declaration.specifiers.some((specifier) => specifier.type === "ImportSpecifier"));
67
+ let defaultSpecifier = null;
68
+ for (const specifier of defaultSpecifiers) {
69
+ if (defaultSpecifier === null) {
70
+ defaultSpecifier = specifier;
71
+ continue;
72
+ }
73
+ // default import は 1 つしか置けないため、別名の default import はまとめられません。
74
+ if (defaultSpecifier.local !== specifier.local ||
75
+ defaultSpecifier.typeOnly !== specifier.typeOnly) {
76
+ return null;
77
+ }
78
+ }
79
+ const allTypeOnly = declarations.every((declaration) => declaration.importKind === "type");
80
+ // `import type Foo, { Bar }` は書けないため、default と名前付きを併存させる場合は `type default as Foo` を使う通常の import に変換します。
81
+ const useTypeOnlyDeclaration = allTypeOnly && !(defaultSpecifier !== null && hasNamed);
82
+ const namedByLocal = new Map();
83
+ const named = [];
84
+ function addNamed(local, text) {
85
+ const existing = namedByLocal.get(local);
86
+ if (existing !== undefined) {
87
+ return existing === text;
88
+ }
89
+ namedByLocal.set(local, text);
90
+ named.push({
91
+ text,
92
+ local,
93
+ });
94
+ return true;
95
+ }
96
+ let defaultClause = null;
97
+ if (defaultSpecifier !== null) {
98
+ if (useTypeOnlyDeclaration || !defaultSpecifier.typeOnly) {
99
+ defaultClause = defaultSpecifier.local;
100
+ }
101
+ else if (!addNamed(defaultSpecifier.local, `type default as ${defaultSpecifier.local}`)) {
102
+ return null;
103
+ }
104
+ }
105
+ for (const declaration of declarations) {
106
+ const forceType = !useTypeOnlyDeclaration && declaration.importKind === "type";
107
+ for (const specifier of declaration.specifiers) {
108
+ if (specifier.type !== "ImportSpecifier") {
109
+ continue;
110
+ }
111
+ const original = sourceCode.getText(specifier);
112
+ const text = forceType && specifier.importKind !== "type" ? `type ${original}` : original;
113
+ if (!addNamed(specifier.local.name, text)) {
114
+ return null;
115
+ }
116
+ }
117
+ }
118
+ if (defaultClause !== null && namedByLocal.has(defaultClause)) {
119
+ return null;
120
+ }
121
+ const bindings = [];
122
+ if (defaultClause !== null) {
123
+ bindings.push(defaultClause);
124
+ }
125
+ if (named.length > 0) {
126
+ bindings.push(buildNamedClause(declarations, named, sourceCode));
127
+ }
128
+ if (bindings.length === 0) {
129
+ return null;
130
+ }
131
+ const sourceText = sourceCode.getText(first.source);
132
+ // `with { ... }` や `assert { ... }`、セミコロンの有無を元の宣言から引き継ぎます。
133
+ const suffix = sourceCode.text.slice(first.source.range[1], first.range[1]);
134
+ return `import ${useTypeOnlyDeclaration ? "type " : ""}${bindings.join(", ")} from ${sourceText}${suffix}`;
135
+ }
136
+ /**
137
+ * 同じモジュールを指す連続した import 宣言を 1 つにまとめます。
138
+ *
139
+ * 別名の default import、namespace import、副作用だけの import、属性が異なる import は安全にまとめられないため対象外にします。コメントが specifier の外側にある場合も、コメントを失わないように対象外にします。
140
+ */
141
+ const mergeImports = defineRule({
142
+ meta: {
143
+ docs: {
144
+ description: "Merge consecutive import declarations that import from the same module.",
145
+ },
146
+ type: "layout",
147
+ fixable: "whitespace",
148
+ messages: {
149
+ merge: "Import declarations from the same module must be merged.",
150
+ },
151
+ },
152
+ create(context) {
153
+ const sourceCode = context.sourceCode;
154
+ return {
155
+ Program(node) {
156
+ const comments = sourceCode.getAllComments();
157
+ let index = 0;
158
+ while (index < node.body.length) {
159
+ const first = node.body[index];
160
+ if (first === undefined || !isMergeableDeclaration(first)) {
161
+ index += 1;
162
+ continue;
163
+ }
164
+ const declarations = [first];
165
+ let next = index + 1;
166
+ while (next < node.body.length) {
167
+ const candidate = node.body[next];
168
+ if (candidate === undefined ||
169
+ !isMergeableDeclaration(candidate) ||
170
+ getModuleName(candidate) !== getModuleName(first) ||
171
+ getAttributesKey(candidate) !== getAttributesKey(first)) {
172
+ break;
173
+ }
174
+ declarations.push(candidate);
175
+ next += 1;
176
+ }
177
+ if (declarations.length > 1 && !hasUnsafeComment(declarations, comments)) {
178
+ const replacement = buildReplacement(declarations, sourceCode);
179
+ const last = declarations.at(-1);
180
+ if (replacement !== null && last !== undefined) {
181
+ context.report({
182
+ fix(fixer) {
183
+ return [
184
+ fixer.replaceText(first, replacement),
185
+ fixer.removeRange([first.range[1], last.range[1]]),
186
+ ];
187
+ },
188
+ node: first,
189
+ messageId: "merge",
190
+ });
191
+ }
192
+ }
193
+ index = next;
194
+ }
195
+ },
196
+ };
197
+ },
198
+ });
199
+ export default mergeImports;
@@ -1,5 +1,5 @@
1
1
  import { defineRule } from "vite-plus/lint/plugins";
2
- import { getNextStatement, getRemoveBlankLineFix } from "./blank-line.js";
2
+ import { getNextStatement, getRemoveBlankLineFix } from "./blank-line-utils.js";
3
3
  function getFunction(node) {
4
4
  if (node.type === "FunctionDeclaration" || node.type === "TSDeclareFunction") {
5
5
  return node;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tai-kun/vp-lint-plugins",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "",
5
5
  "homepage": "https://tai-kun.github.io/vp-lint-plugins/",
6
6
  "license": "MIT",
package/src/index.ts CHANGED
@@ -1,15 +1,11 @@
1
- export { default as blankLineAfterControlBlock } from "./rules/blank-line-after-control-block.js";
2
- export { default as blankLineAfterDeclaration } from "./rules/blank-line-after-declaration.js";
3
- export { default as blankLineAfterVariableDeclaration } from "./rules/blank-line-after-variable-declaration.js";
4
- export { default as blankLineBeforeReturn } from "./rules/blank-line-before-return.js";
5
- export { default as blankLineBetweenClassMembers } from "./rules/blank-line-between-class-members.js";
6
- export { default as blankLineBetweenSwitchCases } from "./rules/blank-line-between-switch-cases.js";
1
+ export { default as blankLine } from "./rules/blank-line.js";
7
2
  export { default as commentJapaneseSpacing } from "./rules/comment-japanese-spacing.js";
8
3
  export { default as commentOneSentencePerLine } from "./rules/comment-one-sentence-per-line.js";
9
4
  export { default as jsdocParamOrder } from "./rules/jsdoc-param-order.js";
10
5
  export { default as jsdocTagLines } from "./rules/jsdoc-tag-lines.js";
11
6
  export { default as jsdocTagOrder } from "./rules/jsdoc-tag-order.js";
12
7
  export { default as memberOrdering } from "./rules/member-ordering.js";
8
+ export { default as mergeImports } from "./rules/merge-imports.js";
13
9
  export { default as objectPropertiesNewline } from "./rules/object-properties-newline.js";
14
10
  export { default as overloadSignaturesAdjacent } from "./rules/overload-signatures-adjacent.js";
15
11
  export { default as sortImportExportSpecifiers } from "./rules/sort-import-export-specifiers.js";
package/src/plugin.ts CHANGED
@@ -1,17 +1,13 @@
1
1
  import { definePlugin } from "vite-plus/lint/plugins";
2
2
 
3
- import blankLineAfterControlBlock from "./rules/blank-line-after-control-block.js";
4
- import blankLineAfterDeclaration from "./rules/blank-line-after-declaration.js";
5
- import blankLineAfterVariableDeclaration from "./rules/blank-line-after-variable-declaration.js";
6
- import blankLineBeforeReturn from "./rules/blank-line-before-return.js";
7
- import blankLineBetweenClassMembers from "./rules/blank-line-between-class-members.js";
8
- import blankLineBetweenSwitchCases from "./rules/blank-line-between-switch-cases.js";
3
+ import blankLine from "./rules/blank-line.js";
9
4
  import commentJapaneseSpacing from "./rules/comment-japanese-spacing.js";
10
5
  import commentOneSentencePerLine from "./rules/comment-one-sentence-per-line.js";
11
6
  import jsdocParamOrder from "./rules/jsdoc-param-order.js";
12
7
  import jsdocTagLines from "./rules/jsdoc-tag-lines.js";
13
8
  import jsdocTagOrder from "./rules/jsdoc-tag-order.js";
14
9
  import memberOrdering from "./rules/member-ordering.js";
10
+ import mergeImports from "./rules/merge-imports.js";
15
11
  import objectPropertiesNewline from "./rules/object-properties-newline.js";
16
12
  import overloadSignaturesAdjacent from "./rules/overload-signatures-adjacent.js";
17
13
  import sortImportExportSpecifiers from "./rules/sort-import-export-specifiers.js";
@@ -24,6 +20,8 @@ import typeLiteralPropertiesNewline from "./rules/type-literal-properties-newlin
24
20
  export default definePlugin({
25
21
  meta: { name: "tai-kun" },
26
22
  rules: {
23
+ "blank-line": blankLine,
24
+ "merge-imports": mergeImports,
27
25
  "sort-jsx-props": sortJsxProps,
28
26
  "spaced-comment": spacedComment,
29
27
  "jsdoc-tag-lines": jsdocTagLines,
@@ -32,17 +30,11 @@ export default definePlugin({
32
30
  "jsdoc-param-order": jsdocParamOrder,
33
31
  "sort-type-members": sortTypeMembers,
34
32
  "sort-object-properties": sortObjectProperties,
35
- "blank-line-before-return": blankLineBeforeReturn,
36
33
  "comment-japanese-spacing": commentJapaneseSpacing,
37
34
  "object-properties-newline": objectPropertiesNewline,
38
- "blank-line-after-declaration": blankLineAfterDeclaration,
39
35
  "overload-signatures-adjacent": overloadSignaturesAdjacent,
40
36
  "comment-one-sentence-per-line": commentOneSentencePerLine,
41
37
  "sort-import-export-specifiers": sortImportExportSpecifiers,
42
- "blank-line-after-control-block": blankLineAfterControlBlock,
43
- "blank-line-between-switch-cases": blankLineBetweenSwitchCases,
44
38
  "type-literal-properties-newline": typeLiteralPropertiesNewline,
45
- "blank-line-between-class-members": blankLineBetweenClassMembers,
46
- "blank-line-after-variable-declaration": blankLineAfterVariableDeclaration,
47
39
  },
48
40
  });
@@ -0,0 +1,165 @@
1
+ import type { Fix, Fixer, ESTree, Comment, SourceCode } from "vite-plus/lint/plugins";
2
+
3
+ /**
4
+ * 文の配列を持つ親から、その文が属する配列を取得します。
5
+ */
6
+ function getStatementBody(node: ESTree.Node): readonly ESTree.Node[] | null {
7
+ const { parent } = node;
8
+
9
+ if (parent === null) {
10
+ return null;
11
+ }
12
+
13
+ if (
14
+ parent.type === "Program" ||
15
+ parent.type === "BlockStatement" ||
16
+ parent.type === "StaticBlock" ||
17
+ parent.type === "TSModuleBlock"
18
+ ) {
19
+ return parent.body;
20
+ }
21
+
22
+ if (parent.type === "SwitchCase") {
23
+ return parent.consequent;
24
+ }
25
+
26
+ return null;
27
+ }
28
+
29
+ function getNextStatement(node: ESTree.Node): ESTree.Node | null {
30
+ const body = getStatementBody(node);
31
+
32
+ if (body === null) {
33
+ return null;
34
+ }
35
+
36
+ const index = body.indexOf(node);
37
+
38
+ if (index === -1 || index === body.length - 1) {
39
+ return null;
40
+ }
41
+
42
+ return body[index + 1] ?? null;
43
+ }
44
+
45
+ function getPreviousStatement(node: ESTree.Node): ESTree.Node | null {
46
+ const body = getStatementBody(node);
47
+
48
+ if (body === null) {
49
+ return null;
50
+ }
51
+
52
+ const index = body.indexOf(node);
53
+
54
+ if (index <= 0) {
55
+ return null;
56
+ }
57
+
58
+ return body[index - 1] ?? null;
59
+ }
60
+
61
+ /**
62
+ * 空行の挿入位置を返します。
63
+ *
64
+ * 次の文に付くコメントがある場合は、そのコメントの前を挿入位置にします。
65
+ * 同じ行の末尾コメントは対象外です。
66
+ */
67
+ function getInsertionTarget(
68
+ node: ESTree.Node,
69
+ nextStatement: ESTree.Node,
70
+ sourceCode: SourceCode,
71
+ ): ESTree.Node | Comment {
72
+ return (
73
+ sourceCode
74
+ .getAllComments()
75
+ .find(
76
+ (comment) =>
77
+ comment.range[0] >= node.range[1] &&
78
+ comment.range[1] <= nextStatement.range[0] &&
79
+ comment.loc.start.line > node.loc.end.line,
80
+ ) ?? nextStatement
81
+ );
82
+ }
83
+
84
+ function hasBlankLine(node: ESTree.Node, target: ESTree.Node | Comment): boolean {
85
+ return target.loc.start.line > node.loc.end.line + 1;
86
+ }
87
+
88
+ /**
89
+ * 挿入対象がコメントかどうかを返します。
90
+ *
91
+ * コメントを挟む場合、前後の空行は任意とします。
92
+ */
93
+ function isComment(target: ESTree.Node | Comment): target is Comment {
94
+ const { type } = target as { type: string };
95
+
96
+ return type === "Line" || type === "Block" || type === "Shebang";
97
+ }
98
+
99
+ /**
100
+ * JSDoc 形式のブロックコメント(`/**` で始まる)かどうかを返します。
101
+ *
102
+ * JSDoc 形式のブロックコメントの 1 行上は空行にします。
103
+ */
104
+ function isDocComment(target: ESTree.Node | Comment): target is Comment {
105
+ return isComment(target) && target.type === "Block" && target.value.startsWith("*");
106
+ }
107
+
108
+ function getBlankLineFix(
109
+ fixer: Fixer,
110
+ sourceCode: SourceCode,
111
+ node: ESTree.Node,
112
+ target: ESTree.Node | Comment,
113
+ ): Fix | null {
114
+ if (target.loc.start.line === node.loc.end.line) {
115
+ return fixer.insertTextAfterRange([node.range[1], node.range[1]], "\n\n");
116
+ }
117
+
118
+ const lineEnd = sourceCode.text.indexOf("\n", node.range[1]);
119
+
120
+ if (lineEnd === -1) {
121
+ return null;
122
+ }
123
+
124
+ return fixer.insertTextBeforeRange([lineEnd, lineEnd + 1], "\n");
125
+ }
126
+
127
+ /**
128
+ * 指定したノードと対象の間の空行を削除します。
129
+ */
130
+ function getRemoveBlankLineFix(
131
+ fixer: Fixer,
132
+ sourceCode: SourceCode,
133
+ node: ESTree.Node,
134
+ target: ESTree.Node | Comment,
135
+ ): Fix | null {
136
+ if (target.loc.start.line <= node.loc.end.line + 1) {
137
+ return null;
138
+ }
139
+
140
+ const fromLineEnd = sourceCode.text.indexOf("\n", node.range[1]);
141
+
142
+ if (fromLineEnd === -1) {
143
+ return null;
144
+ }
145
+
146
+ const targetLineStart = sourceCode.text.lastIndexOf("\n", target.range[0]) + 1;
147
+ const indent = sourceCode.text.slice(targetLineStart, target.range[0]);
148
+
149
+ if (indent.trim() !== "") {
150
+ return null;
151
+ }
152
+
153
+ return fixer.replaceTextRange([fromLineEnd, target.range[0]], `\n${indent}`);
154
+ }
155
+
156
+ export {
157
+ isComment,
158
+ hasBlankLine,
159
+ isDocComment,
160
+ getBlankLineFix,
161
+ getNextStatement,
162
+ getInsertionTarget,
163
+ getPreviousStatement,
164
+ getRemoveBlankLineFix,
165
+ };