@codegraft/rules 0.1.0-beta.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-present Joël Charles
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,50 @@
1
+ # @codegraft/rules
2
+
3
+ Ready-made codemods — ESLint-rule-style transforms authored with [`@codegraft/codemod`](../codemod) and the `@codegraft/core` scope resolver.
4
+
5
+ Each rule lives in its own module, is re-exported by name from the barrel, and the package is `"sideEffects": false` — so a consumer that imports one rule tree-shakes the rest. Every rule runs live via `forTarget` — directly, through `@codegraft/unplugin`, or `codegraft run`.
6
+
7
+ ## Rules
8
+
9
+ ### `removeUnusedImports`
10
+
11
+ Removes imports whose local binding is never referenced, and rewrites value imports used only in type positions into type imports — the analogue of `eslint-plugin-unused-imports` plus the import half of `@typescript-eslint/consistent-type-imports`. Syntactic, single-file, and **confident-or-abstain**: it keeps anything it can't prove unused and never emits invalid code.
12
+
13
+ Per binding, three outcomes:
14
+
15
+ - **value-used** → kept as-is (a value import already serves type positions);
16
+ - **type-used only** → rewritten as a type import — inline `import { type X }` next to a surviving value specifier, or a whole `import type …` when the entire statement becomes type-only (covers default and `* as ns` too);
17
+ - **unused** → removed, including unused `import type …` and inline `{ type X }`; the whole statement goes when every binding is unused, otherwise the clause is rebuilt from the survivors.
18
+
19
+ Safety, always erring towards code that still compiles:
20
+
21
+ - never touches a side-effect import (`import 'x'`);
22
+ - abstains on the whole file when the scope resolver can't model it (`with` / `eval` / a TS `namespace` / ambient `module`);
23
+ - value-use detection is scope-aware (a use shadowed in an inner scope doesn't keep an outer import alive), and `typeof X` counts as a value use;
24
+ - a type-only default/namespace that shares a statement with a surviving value binding is kept as a value import rather than split across two statements (safe, just not erasable).
25
+
26
+ ```ts
27
+ import { removeUnusedImports } from '@codegraft/rules'
28
+
29
+ const transform = await removeUnusedImports.forTarget('tsx')
30
+ transform.transform("import { used, unused } from 'm'\nused()", {})
31
+ // → "import { used } from 'm'\nused()"
32
+ transform.transform("import { Foo } from 'm'\nlet v: Foo", {})
33
+ // → "import type { Foo } from 'm'\nlet v: Foo"
34
+ ```
35
+
36
+ It works on every JS-family grammar (JS / JSX / TS / TSX) and, through a `ZoneSplitter`, the `<script>` of a Vue SFC.
37
+
38
+ The rule module is also a ready codemod (default export + `targets: ['javascript', 'typescript', 'tsx']`), so the CLI runs it directly — `.vue` `<script>` included, via the cli's built-in splitter:
39
+
40
+ ```bash
41
+ codegraft run "src/**/*.{ts,tsx,vue}" --codemod @codegraft/rules/remove-unused-imports --in-place
42
+ ```
43
+
44
+ See the root [README](../../README.md#ready-made-rules-codegraftrules) for how to wire a rule into a bundler or `codegraft run`.
45
+
46
+ ## Adding a rule
47
+
48
+ 1. Add `src/<rule-name>.ts` exporting a `defineCodemod(...)` result.
49
+ 2. Re-export it from `src/index.ts`.
50
+ 3. Add `src/<rule-name>.test.ts`, covering each grammar you support plus the `vueSplitter` path and the abstain cases.
@@ -0,0 +1,2 @@
1
+ export { removeUnusedImports } from './remove-unused-imports.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ // One rule per module, re-exported by name — combined with `"sideEffects": false`, a consumer
2
+ // that imports a single rule tree-shakes the rest. Add new rules here the same way.
3
+ export { removeUnusedImports } from './remove-unused-imports.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,oFAAoF;AACpF,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAA"}
@@ -0,0 +1,12 @@
1
+ import type { GrammarId } from '@codegraft/core';
2
+ /**
3
+ * Remove imports with no reference, and rewrite a value import used only in type positions into a
4
+ * type import — the analogue of `eslint-plugin-unused-imports` plus the import half of
5
+ * `@typescript-eslint/consistent-type-imports`. Syntactic and single-file; confident-or-abstain, so
6
+ * a binding the scope resolver can't resolve is left untouched rather than deleted. Runs on every
7
+ * JS-family grammar and, through a `ZoneSplitter`, the `<script>` of a Vue SFC.
8
+ */
9
+ export declare const removeUnusedImports: import("@codegraft/codemod").Codemod<Record<string, unknown>, GrammarId>;
10
+ export default removeUnusedImports;
11
+ export declare const targets: GrammarId[];
12
+ //# sourceMappingURL=remove-unused-imports.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remove-unused-imports.d.ts","sourceRoot":"","sources":["../src/remove-unused-imports.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAc,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAG5D;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,0EAgF9B,CAAA;AAEF,eAAe,mBAAmB,CAAA;AAIlC,eAAO,MAAM,OAAO,EAAE,SAAS,EAAwC,CAAA"}
@@ -0,0 +1,87 @@
1
+ import { defineCodemod } from '@codegraft/codemod';
2
+ /**
3
+ * Remove imports with no reference, and rewrite a value import used only in type positions into a
4
+ * type import — the analogue of `eslint-plugin-unused-imports` plus the import half of
5
+ * `@typescript-eslint/consistent-type-imports`. Syntactic and single-file; confident-or-abstain, so
6
+ * a binding the scope resolver can't resolve is left untouched rather than deleted. Runs on every
7
+ * JS-family grammar and, through a `ZoneSplitter`, the `<script>` of a Vue SFC.
8
+ */
9
+ export const removeUnusedImports = defineCodemod((root) => {
10
+ // The resolver reports only value (`identifier`) references, so type-position uses are gathered
11
+ // separately: every `type_identifier`, plus the `identifier` head of a qualified type (`NS.x`).
12
+ const typeRefs = new Set();
13
+ root.find('type_identifier').forEach((ref) => typeRefs.add(ref.text));
14
+ root.find('nested_type_identifier').forEach((qualified) => {
15
+ const head = qualified.field('module');
16
+ if (head.type === 'identifier')
17
+ typeRefs.add(head.text);
18
+ });
19
+ root.find('import_statement').forEach((stmt) => {
20
+ const clause = stmt.children().filter((child) => child.type === 'import_clause').first();
21
+ if (clause.size() === 0)
22
+ return; // side-effect import (`import 'x'`): no binding to be unused
23
+ const isTypeStatement = stmt.node.allChildren.some((child) => child.type === 'type'); // `import type …`
24
+ const bindings = [];
25
+ clause.children().forEach((part) => {
26
+ if (part.type === 'identifier') {
27
+ bindings.push({ named: false, text: part.text, local: part, isType: isTypeStatement });
28
+ }
29
+ else if (part.type === 'namespace_import') {
30
+ bindings.push({ named: false, text: part.text, local: part.find('identifier').first(), isType: isTypeStatement });
31
+ }
32
+ else if (part.type === 'named_imports') {
33
+ part.find('import_specifier').forEach((spec) => {
34
+ const alias = spec.field('alias');
35
+ const name = spec.field('name');
36
+ const inlineType = spec.node.allChildren.some((child) => child.type === 'type');
37
+ const text = alias.size() ? `${name.text} as ${alias.text}` : name.text;
38
+ bindings.push({ named: true, text, local: alias.size() ? alias : name, isType: isTypeStatement || inlineType });
39
+ });
40
+ }
41
+ });
42
+ // Keep each referenced binding, recording whether its only references are type-position ones.
43
+ const kept = [];
44
+ for (const binding of bindings) {
45
+ const references = binding.local.references();
46
+ if (!references)
47
+ return; // resolver abstains on this file — leave the statement untouched
48
+ const declaration = binding.local.node;
49
+ const valueUsed = !binding.isType &&
50
+ references.nodes().some((ref) => {
51
+ // A qualified-type head (`NS.Thing`) lexes as a value identifier but is a type use.
52
+ const parent = ref.parent;
53
+ return ref !== declaration && !(parent?.type === 'nested_type_identifier' && parent.child('module') === ref);
54
+ });
55
+ if (!valueUsed && !typeRefs.has(binding.local.text))
56
+ continue; // unreferenced
57
+ kept.push({ ...binding, typeOnly: !valueUsed });
58
+ }
59
+ if (kept.length === 0) {
60
+ stmt.remove();
61
+ return;
62
+ }
63
+ // A type-only default or `* as ns` can't be marked inline, so a binding renders as a type only
64
+ // when the whole statement does (every binding type-only) or it's a named specifier. `asType`
65
+ // is the single source of truth for the no-op check and the rendering below.
66
+ const asTypeStatement = kept.every((binding) => binding.typeOnly);
67
+ const asType = (binding) => asTypeStatement || (binding.named && binding.typeOnly);
68
+ if (kept.length === bindings.length && kept.every((binding) => asType(binding) === binding.isType))
69
+ return;
70
+ const leading = [];
71
+ const specifiers = [];
72
+ for (const binding of kept) {
73
+ if (!binding.named)
74
+ leading.push(binding.text);
75
+ else
76
+ specifiers.push(asType(binding) && !asTypeStatement ? `type ${binding.text}` : binding.text);
77
+ }
78
+ if (specifiers.length)
79
+ leading.push(`{ ${specifiers.join(', ')} }`);
80
+ stmt.replaceWith(`${asTypeStatement ? 'import type' : 'import'} ${leading.join(', ')} from ${stmt.field('source').text}`);
81
+ });
82
+ });
83
+ export default removeUnusedImports;
84
+ // Lets `codegraft run --codemod @codegraft/rules/remove-unused-imports` apply over `.js/.jsx/.ts/.tsx`
85
+ // directly; the cli adds the Vue splitter, so `.vue` `<script>` works too without declaring it here.
86
+ export const targets = ['javascript', 'typescript', 'tsx'];
87
+ //# sourceMappingURL=remove-unused-imports.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remove-unused-imports.js","sourceRoot":"","sources":["../src/remove-unused-imports.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAElD;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,aAAa,CAAC,CAAC,IAAI,EAAE,EAAE;IACxD,gGAAgG;IAChG,gGAAgG;IAChG,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAA;IAClC,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAA;IACrE,IAAI,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,EAAE;QACxD,MAAM,IAAI,GAAG,SAAS,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;QACtC,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY;YAAE,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IACzD,CAAC,CAAC,CAAA;IAaF,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC7C,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,EAAE,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,eAAe,CAAC,CAAC,KAAK,EAAE,CAAA;QACxF,IAAI,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC;YAAE,OAAM,CAAC,6DAA6D;QAE7F,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,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IAAI,CAAC,SAAS,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC,CAAA;IAC3H,CAAC,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA;AAEF,eAAe,mBAAmB,CAAA;AAElC,uGAAuG;AACvG,qGAAqG;AACrG,MAAM,CAAC,MAAM,OAAO,GAAgB,CAAC,YAAY,EAAE,YAAY,EAAE,KAAK,CAAC,CAAA"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@codegraft/rules",
3
+ "version": "0.1.0-beta.0",
4
+ "description": "Ready-made Codegraft codemods — ESLint-rule-style transforms (e.g. removeUnusedImports), one rule per module, tree-shakeable.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/magne4000/codegraft.git",
11
+ "directory": "packages/rules"
12
+ },
13
+ "homepage": "https://github.com/magne4000/codegraft#readme",
14
+ "bugs": "https://github.com/magne4000/codegraft/issues",
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "exports": {
19
+ ".": {
20
+ "import": "./dist/index.js",
21
+ "types": "./dist/index.d.ts"
22
+ },
23
+ "./*": {
24
+ "import": "./dist/*.js",
25
+ "types": "./dist/*.d.ts"
26
+ }
27
+ },
28
+ "engines": {
29
+ "node": ">=22.13"
30
+ },
31
+ "dependencies": {
32
+ "@codegraft/codemod": "0.1.0-beta.0",
33
+ "@codegraft/core": "0.1.0-beta.0"
34
+ },
35
+ "devDependencies": {
36
+ "@codegraft/vue": "0.1.0-beta.0"
37
+ },
38
+ "scripts": {
39
+ "build": "tsc -b"
40
+ }
41
+ }