@agoric/eslint-plugin 0.1.1-dev.0 → 0.1.1-other-dev-d15096d.0.d15096d

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/package.json CHANGED
@@ -1,36 +1,34 @@
1
1
  {
2
2
  "name": "@agoric/eslint-plugin",
3
- "version": "0.1.1-dev.0",
4
- "description": "Agoric-specific ESLint plugin",
3
+ "version": "0.1.1-other-dev-d15096d.0.d15096d",
4
+ "description": "ESLint plugin for Agoric best practices",
5
+ "main": "src/index.js",
6
+ "type": "commonjs",
7
+ "files": [
8
+ "src"
9
+ ],
5
10
  "keywords": [
6
11
  "eslint",
7
12
  "eslintplugin",
8
13
  "eslint-plugin"
9
14
  ],
10
- "author": "Agoric",
11
- "main": "lib/index.js",
12
15
  "scripts": {
13
- "test": "exit 0",
14
16
  "build": "exit 0",
15
- "lint-fix": "exit 0",
16
- "lint-check": "exit 0"
17
+ "lint": "yarn run -T run-s --continue-on-error 'lint:*'",
18
+ "lint:types": "yarn run -T tsc",
19
+ "test": "node --test **/*.test.*",
20
+ "test:xs": "exit 0"
17
21
  },
18
- "dependencies": {
19
- "requireindex": "~1.1.0"
22
+ "peerDependencies": {
23
+ "eslint": "^9.0.0"
20
24
  },
21
25
  "devDependencies": {
22
- "eslint": "^6.8.0"
26
+ "eslint": "^9.0.0",
27
+ "eslint-plugin-eslint-plugin": "^7.2.0"
23
28
  },
29
+ "license": "Apache-2.0",
24
30
  "engines": {
25
- "node": ">=0.10.0"
26
- },
27
- "publishConfig": {
28
- "access": "public"
31
+ "node": "^20.9 || ^22.11"
29
32
  },
30
- "prettier": {
31
- "trailingComma": "all",
32
- "singleQuote": true
33
- },
34
- "license": "Apache-2.0",
35
- "gitHead": "6b1b4f605ab0fa22c6caba3eef347ec97f35b667"
33
+ "gitHead": "d15096dc4ff8b96e9b6cd11954c20d3a9efbb393"
36
34
  }
package/src/index.js ADDED
@@ -0,0 +1,34 @@
1
+ const fs = require('node:fs');
2
+ const path = require('path');
3
+
4
+ const pkg = JSON.parse(
5
+ fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8'),
6
+ );
7
+
8
+ // Import rules
9
+ const noTypedefImport = require('./rules/no-typedef-import.js');
10
+ const groupJsdocImports = require('./rules/group-jsdoc-imports.js');
11
+
12
+ module.exports = {
13
+ meta: {
14
+ name: pkg.name,
15
+ version: pkg.version,
16
+ },
17
+
18
+ // Rule definitions
19
+ rules: {
20
+ 'no-typedef-import': noTypedefImport,
21
+ 'group-jsdoc-imports': groupJsdocImports,
22
+ },
23
+
24
+ // Recommended config
25
+ configs: {
26
+ recommended: {
27
+ plugins: ['@agoric'],
28
+ rules: {
29
+ '@agoric/no-typedef-import': 'error',
30
+ '@agoric/group-jsdoc-imports': 'warn',
31
+ },
32
+ },
33
+ },
34
+ };
@@ -0,0 +1,311 @@
1
+ /**
2
+ * ESLint rule: group-jsdoc-imports
3
+ *
4
+ * Moves inline JSDoc type imports (e.g. \@type {import('foo').Bar})
5
+ * into a top-level JSDoc block with \@import lines, then references the
6
+ * import by name (e.g. \@type {Bar}).
7
+ *
8
+ * Usage example in your .eslintrc.js:
9
+ *
10
+ * {
11
+ * "plugins": ["@agoric"],
12
+ * "rules": {
13
+ * "@agoric/group-jsdoc-imports": "warning"
14
+ * }
15
+ * }
16
+ *
17
+ * @type {import('eslint').Rule.RuleModule}
18
+ */
19
+ /**
20
+ * ESLint rule: group-jsdoc-imports (one-fix-per-inline-import version)
21
+ */
22
+
23
+ module.exports = {
24
+ meta: {
25
+ type: /** @type {const} */ ('suggestion'),
26
+ docs: {
27
+ description: 'Move inline type import to top-level JSDoc import block',
28
+ category: 'Stylistic Issues',
29
+ recommended: false,
30
+ },
31
+ fixable: /** @type {const} */ ('code'),
32
+ schema: [
33
+ {
34
+ type: 'object',
35
+ properties: {
36
+ paths: {
37
+ type: 'array',
38
+ items: { type: 'string' },
39
+ },
40
+ },
41
+ additionalProperties: false,
42
+ },
43
+ ],
44
+ messages: {
45
+ moveInline: 'Move inline type import to top-level JSDoc import block',
46
+ },
47
+ },
48
+
49
+ create(context) {
50
+ const sourceCode = context.getSourceCode();
51
+ const { paths: allowedPaths = [] } = context.options[0] || {};
52
+
53
+ // Use the `g` flag so we can match multiple inline imports in one comment.
54
+ const INLINE_IMPORT_REGEX =
55
+ /import\(['"]([^'"]+)['"]\)\.([A-Za-z0-9_$]+(?:<[A-Za-z0-9_<>{},\s]+>)?)/g;
56
+
57
+ function isAllowedPath(importPath) {
58
+ if (
59
+ importPath.startsWith('./') ||
60
+ importPath.startsWith('../') ||
61
+ importPath === '.' ||
62
+ importPath === '..'
63
+ ) {
64
+ return true; // always allow relative paths
65
+ }
66
+ if (!allowedPaths.length) {
67
+ return true; // no filtering if no paths configured
68
+ }
69
+ return allowedPaths.some(prefix => importPath.startsWith(prefix));
70
+ }
71
+
72
+ /**
73
+ * Finds an existing top-level `@import` block comment (one that contains "@import")
74
+ * or returns `null` if none exists.
75
+ */
76
+ function findTopBlockComment(allComments) {
77
+ for (const comment of allComments) {
78
+ if (comment.type === 'Block') {
79
+ // Rebuild with the /* ... */ so we can search for "@import"
80
+ const text = `/*${comment.value}*/`;
81
+ if (text.includes('@import ')) {
82
+ return comment;
83
+ }
84
+ }
85
+ }
86
+ return null;
87
+ }
88
+
89
+ /**
90
+ * Checks if the doc block already imports a specific type from a path,
91
+ * returning `true` if found.
92
+ */
93
+ function alreadyHasImport(blockValue, typeName, importPath) {
94
+ // blockValue is the text inside /* ... */
95
+ // Look for lines like: @import {Type} from 'xyz'
96
+ // Possibly could handle multiple types in one line, but let's keep it simple:
97
+ const lines = blockValue.split('\n');
98
+ for (const line of lines) {
99
+ const m = line.match(/@import\s+{([^}]+)}\s+from\s+['"]([^'"]+)['"]/);
100
+ if (m) {
101
+ const importedTypes = m[1].split(',').map(s => s.trim());
102
+ const fromPath = m[2];
103
+ if (fromPath === importPath && importedTypes.includes(typeName)) {
104
+ return true; // Found a matching import already
105
+ }
106
+ }
107
+ }
108
+ return false;
109
+ }
110
+
111
+ const allComments = sourceCode.getAllComments();
112
+
113
+ const buildImportLine = (typeName, importPath) =>
114
+ ` * @import {${typeName}} from '${importPath}';\n`;
115
+
116
+ const buildNewBlock = (typeName, importPath) =>
117
+ ['/**', buildImportLine(typeName, importPath).trimEnd(), ' */', ''].join(
118
+ '\n',
119
+ );
120
+
121
+ const appendImportToComment = (commentNode, typeName, importPath) => {
122
+ const existingText = sourceCode.getText(commentNode);
123
+ const closingIndex = existingText.lastIndexOf('*/');
124
+ const importLine = buildImportLine(typeName, importPath);
125
+
126
+ if (closingIndex === -1) {
127
+ return `${existingText}\n${importLine}`;
128
+ }
129
+
130
+ const beforeCloseFull = existingText.slice(0, closingIndex);
131
+ const lastNewlineIndex = beforeCloseFull.lastIndexOf('\n');
132
+ let beforeClose = beforeCloseFull;
133
+ let closingIndent = '';
134
+
135
+ if (lastNewlineIndex !== -1) {
136
+ const tail = beforeCloseFull.slice(lastNewlineIndex + 1);
137
+ if (/^[\t ]*$/.test(tail)) {
138
+ closingIndent = tail;
139
+ beforeClose = beforeCloseFull.slice(0, lastNewlineIndex + 1);
140
+ }
141
+ } else {
142
+ beforeClose = beforeCloseFull.trimEnd();
143
+ }
144
+
145
+ const suffixIndent =
146
+ closingIndent !== ''
147
+ ? closingIndent
148
+ : existingText.startsWith('/*')
149
+ ? ' '
150
+ : '';
151
+ const suffix = `${suffixIndent}${existingText.slice(closingIndex)}`;
152
+ const needsNewline = beforeClose.endsWith('\n') ? '' : '\n';
153
+
154
+ return `${beforeClose}${needsNewline}${importLine}${suffix}`;
155
+ };
156
+
157
+ const advancePastWhitespaceNewline = startIndex => {
158
+ const match = sourceCode.text.slice(startIndex).match(/^[^\S\r\n]*\r?\n/);
159
+ if (match) {
160
+ return { matched: true, nextIndex: startIndex + match[0].length };
161
+ }
162
+ return { matched: false, nextIndex: startIndex };
163
+ };
164
+
165
+ const getNewBlockInsertPlacement = () => {
166
+ const programBody = sourceCode.ast.body || [];
167
+ const importNodes = programBody.filter(
168
+ node => node.type === 'ImportDeclaration',
169
+ );
170
+ const firstContentIndex = sourceCode.text.search(/\S/);
171
+ let insertIndex = firstContentIndex === -1 ? 0 : firstContentIndex;
172
+ let prefix = '';
173
+ let needsTrailingBlankLine = false;
174
+
175
+ if (importNodes.length) {
176
+ insertIndex = importNodes[importNodes.length - 1].range[1];
177
+
178
+ let step = advancePastWhitespaceNewline(insertIndex);
179
+ const hasNewlineAfterImports = step.matched;
180
+ insertIndex = step.nextIndex;
181
+
182
+ step = advancePastWhitespaceNewline(insertIndex);
183
+ const hasBlankLine = step.matched;
184
+ insertIndex = step.nextIndex;
185
+
186
+ if (!hasNewlineAfterImports) {
187
+ prefix += '\n';
188
+ }
189
+ if (!hasBlankLine) {
190
+ prefix += '\n';
191
+ } else {
192
+ needsTrailingBlankLine = true;
193
+ }
194
+ } else {
195
+ const blankLineMatch = /\r?\n[^\S\r\n]*\r?\n/.exec(sourceCode.text);
196
+ if (blankLineMatch) {
197
+ insertIndex = blankLineMatch.index + blankLineMatch[0].length;
198
+ needsTrailingBlankLine = true;
199
+ }
200
+ }
201
+
202
+ return { insertIndex, prefix, needsTrailingBlankLine };
203
+ };
204
+
205
+ // Walk all block comments and look for inline imports.
206
+ for (const comment of allComments) {
207
+ if (comment.type !== 'Block') {
208
+ continue;
209
+ }
210
+ const { value: commentText } = comment;
211
+
212
+ // We collect all matches in this comment for `import('...').SomeType`
213
+ const matches = [...commentText.matchAll(INLINE_IMPORT_REGEX)];
214
+ for (const match of matches) {
215
+ const [fullMatch, importPath, rawTypeName] = match;
216
+ if (!isAllowedPath(importPath)) {
217
+ continue; // skip if path is not in allowedPaths
218
+ }
219
+ const typeName =
220
+ typeof rawTypeName === 'string'
221
+ ? rawTypeName
222
+ : String(rawTypeName ?? '');
223
+ const importTypeName = typeName.includes('<')
224
+ ? typeName.slice(0, typeName.indexOf('<'))
225
+ : typeName;
226
+
227
+ // We have an inline import. We'll report exactly one error
228
+ // for *this* inline import. The fix will:
229
+ // 1) Insert/update the doc block
230
+ // 2) Remove inline usage from this comment
231
+ context.report({
232
+ loc: comment.loc,
233
+ messageId: 'moveInline',
234
+ fix: fixer => {
235
+ // We'll build a set of fix operations for both the doc block
236
+ // (somewhere in the file) and this inline usage.
237
+ const fixOps = [];
238
+
239
+ const inlineStart =
240
+ comment.range[0] +
241
+ 2 +
242
+ (match.index ?? commentText.indexOf(fullMatch));
243
+ const inlineEnd = inlineStart + fullMatch.length;
244
+
245
+ // (a) We locate or create a top-level block
246
+ const topBlockComment = findTopBlockComment(allComments);
247
+ const topBlockIsSameAsComment =
248
+ topBlockComment &&
249
+ topBlockComment.range[0] === comment.range[0] &&
250
+ topBlockComment.range[1] === comment.range[1];
251
+
252
+ if (!topBlockComment) {
253
+ // If no block with @import found, create a new block at top
254
+ const {
255
+ insertIndex,
256
+ prefix: newBlockPrefix,
257
+ needsTrailingBlankLine,
258
+ } = getNewBlockInsertPlacement();
259
+ const trailingSpacer = needsTrailingBlankLine ? '\n' : '';
260
+ fixOps.push(
261
+ fixer.insertTextBeforeRange(
262
+ [insertIndex, insertIndex],
263
+ `${newBlockPrefix}${buildNewBlock(importTypeName, importPath)}${trailingSpacer}`,
264
+ ),
265
+ );
266
+ } else if (topBlockIsSameAsComment) {
267
+ fixOps.push(
268
+ fixer.insertTextBeforeRange(
269
+ [comment.range[0], comment.range[0]],
270
+ `${buildNewBlock(importTypeName, importPath)}\n`,
271
+ ),
272
+ );
273
+ } else {
274
+ // If we do have a block, ensure it includes `@import {typeName} from 'importPath'`
275
+ if (
276
+ !alreadyHasImport(
277
+ topBlockComment.value,
278
+ importTypeName,
279
+ importPath,
280
+ )
281
+ ) {
282
+ fixOps.push(
283
+ fixer.replaceTextRange(
284
+ topBlockComment.range,
285
+ appendImportToComment(
286
+ topBlockComment,
287
+ importTypeName,
288
+ importPath,
289
+ ),
290
+ ),
291
+ );
292
+ }
293
+ }
294
+
295
+ // (b) Remove the inline usage from *this* comment
296
+ // Replace `import('...').Foo` → `Foo`
297
+ fixOps.push(
298
+ fixer.replaceTextRange([inlineStart, inlineEnd], typeName),
299
+ );
300
+
301
+ return fixOps;
302
+ },
303
+ });
304
+ }
305
+ }
306
+
307
+ // We do NOT do anything in Program:exit, because each inline usage
308
+ // is already handled in a single fix above.
309
+ return {};
310
+ },
311
+ };
@@ -0,0 +1,147 @@
1
+ /**
2
+ * ESLint rule: no-typedef-import
3
+ *
4
+ * Finds inline `import()` expressions inside `@typedef` declarations and replaces
5
+ * them with a corresponding `@import` directive. This prevents generating new type aliases
6
+ * and unwittingly exporting them from the module.
7
+ *
8
+ * If the module should be exporting the types, `@typedef` is still the only way in JSDoc
9
+ * so disable this rule in those files.
10
+ *
11
+ * @see https://github.com/microsoft/typescript/issues/60831
12
+ */
13
+
14
+ const LINE_REGEX =
15
+ /^(\s*\*?\s*)@typedef\s+\{\s*import\((['"])([^'"]+)\2\)\.([A-Za-z0-9_$]+)([^}]*)\}\s+([A-Za-z0-9_$]+)(.*)$/;
16
+
17
+ const getConversionPlan = value => {
18
+ const lines = value.split('\n');
19
+ const convertible = [];
20
+
21
+ for (let index = 0; index < lines.length; index += 1) {
22
+ const line = lines[index];
23
+ const match = line.match(LINE_REGEX);
24
+ if (!match) {
25
+ continue;
26
+ }
27
+
28
+ const [
29
+ ,
30
+ indent,
31
+ quote,
32
+ importPath,
33
+ importedType,
34
+ rawSuffix = '',
35
+ ,
36
+ // typedefName (unused),
37
+ trailing = '',
38
+ ] = match;
39
+
40
+ if (rawSuffix && rawSuffix.trim() !== '') {
41
+ continue; // skip typedefs that add generics or other suffixes
42
+ }
43
+
44
+ convertible.push({
45
+ index,
46
+ indent,
47
+ quote,
48
+ importPath,
49
+ importedType,
50
+ trailing,
51
+ });
52
+ }
53
+
54
+ return { lines, convertible };
55
+ };
56
+
57
+ const transformCommentValue = value => {
58
+ const { lines, convertible } = getConversionPlan(value);
59
+ if (!convertible.length) {
60
+ return null;
61
+ }
62
+
63
+ for (const {
64
+ index,
65
+ indent,
66
+ quote,
67
+ importPath,
68
+ importedType,
69
+ trailing,
70
+ } of convertible) {
71
+ const trailingText = trailing || '';
72
+ lines[index] =
73
+ `${indent}@import {${importedType}} from ${quote}${importPath}${quote};${trailingText}`;
74
+ }
75
+
76
+ return lines.join('\n');
77
+ };
78
+
79
+ /** @type {import('eslint').Rule.RuleModule} */
80
+ module.exports = {
81
+ meta: {
82
+ type: 'problem',
83
+ docs: {
84
+ description:
85
+ 'Disallow inline import() expressions inside @typedef; prefer @import directives.',
86
+ recommended: false,
87
+ },
88
+ fixable: 'code',
89
+ schema: [],
90
+ messages: {
91
+ noTypedefImport:
92
+ 'Use an @import directive instead of an inline import() inside @typedef.',
93
+ },
94
+ },
95
+
96
+ create(context) {
97
+ const sourceCode = context.getSourceCode();
98
+
99
+ return {
100
+ Program() {
101
+ for (const comment of sourceCode.getAllComments()) {
102
+ if (comment.type !== 'Block') {
103
+ continue;
104
+ }
105
+ if (!comment.value.includes('@typedef')) {
106
+ continue;
107
+ }
108
+
109
+ const { convertible } = getConversionPlan(comment.value);
110
+ if (!convertible.length) {
111
+ continue;
112
+ }
113
+
114
+ const { range, loc } = comment;
115
+ if (!range) {
116
+ continue;
117
+ }
118
+
119
+ const originalText = sourceCode.text.slice(range[0], range[1]);
120
+ const reportLoc = loc ?? {
121
+ start: sourceCode.getLocFromIndex(range[0]),
122
+ end: sourceCode.getLocFromIndex(range[1]),
123
+ };
124
+
125
+ const descriptor = {
126
+ loc: reportLoc,
127
+ messageId: 'noTypedefImport',
128
+ fix(fixer) {
129
+ const newValue = transformCommentValue(comment.value);
130
+ if (!newValue) {
131
+ return null;
132
+ }
133
+
134
+ const newCommentText = originalText.replace(
135
+ comment.value,
136
+ newValue,
137
+ );
138
+ return fixer.replaceTextRange(range, newCommentText);
139
+ },
140
+ };
141
+
142
+ context.report(descriptor);
143
+ }
144
+ },
145
+ };
146
+ },
147
+ };
package/CHANGELOG.md DELETED
@@ -1,19 +0,0 @@
1
- # Change Log
2
-
3
- All notable changes to this project will be documented in this file.
4
- See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
-
6
- ## [0.1.1-dev.0](https://github.com/Agoric/agoric-sdk/compare/@agoric/eslint-plugin@0.1.0...@agoric/eslint-plugin@0.1.1-dev.0) (2021-02-23)
7
-
8
- **Note:** Version bump only for package @agoric/eslint-plugin
9
-
10
-
11
-
12
-
13
-
14
- # 0.1.0 (2021-02-16)
15
-
16
-
17
- ### Features
18
-
19
- * make @agoric/eslint-plugin deal with assert.fail as throw ([f23adee](https://github.com/Agoric/agoric-sdk/commit/f23adee512aec50788d9c9efed1cea9d774dfe8f))
package/README.md DELETED
@@ -1,51 +0,0 @@
1
- # eslint-plugin-agoric
2
-
3
- Agoric-specific plugin
4
-
5
- ## Installation
6
-
7
- You'll first need to install [ESLint](http://eslint.org):
8
-
9
- ```
10
- $ npm i eslint --save-dev
11
- ```
12
-
13
- Next, install `eslint-plugin-agoric`:
14
-
15
- ```
16
- $ npm install eslint-plugin-agoric --save-dev
17
- ```
18
-
19
- **Note:** If you installed ESLint globally (using the `-g` flag) then you must also install `eslint-plugin-agoric` globally.
20
-
21
- ## Usage
22
-
23
- Add `agoric` to the plugins section of your `.eslintrc` configuration file. You can omit the `eslint-plugin-` prefix:
24
-
25
- ```json
26
- {
27
- "plugins": [
28
- "agoric"
29
- ]
30
- }
31
- ```
32
-
33
-
34
- Then configure the rules you want to use under the rules section.
35
-
36
- ```json
37
- {
38
- "rules": {
39
- "agoric/rule-name": 2
40
- }
41
- }
42
- ```
43
-
44
- ## Supported Rules
45
-
46
- * Fill in provided rules here
47
-
48
-
49
-
50
-
51
-
@@ -1,6 +0,0 @@
1
- module.exports = {
2
- plugins: ["@agoric"],
3
- rules: {
4
- "@agoric/assert-fail-as-throw": 2
5
- },
6
- };
package/lib/index.js DELETED
@@ -1,20 +0,0 @@
1
- /**
2
- * @fileoverview Agoric-specific plugin
3
- * @author Agoric
4
- */
5
- "use strict";
6
-
7
- //------------------------------------------------------------------------------
8
- // Requirements
9
- //------------------------------------------------------------------------------
10
-
11
- var requireIndex = require("requireindex");
12
-
13
- //------------------------------------------------------------------------------
14
- // Plugin Definition
15
- //------------------------------------------------------------------------------
16
-
17
-
18
- // import all rules in lib/rules
19
- module.exports.rules = requireIndex(__dirname + "/rules");
20
- module.exports.configs = requireIndex(__dirname + "/configs");
@@ -1,167 +0,0 @@
1
- /**
2
- * @author Toru Nagashima
3
- * See LICENSE file in root directory for full license.
4
- *
5
- * Modified by Michael FIG <mfig@agoric.com> for Agoric's assert.fail.
6
- * (This file used to be github.com/mysticatea/eslint-plugin-node/.../process-exit-as-throw.js.)
7
- */
8
- "use strict"
9
-
10
- const CodePathAnalyzer = safeRequire(
11
- "eslint/lib/linter/code-path-analysis/code-path-analyzer",
12
- "eslint/lib/code-path-analysis/code-path-analyzer"
13
- )
14
- const CodePathSegment = safeRequire(
15
- "eslint/lib/linter/code-path-analysis/code-path-segment",
16
- "eslint/lib/code-path-analysis/code-path-segment"
17
- )
18
- const CodePath = safeRequire(
19
- "eslint/lib/linter/code-path-analysis/code-path",
20
- "eslint/lib/code-path-analysis/code-path"
21
- )
22
-
23
- const originalLeaveNode =
24
- CodePathAnalyzer && CodePathAnalyzer.prototype.leaveNode
25
-
26
- /**
27
- * Imports a specific module.
28
- * @param {...string} moduleNames - module names to import.
29
- * @returns {object|null} The imported object, or null.
30
- */
31
- function safeRequire(...moduleNames) {
32
- for (const moduleName of moduleNames) {
33
- try {
34
- return require(moduleName)
35
- } catch (_err) {
36
- // Ignore.
37
- }
38
- }
39
- return null
40
- }
41
-
42
- /* istanbul ignore next */
43
- /**
44
- * Copied from https://github.com/eslint/eslint/blob/16fad5880bb70e9dddbeab8ed0f425ae51f5841f/lib/code-path-analysis/code-path-analyzer.js#L137
45
- *
46
- * @param {CodePathAnalyzer} analyzer - The instance.
47
- * @param {ASTNode} node - The current AST node.
48
- * @returns {void}
49
- */
50
- function forwardCurrentToHead(analyzer, node) {
51
- const codePath = analyzer.codePath
52
- const state = CodePath.getState(codePath)
53
- const currentSegments = state.currentSegments
54
- const headSegments = state.headSegments
55
- const end = Math.max(currentSegments.length, headSegments.length)
56
- let i = 0
57
- let currentSegment = null
58
- let headSegment = null
59
-
60
- // Fires leaving events.
61
- for (i = 0; i < end; ++i) {
62
- currentSegment = currentSegments[i]
63
- headSegment = headSegments[i]
64
-
65
- if (currentSegment !== headSegment && currentSegment) {
66
- if (currentSegment.reachable) {
67
- analyzer.emitter.emit(
68
- "onCodePathSegmentEnd",
69
- currentSegment,
70
- node
71
- )
72
- }
73
- }
74
- }
75
-
76
- // Update state.
77
- state.currentSegments = headSegments
78
-
79
- // Fires entering events.
80
- for (i = 0; i < end; ++i) {
81
- currentSegment = currentSegments[i]
82
- headSegment = headSegments[i]
83
-
84
- if (currentSegment !== headSegment && headSegment) {
85
- CodePathSegment.markUsed(headSegment)
86
- if (headSegment.reachable) {
87
- analyzer.emitter.emit(
88
- "onCodePathSegmentStart",
89
- headSegment,
90
- node
91
- )
92
- }
93
- }
94
- }
95
- }
96
-
97
- /**
98
- * Checks whether a given node is `assert.fail()` or not.
99
- *
100
- * @param {ASTNode} node - A node to check.
101
- * @returns {boolean} `true` if the node is `assert.fail()`.
102
- */
103
- function isAssertFail(node) {
104
- return (
105
- node.type === "CallExpression" &&
106
- node.callee.type === "MemberExpression" &&
107
- node.callee.computed === false &&
108
- node.callee.object.type === "Identifier" &&
109
- node.callee.object.name === "assert" &&
110
- node.callee.property.type === "Identifier" &&
111
- node.callee.property.name === "fail"
112
- )
113
- }
114
-
115
- /**
116
- * The function to override `CodePathAnalyzer.prototype.leaveNode` in order to
117
- * address `assert.fail()` as throw.
118
- *
119
- * @this CodePathAnalyzer
120
- * @param {ASTNode} node - A node to be left.
121
- * @returns {void}
122
- */
123
- function overrideLeaveNode(node) {
124
- if (isAssertFail(node)) {
125
- this.currentNode = node
126
-
127
- forwardCurrentToHead(this, node)
128
- CodePath.getState(this.codePath).makeThrow()
129
-
130
- this.original.leaveNode(node)
131
- this.currentNode = null
132
- } else {
133
- originalLeaveNode.call(this, node)
134
- }
135
- }
136
-
137
- const visitor =
138
- CodePathAnalyzer == null
139
- ? {}
140
- : {
141
- Program: function installAssertFailAsThrow() {
142
- CodePathAnalyzer.prototype.leaveNode = overrideLeaveNode
143
- },
144
- "Program:exit": function restoreAssertFailAsThrow() {
145
- CodePathAnalyzer.prototype.leaveNode = originalLeaveNode
146
- },
147
- }
148
-
149
- module.exports = {
150
- meta: {
151
- docs: {
152
- description:
153
- "make `assert.fail()` expressions the same code path as `throw`",
154
- category: "Possible Errors",
155
- recommended: true,
156
- url:
157
- "https://github.com/Agoric/agoric-sdk/blob/master/packages/eslint-plugin/lib/rules/assert-fail-as-throw.js",
158
- },
159
- type: "problem",
160
- fixable: null,
161
- schema: [],
162
- supported: true || CodePathAnalyzer != null,
163
- },
164
- create() {
165
- return visitor
166
- },
167
- }