eslint-rule-forge 0.0.0-stage → 0.2.0

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/README.md CHANGED
@@ -1,3 +1,212 @@
1
- # Temporary Holding Version
1
+ # eslint-rule-forge
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Helpers for writing [typescript-eslint](https://typescript-eslint.io/) rules
4
+ that are hard to fool: they see through type wrappers and parentheses, and
5
+ resolve what a file imports however it is written.
6
+
7
+ A rule that matches `Number(x)` but not `(Number as NumberConstructor)(x)` has
8
+ a hole a wrapper slips through, and one that asks the type of `x as string`
9
+ trusts a claim the checker never verified. These are the helpers the
10
+ `eslint-plugin-ts-*` packages and `eslint-config-typed` share for that, in one
11
+ place, so that a fix to one of them reaches every rule.
12
+
13
+ ## Installation
14
+
15
+ ```sh
16
+ npm install eslint-rule-forge
17
+ ```
18
+
19
+ `@typescript-eslint/utils` comes with it; `eslint` and `typescript` are peer
20
+ dependencies.
21
+
22
+ ## Type wrappers
23
+
24
+ `x as T`, `x!`, `x satisfies T` and `<T>x` change a type and never a value.
25
+
26
+ | Helper | What it gives |
27
+ | :------------------ | :------------------------------------------------------------------------------------ |
28
+ | `isTypeWrapper` | whether a node is one of the four |
29
+ | `skipTypeWrappers` | the expression inside every wrapper around a node: judge syntax on this |
30
+ | `typeWrapperLayers` | the node and every expression inside its wrappers, outermost first: ask types of each |
31
+ | `TypeWrapper` | the four node types |
32
+
33
+ All of them take a readonly (`DeepReadonly<TSESTree.Node>`) or a mutable node
34
+ and give back the same kind.
35
+
36
+ Judge syntax on what `skipTypeWrappers` returns, and write the fix from the
37
+ original node, so that the wrapper is kept:
38
+
39
+ ```ts
40
+ import { AST_NODE_TYPES, type TSESLint } from '@typescript-eslint/utils';
41
+ import { getArgumentText, skipTypeWrappers } from 'eslint-rule-forge';
42
+
43
+ // Reports `Number(x)`, also written `(Number as NumberConstructor)(x)` or
44
+ // `Number!(x)`, and rewrites it to `toNumber(x)`.
45
+ export const noNumberCall: TSESLint.RuleModule<'noNumberCall'> = {
46
+ meta: {
47
+ type: 'suggestion',
48
+ messages: { noNumberCall: 'Use `toNumber` instead of `Number`.' },
49
+ fixable: 'code',
50
+ schema: [],
51
+ },
52
+ defaultOptions: [],
53
+ create: (context) => ({
54
+ CallExpression: (node) => {
55
+ // Judge the syntax on the expression inside the wrappers ...
56
+ const callee = skipTypeWrappers(node.callee);
57
+
58
+ const [argument] = node.arguments;
59
+
60
+ if (
61
+ argument === undefined ||
62
+ callee.type !== AST_NODE_TYPES.Identifier ||
63
+ callee.name !== 'Number'
64
+ ) {
65
+ return;
66
+ }
67
+
68
+ context.report({
69
+ node,
70
+ messageId: 'noNumberCall',
71
+ // ... and write the fix from the original nodes, keeping a sequence
72
+ // argument `(a, b)` one argument.
73
+ fix: (fixer) =>
74
+ fixer.replaceText(
75
+ node,
76
+ `toNumber(${getArgumentText(context.sourceCode, argument)})`,
77
+ ),
78
+ });
79
+ },
80
+ }),
81
+ } as const;
82
+ ```
83
+
84
+ A conclusion drawn from a type — that a guard always holds, that a value is an
85
+ array — has to hold at every layer `typeWrapperLayers` returns. A widening
86
+ assertion (`x as string | null`) then makes the rule more cautious, and a
87
+ narrowing one (`x!`, `v as string` on an `unknown`), which the checker cannot
88
+ verify, changes nothing.
89
+
90
+ ## Negation
91
+
92
+ Writing the negation of a condition the short way, as a fix that removes a
93
+ ternary or turns a filter into a loop has to.
94
+
95
+ | Helper | What it gives |
96
+ | :---------------------------- | :------------------------------------------------------------------------------------------------------------------------ |
97
+ | `negationOf` | `a !== b` for `a === b`, `!a && !b` for `a \|\| b`, `a` for `!a` (when a boolean), else `!a`; parenthesized as an operand |
98
+ | `prefixedNegationOf` | `!a`, `!f(x)`, `!(a === b)`: a `!` in front, with parentheses only when it needs them |
99
+ | `isComparison` | whether a node is an equality or a relational comparison |
100
+ | `isExactlyInvertible` | whether inverting a comparison's operator is its exact negation: always for an equality, for `<` only without `NaN` |
101
+ | `invertedComparisonText` | the comparison's source with its operator inverted |
102
+ | `needsParenthesesAsOperandOf` | whether a node needs parentheses as an operand of `&&` or `\|\|` |
103
+ | `createGetLayerTypes` | a function giving a node's type at every type-wrapper layer, which the checks above ask |
104
+
105
+ `negationOf` gives `undefined` when the only exact negation is `!!a` (for an
106
+ `a` that may not be a boolean) or `!(a < b)` (for operands that may be `NaN`),
107
+ so that a rule can choose between `prefixedNegationOf` and giving up. Where
108
+ only the truthiness of the negation is read, such as the test of an `if`, its
109
+ context may call every node a boolean.
110
+
111
+ ## Parentheses
112
+
113
+ The range and the text of a node leave out the parentheses written around it.
114
+
115
+ | Helper | What it gives |
116
+ | :------------------- | :------------------------------------------------------------------ |
117
+ | `parenthesesDepth` | how many pairs of parentheses surround a node |
118
+ | `getRangeWithParens` | the node's range including them |
119
+ | `getArgumentText` | the node's text for an argument list, `(a, b)` kept as one argument |
120
+
121
+ ## Imports and bindings
122
+
123
+ | Helper | What it gives |
124
+ | :---------------------- | :--------------------------------------------------------------------------------------------------- |
125
+ | `getImportDeclarations` | every `import … from '<module>'` in the file, not only the first |
126
+ | `getNamedImports` | the export names those declarations import |
127
+ | `getImportedLocalName` | the local name an export is imported as (`'y'` for `import { x as y }`) |
128
+ | `buildCalleeResolver` | which export a callee calls, through aliases, namespace imports and type wrappers |
129
+ | `buildNamedImportFix` | a fix inserting `import { … } from '<module>';`, for an import sorter to place |
130
+ | `hasForeignBinding` | whether a name, at a node, is bound to something other than the module's import (a fix must give up) |
131
+ | `isLocallyBound` | whether a name, at a node, is declared in the file rather than a global or a standard-library type |
132
+
133
+ ```ts
134
+ import type { TSESLint } from '@typescript-eslint/utils';
135
+ import {
136
+ buildCalleeResolver,
137
+ buildNamedImportFix,
138
+ getImportDeclarations,
139
+ getImportedLocalName,
140
+ hasForeignBinding,
141
+ } from 'eslint-rule-forge';
142
+
143
+ const MODULE = 'my-lib';
144
+
145
+ // Rewrites a call to `isNull` from `my-lib`, however it is imported, to
146
+ // `isNullish` from the same module, adding the import when it is missing.
147
+ export const preferIsNullish: TSESLint.RuleModule<'preferIsNullish'> = {
148
+ meta: {
149
+ type: 'suggestion',
150
+ messages: { preferIsNullish: 'Use `isNullish`.' },
151
+ fixable: 'code',
152
+ schema: [],
153
+ },
154
+ defaultOptions: [],
155
+ create: (context) => {
156
+ const program = context.sourceCode.ast;
157
+
158
+ const declarations = getImportDeclarations(program, MODULE);
159
+
160
+ // `isNull(x)`, `n(x)` after `import { isNull as n }` and `lib.isNull(x)`
161
+ // after `import * as lib` all call `isNull`.
162
+ const resolve = buildCalleeResolver(declarations);
163
+
164
+ return {
165
+ CallExpression: (node) => {
166
+ const resolved = resolve(node.callee);
167
+
168
+ if (resolved?.canonicalName !== 'isNull') {
169
+ return;
170
+ }
171
+
172
+ const importedAs = getImportedLocalName(
173
+ declarations,
174
+ 'isNullish',
175
+ );
176
+
177
+ const name = resolved.isNamespace
178
+ ? 'isNullish'
179
+ : (importedAs ?? 'isNullish');
180
+
181
+ // A local `isNullish` that is not `my-lib`'s would capture the call.
182
+ const canFix =
183
+ resolved.isNamespace ||
184
+ !hasForeignBinding(context.sourceCode, node, name, MODULE);
185
+
186
+ context.report({
187
+ node,
188
+ messageId: 'preferIsNullish',
189
+ fix: canFix
190
+ ? (fixer) => [
191
+ ...(importedAs !== undefined ||
192
+ resolved.isNamespace
193
+ ? []
194
+ : buildNamedImportFix(
195
+ fixer,
196
+ program,
197
+ MODULE,
198
+ [name],
199
+ )),
200
+ fixer.replaceText(resolved.propertyNode, name),
201
+ ]
202
+ : null,
203
+ });
204
+ },
205
+ };
206
+ },
207
+ } as const;
208
+ ```
209
+
210
+ ## License
211
+
212
+ [Apache-2.0](https://github.com/noshiro-pf/mono/blob/main/libs/eslint-rule-forge/LICENSE)
@@ -0,0 +1,23 @@
1
+ import { type TSESLint, type TSESTree } from '@typescript-eslint/utils';
2
+ /**
3
+ * Whether `name`, read at `node`, resolves to something this file writes down
4
+ * — a declaration, a parameter, an import — rather than to a global or a
5
+ * standard-library type of the same name.
6
+ *
7
+ * The scope manager makes an implicit variable for every reference it cannot
8
+ * resolve, so `findVariable` finds `Exclude` in a file that never declares it;
9
+ * only a variable with a definition was written in the file.
10
+ */
11
+ export declare const isLocallyBound: (sourceCode: TSESLint.SourceCode, node: TSESTree.Node, name: string) => boolean;
12
+ /**
13
+ * Whether `name`, read at `node`, resolves to a binding that is not an import
14
+ * from `moduleName` — a declaration, a parameter, or an import from another
15
+ * module. A fix that makes code at `node` refer to `moduleName`'s export
16
+ * `name` has to give up then, because the name would refer to that binding
17
+ * instead.
18
+ *
19
+ * The innermost binding decides: an import from `moduleName` at the top of the
20
+ * file does not help a name a function shadows around `node`.
21
+ */
22
+ export declare const hasForeignBinding: (sourceCode: TSESLint.SourceCode, node: TSESTree.Node, name: string, moduleName: string) => boolean;
23
+ //# sourceMappingURL=bindings.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bindings.d.mts","sourceRoot":"","sources":["../src/bindings.mts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,QAAQ,EACb,KAAK,QAAQ,EACd,MAAM,0BAA0B,CAAC;AAIlC;;;;;;;;GAQG;AACH,eAAO,MAAM,cAAc,eACb,QAAQ,CAAC,UAAU,QACzB,QAAQ,CAAC,IAAI,QACb,MAAM,KACX,OAIF,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,iBAAiB,eAChB,QAAQ,CAAC,UAAU,QACzB,QAAQ,CAAC,IAAI,QACb,MAAM,cACA,MAAM,KACjB,OAIF,CAAC"}
@@ -0,0 +1,39 @@
1
+ import { AST_NODE_TYPES, ASTUtils, } from '@typescript-eslint/utils';
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+ export const isLocallyBound = (sourceCode, node, name) => {
13
+ const variable = ASTUtils.findVariable(sourceCode.getScope(node), name);
14
+ return variable !== null && variable.defs.length > 0;
15
+ };
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+ export const hasForeignBinding = (sourceCode, node, name, moduleName) => {
27
+ const variable = ASTUtils.findVariable(sourceCode.getScope(node), name);
28
+ return variable?.defs.some((def) => !isImportFrom(def, moduleName)) ?? false;
29
+ };
30
+
31
+
32
+
33
+
34
+ const isImportFrom = (def, moduleName) => (def.node.type === AST_NODE_TYPES.ImportSpecifier ||
35
+ def.node.type === AST_NODE_TYPES.ImportDefaultSpecifier ||
36
+ def.node.type === AST_NODE_TYPES.ImportNamespaceSpecifier) &&
37
+ def.node.parent.type === AST_NODE_TYPES.ImportDeclaration &&
38
+ def.node.parent.source.value === moduleName;
39
+ //# sourceMappingURL=bindings.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bindings.mjs","sourceRoot":"","sources":["../src/bindings.mts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,QAAQ,GAGT,MAAM,0BAA0B,CAAC;AAElC,uEAAuE;AAEvE;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAC5B,UAA+B,EAC/B,IAAmB,EACnB,IAAY,EACH,EAAE;IACX,MAAM,QAAQ,GAAG,QAAQ,CAAC,YAAY,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IAExE,OAAO,QAAQ,KAAK,IAAI,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;AACvD,CAAC,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAC/B,UAA+B,EAC/B,IAAmB,EACnB,IAAY,EACZ,UAAkB,EACT,EAAE;IACX,MAAM,QAAQ,GAAG,QAAQ,CAAC,YAAY,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IAExE,OAAO,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,YAAY,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC,IAAI,KAAK,CAAC;AAC/E,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,YAAY,GAAG,CACnB,GAA8B,EAC9B,UAAkB,EACT,EAAE,CACX,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,cAAc,CAAC,eAAe;IAC/C,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,cAAc,CAAC,sBAAsB;IACvD,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,cAAc,CAAC,wBAAwB,CAAC;IAC5D,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,KAAK,cAAc,CAAC,iBAAiB;IACzD,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,KAAK,UAAU,CAAC"}
@@ -0,0 +1,54 @@
1
+ import { type TSESLint, type TSESTree } from '@typescript-eslint/utils';
2
+ import type { DeepReadonly } from 'ts-type-forge';
3
+ /**
4
+ * Every `import … from '<moduleName>'` declaration in the file, not only the
5
+ * first: `import type { A } from 'm'` and `import { b } from 'm'` are two
6
+ * declarations, and a name imported by either is in scope.
7
+ */
8
+ export declare const getImportDeclarations: (program: TSESTree.Program, moduleName: string) => readonly TSESTree.ImportDeclaration[];
9
+ /**
10
+ * The exported names `declarations` import by name, whatever they are bound to
11
+ * locally: `import { a, b as c }` gives `a` and `b`.
12
+ */
13
+ export declare const getNamedImports: (declarations: DeepReadonly<TSESTree.ImportDeclaration[]>) => readonly string[];
14
+ /**
15
+ * The local name `declarations` bind the export `importedName` to, or
16
+ * `undefined` when they do not import it: `'y'` for `import { x as y }`. A fix
17
+ * writes this rather than the exported name, which may not be in scope.
18
+ */
19
+ export declare const getImportedLocalName: (declarations: DeepReadonly<TSESTree.ImportDeclaration[]>, importedName: string) => string | undefined;
20
+ /** What {@link buildCalleeResolver}'s resolver says a callee calls. */
21
+ export type ResolvedCallee = Readonly<{
22
+ /** The exported name, whatever the callee calls it locally. */
23
+ canonicalName: string;
24
+ /**
25
+ * The identifier to rewrite to change what is called: the callee itself for
26
+ * a named import, the property for a namespace import.
27
+ */
28
+ propertyNode: TSESTree.Identifier;
29
+ /** Whether the call goes through a namespace import (`m.f(...)`). */
30
+ isNamespace: boolean;
31
+ }>;
32
+ /**
33
+ * Builds a function that says which export of the module `declarations`
34
+ * import a callee calls, or `undefined` when it calls none of them. It knows
35
+ * named imports, aliased ones (`import { f as g }` → `g(...)` calls `f`) and
36
+ * namespace imports (`import * as m` → `m.f(...)`), and reads both the callee
37
+ * and a namespace object through their type wrappers:
38
+ * `(f as (u: unknown) => boolean)(x)` and `(m as typeof m).f(x)` still call
39
+ * `f`.
40
+ */
41
+ export declare const buildCalleeResolver: (declarations: DeepReadonly<TSESTree.ImportDeclaration[]>) => ((callee: TSESTree.Expression) => ResolvedCallee | undefined);
42
+ /**
43
+ * A fix that inserts `import { <specifiers> } from '<moduleName>';` at the top
44
+ * of the file, or no fix when `specifiers` is empty. Each specifier is written
45
+ * as given, so `type T` imports a type.
46
+ *
47
+ * The placement is deliberately naive: an import sorter
48
+ * (prettier-plugin-organize-imports or any equivalent) merges and orders it
49
+ * afterwards. Put every name one report needs into a single call: ESLint
50
+ * merges the fixes of one report into one edit, and two fixes inserting at the
51
+ * start of the file conflict, so that one of them is dropped.
52
+ */
53
+ export declare const buildNamedImportFix: (fixer: TSESLint.RuleFixer, program: TSESTree.Program, moduleName: string, specifiers: readonly string[]) => readonly TSESLint.RuleFix[];
54
+ //# sourceMappingURL=imports.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"imports.d.mts","sourceRoot":"","sources":["../src/imports.mts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,QAAQ,EACb,KAAK,QAAQ,EACd,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAKlD;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,YACvB,QAAQ,CAAC,OAAO,cACb,MAAM,KACjB,SAAS,QAAQ,CAAC,iBAAiB,EAKnC,CAAC;AAEJ;;;GAGG;AACH,eAAO,MAAM,eAAe,iBACZ,YAAY,CAAC,QAAQ,CAAC,iBAAiB,EAAE,CAAC,KACvD,SAAS,MAAM,EAOf,CAAC;AAEJ;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,iBACjB,YAAY,CAAC,QAAQ,CAAC,iBAAiB,EAAE,CAAC,gBAC1C,MAAM,KACnB,MAAM,GAAG,SAOK,CAAC;AAElB,uEAAuE;AACvE,MAAM,MAAM,cAAc,GAAG,QAAQ,CAAC;IACpC,+DAA+D;IAC/D,aAAa,EAAE,MAAM,CAAC;IAEtB;;;OAGG;IACH,YAAY,EAAE,QAAQ,CAAC,UAAU,CAAC;IAElC,qEAAqE;IACrE,WAAW,EAAE,OAAO,CAAC;CACtB,CAAC,CAAC;AAEH;;;;;;;;GAQG;AACH,eAAO,MAAM,mBAAmB,iBAChB,YAAY,CAAC,QAAQ,CAAC,iBAAiB,EAAE,CAAC,KACvD,CAAC,CAAC,MAAM,EAAE,QAAQ,CAAC,UAAU,KAAK,cAAc,GAAG,SAAS,CAuD9D,CAAC;AAEF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,mBAAmB,UACvB,QAAQ,CAAC,SAAS,WAChB,QAAQ,CAAC,OAAO,cACb,MAAM,cACN,SAAS,MAAM,EAAE,KAC5B,SAAS,QAAQ,CAAC,OAAO,EAQX,CAAC"}
@@ -0,0 +1,90 @@
1
+ import { AST_NODE_TYPES, } from '@typescript-eslint/utils';
2
+ import { isTypeWrapper, skipTypeWrappers } from './type-wrappers.mjs';
3
+
4
+
5
+
6
+
7
+
8
+
9
+ export const getImportDeclarations = (program, moduleName) => program.body.filter((node) => node.type === AST_NODE_TYPES.ImportDeclaration &&
10
+ node.source.value === moduleName);
11
+
12
+
13
+
14
+
15
+ export const getNamedImports = (declarations) => declarations.flatMap((declaration) => declaration.specifiers.flatMap((specifier) => specifier.type === AST_NODE_TYPES.ImportSpecifier
16
+ ? [importedNameOf(specifier)]
17
+ : []));
18
+
19
+
20
+
21
+
22
+
23
+ export const getImportedLocalName = (declarations, importedName) => declarations
24
+ .flatMap((declaration) => declaration.specifiers)
25
+ .find((specifier) => specifier.type === AST_NODE_TYPES.ImportSpecifier &&
26
+ importedNameOf(specifier) === importedName)?.local.name;
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+ export const buildCalleeResolver = (declarations) => {
37
+ const specifiers = declarations.flatMap((declaration) => declaration.specifiers);
38
+ const namespaceNames = new Set(specifiers.flatMap((specifier) => specifier.type === AST_NODE_TYPES.ImportNamespaceSpecifier
39
+ ? [specifier.local.name]
40
+ : []));
41
+ const localToCanonical = new Map(specifiers.flatMap((specifier) => specifier.type === AST_NODE_TYPES.ImportSpecifier
42
+ ? [[specifier.local.name, importedNameOf(specifier)]]
43
+ : []));
44
+ const resolve = (callee) => {
45
+ if (isTypeWrapper(callee)) {
46
+ return resolve(callee.expression);
47
+ }
48
+ if (callee.type === AST_NODE_TYPES.Identifier) {
49
+ const canonicalName = localToCanonical.get(callee.name);
50
+ return canonicalName === undefined
51
+ ? undefined
52
+ : { canonicalName, propertyNode: callee, isNamespace: false };
53
+ }
54
+ if (callee.type !== AST_NODE_TYPES.MemberExpression ||
55
+ callee.computed ||
56
+ callee.property.type !== AST_NODE_TYPES.Identifier) {
57
+ return undefined;
58
+ }
59
+ const object = skipTypeWrappers(callee.object);
60
+ return object.type === AST_NODE_TYPES.Identifier &&
61
+ namespaceNames.has(object.name)
62
+ ? {
63
+ canonicalName: callee.property.name,
64
+ propertyNode: callee.property,
65
+ isNamespace: true,
66
+ }
67
+ : undefined;
68
+ };
69
+ return resolve;
70
+ };
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+ export const buildNamedImportFix = (fixer, program, moduleName, specifiers) => specifiers.length === 0
83
+ ? []
84
+ : [
85
+ fixer.insertTextBefore(program, `import { ${specifiers.join(', ')} } from '${moduleName}';\n`),
86
+ ];
87
+ const importedNameOf = (specifier) => specifier.imported.type === AST_NODE_TYPES.Identifier
88
+ ? specifier.imported.name
89
+ : specifier.imported.value;
90
+ //# sourceMappingURL=imports.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"imports.mjs","sourceRoot":"","sources":["../src/imports.mts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,GAGf,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEtE,uEAAuE;AAEvE;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,OAAyB,EACzB,UAAkB,EACqB,EAAE,CACzC,OAAO,CAAC,IAAI,CAAC,MAAM,CACjB,CAAC,IAAI,EAAsC,EAAE,CAC3C,IAAI,CAAC,IAAI,KAAK,cAAc,CAAC,iBAAiB;IAC9C,IAAI,CAAC,MAAM,CAAC,KAAK,KAAK,UAAU,CACnC,CAAC;AAEJ;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAC7B,YAAwD,EACrC,EAAE,CACrB,YAAY,CAAC,OAAO,CAAC,CAAC,WAAW,EAAE,EAAE,CACnC,WAAW,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,EAAE,CAC3C,SAAS,CAAC,IAAI,KAAK,cAAc,CAAC,eAAe;IAC/C,CAAC,CAAC,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;IAC7B,CAAC,CAAC,EAAE,CACP,CACF,CAAC;AAEJ;;;;GAIG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,YAAwD,EACxD,YAAoB,EACA,EAAE,CACtB,YAAY;KACT,OAAO,CAAC,CAAC,WAAW,EAAE,EA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AAC,IAAI;IACzB,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC"}
@@ -0,0 +1,6 @@
1
+ export * from './bindings.mjs';
2
+ export * from './imports.mjs';
3
+ export * from './negation.mjs';
4
+ export * from './parentheses.mjs';
5
+ export * from './type-wrappers.mjs';
6
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.mts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,qBAAqB,CAAC"}
package/dist/index.mjs ADDED
@@ -0,0 +1,6 @@
1
+ export * from './bindings.mjs';
2
+ export * from './imports.mjs';
3
+ export * from './negation.mjs';
4
+ export * from './parentheses.mjs';
5
+ export * from './type-wrappers.mjs';
6
+ //# sourceMappingURL=index.mjs.map