eslint-plugin-ts-fortress 0.1.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.
Files changed (49) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +77 -0
  3. package/dist/index.d.mts +5 -0
  4. package/dist/index.d.mts.map +1 -0
  5. package/dist/index.mjs +3 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/dist/plugin.d.mts +3 -0
  8. package/dist/plugin.d.mts.map +1 -0
  9. package/dist/plugin.mjs +11 -0
  10. package/dist/plugin.mjs.map +1 -0
  11. package/dist/rule-types.d.mts +25 -0
  12. package/dist/rule-types.d.mts.map +1 -0
  13. package/dist/rule-types.mjs +2 -0
  14. package/dist/rule-types.mjs.map +1 -0
  15. package/dist/rules/constants.d.mts +4 -0
  16. package/dist/rules/constants.d.mts.map +1 -0
  17. package/dist/rules/constants.mjs +6 -0
  18. package/dist/rules/constants.mjs.map +1 -0
  19. package/dist/rules/import-utils.d.mts +40 -0
  20. package/dist/rules/import-utils.d.mts.map +1 -0
  21. package/dist/rules/import-utils.mjs +68 -0
  22. package/dist/rules/import-utils.mjs.map +1 -0
  23. package/dist/rules/index.d.mts +2 -0
  24. package/dist/rules/index.d.mts.map +1 -0
  25. package/dist/rules/index.mjs +2 -0
  26. package/dist/rules/index.mjs.map +1 -0
  27. package/dist/rules/prefer-non-empty-array.d.mts +6 -0
  28. package/dist/rules/prefer-non-empty-array.d.mts.map +1 -0
  29. package/dist/rules/prefer-non-empty-array.mjs +100 -0
  30. package/dist/rules/prefer-non-empty-array.mjs.map +1 -0
  31. package/dist/rules/rules.d.mts +4 -0
  32. package/dist/rules/rules.d.mts.map +1 -0
  33. package/dist/rules/rules.mjs +8 -0
  34. package/dist/rules/rules.mjs.map +1 -0
  35. package/dist/types.d.mts +4 -0
  36. package/dist/types.d.mts.map +1 -0
  37. package/dist/types.mjs +2 -0
  38. package/dist/types.mjs.map +1 -0
  39. package/package.json +77 -0
  40. package/src/index.mts +7 -0
  41. package/src/plugin.mts +9 -0
  42. package/src/rule-types.mts +40 -0
  43. package/src/rules/constants.mts +5 -0
  44. package/src/rules/import-utils.mts +185 -0
  45. package/src/rules/index.mts +1 -0
  46. package/src/rules/prefer-non-empty-array.mts +190 -0
  47. package/src/rules/prefer-non-empty-array.test.mts +222 -0
  48. package/src/rules/rules.mts +6 -0
  49. package/src/types.mts +4 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prefer-non-empty-array.mjs","sources":["../../src/rules/prefer-non-empty-array.mts"],"sourcesContent":["import {\n AST_NODE_TYPES,\n type TSESLint,\n type TSESTree,\n} from '@typescript-eslint/utils';\nimport { MIN_LENGTH_ARRAY_FN, NON_EMPTY_ARRAY_FN } from './constants.mjs';\nimport {\n buildCalleeResolver,\n buildImportFix,\n getImportedLocalName,\n getTsFortressImports,\n hasConflictingDeclaration,\n} from './import-utils.mjs';\n\ntype Options = readonly [];\n\ntype MessageIds = 'useNonEmptyArray';\n\nexport const preferNonEmptyArray: TSESLint.RuleModule<MessageIds, Options> = {\n meta: {\n type: 'suggestion',\n docs: {\n description:\n 'Replace `minLengthArray(1, ...)` with `nonEmptyArray(...)` from ts-fortress.',\n },\n fixable: 'code',\n schema: [],\n messages: {\n useNonEmptyArray:\n 'Use `{{replacement}}(...)` instead of `{{original}}(1, ...)`: both build the same `NonEmptyArray` type, and `{{replacement}}` reports a clearer `typeName` on validation failure.',\n },\n },\n\n create: (context) => {\n const sourceCode = context.sourceCode;\n\n const program = sourceCode.ast;\n\n const tsFortressImports = getTsFortressImports(program);\n\n const resolveCallee = buildCalleeResolver(tsFortressImports);\n\n const importedLocalName = getImportedLocalName(\n tsFortressImports,\n NON_EMPTY_ARRAY_FN,\n );\n\n const mut_callsToFix: {\n node: TSESTree.CallExpression;\n propertyNode: TSESTree.Node;\n isNamespace: boolean;\n }[] = [];\n\n return {\n CallExpression: (node) => {\n const resolved = resolveCallee(node.callee);\n\n if (resolved === undefined) return;\n\n if (\n resolved.canonicalName !== MIN_LENGTH_ARRAY_FN ||\n !isRewritableMinLengthOneCall(node)\n ) {\n return;\n }\n\n mut_callsToFix.push({\n node,\n propertyNode: resolved.propertyNode,\n isNamespace: resolved.isNamespace,\n });\n },\n 'Program:exit': () => {\n if (mut_callsToFix.length === 0) return;\n\n const needsNamedBinding = mut_callsToFix.some(\n (call) => !call.isNamespace,\n );\n\n // A named-import rewrite introduces the identifier `nonEmptyArray`; if\n // that name is already bound to something else in this file, the fix\n // would silently call the wrong function. Namespace calls\n // (`t.nonEmptyArray(...)`) are unaffected, so only bail out when a\n // named binding is actually needed.\n if (\n needsNamedBinding &&\n importedLocalName === undefined &&\n hasConflictingDeclaration(program, NON_EMPTY_ARRAY_FN)\n ) {\n return;\n }\n\n const localName = importedLocalName ?? NON_EMPTY_ARRAY_FN;\n\n // Only the first *named* call carries the import fix; a namespace call\n // (`t.nonEmptyArray(...)`) needs no new binding, so it must not be the\n // one that owns it.\n const importFixIndex =\n needsNamedBinding && importedLocalName === undefined\n ? mut_callsToFix.findIndex((call) => !call.isNamespace)\n : -1;\n\n for (const [\n index,\n { node, propertyNode, isNamespace },\n ] of mut_callsToFix.entries()) {\n context.report({\n node,\n messageId: 'useNonEmptyArray',\n data: {\n original: MIN_LENGTH_ARRAY_FN,\n replacement: isNamespace ? NON_EMPTY_ARRAY_FN : localName,\n },\n fix: (fixer) => [\n ...(index === importFixIndex\n ? buildImportFix(fixer, program, NON_EMPTY_ARRAY_FN)\n : []),\n fixer.replaceText(\n propertyNode,\n isNamespace ? NON_EMPTY_ARRAY_FN : localName,\n ),\n // Drop the leading `1` argument, from its start up to the start\n // of the element-type argument, so any comments and whitespace\n // in between go with it.\n ...dropFirstArgumentFix(fixer, node),\n ],\n });\n }\n },\n };\n },\n defaultOptions: [],\n} as const;\n\n/**\n * Whether `node` is a `minLengthArray(1, elementType)` call that can be\n * rewritten to `nonEmptyArray(elementType)` without changing types.\n *\n * `nonEmptyArray` takes its `defaultValue` as a `NonEmptyTuple<A>` while\n * `minLengthArray` takes the branded `MinLengthArray<1, A>`, so calls that pass\n * a `defaultValue` are left alone rather than risking a fix that does not\n * type-check. A `typeName`-only options object is safe and still rewritten.\n */\nconst isRewritableMinLengthOneCall = (\n // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types\n node: TSESTree.CallExpression,\n): boolean => {\n const args = node.arguments;\n\n if (args.length < 2 || args.length > 3) return false;\n\n if (args.some((arg) => arg.type === AST_NODE_TYPES.SpreadElement)) {\n return false;\n }\n\n const [minLength, , options] = args;\n\n if (\n minLength?.type !== AST_NODE_TYPES.Literal ||\n minLength.value !== 1 ||\n node.typeArguments !== undefined\n ) {\n return false;\n }\n\n if (options === undefined) return true;\n\n return (\n options.type === AST_NODE_TYPES.ObjectExpression &&\n options.properties.every(\n (property) =>\n property.type === AST_NODE_TYPES.Property &&\n !property.computed &&\n property.key.type === AST_NODE_TYPES.Identifier &&\n property.key.name !== 'defaultValue',\n )\n );\n};\n\nconst dropFirstArgumentFix = (\n fixer: TSESLint.RuleFixer,\n // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types\n node: TSESTree.CallExpression,\n): readonly TSESLint.RuleFix[] => {\n const [minLength, elementType] = node.arguments;\n\n return minLength === undefined || elementType === undefined\n ? []\n : [fixer.removeRange([minLength.range[0], elementType.range[0]])];\n};\n"],"names":[],"mappings":";;;;AAkBO,MAAM,mBAAA,GAAgE;AAAA,EAC3E,IAAA,EAAM;AAAA,IACJ,IAAA,EAAM,YAAA;AAAA,IACN,IAAA,EAAM;AAAA,MACJ,WAAA,EACE;AAAA,KACJ;AAAA,IACA,OAAA,EAAS,MAAA;AAAA,IACT,QAAQ,EAAC;AAAA,IACT,QAAA,EAAU;AAAA,MACR,gBAAA,EACE;AAAA;AACJ,GACF;AAAA,EAEA,MAAA,EAAQ,CAAC,OAAA,KAAY;AACnB,IAAA,MAAM,aAAa,OAAA,CAAQ,UAAA;AAE3B,IAAA,MAAM,UAAU,UAAA,CAAW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C,EAAA,OACE,OAAA,CAAQ,IAAA,KAAS,cAAA,CAAe,gBAAA,IAChC,QAAQ,UAAA,CAAW,KAAA;AAAA,IACjB,CAAC,QAAA,KACC,QAAA,CAAS,IAAA,KAAS,cAAA,CAAe,YACjC,CAAC,QAAA,CAAS,QAAA,IACV,QAAA,CAAS,IAAI,IAAA,KAAS,cAAA,CAAe,UAAA,IACrC,QAAA,CAAS,IAAI,IAAA,KAAS;AAAA,GAC1B;AAEJ,CAAA;AAEA,MAAM,oBAAA,GAAuB,CAC3B,KAAA,EAEA,IAAA,KACgC;AAChC,EAAA,MAAM,CAAC,SAAA,EAAW,WAAW,CAAA,GAAI,IAAA,CAAK,SAAA;AAEtC,EAAA,OAAO,cAAc,MAAA,IAAa,WAAA,KAAgB,SAC9C,EAAC,GACD,CAAC,KAAA,CAAM,WAAA,CAAY,CAAC,SAAA,CAAU,KAAA,CAAM,CAAC,CAAA,EAAG,WAAA,CAAY,MAAM,CAAC,CAAC,CAAC,CAAC,CAAA;AACpE,CAAA;;;;"}
@@ -0,0 +1,4 @@
1
+ export declare const tsFortressRules: {
2
+ readonly 'prefer-non-empty-array': import("@typescript-eslint/utils/ts-eslint").RuleModule<"useNonEmptyArray", readonly [], unknown, import("@typescript-eslint/utils/ts-eslint").RuleListener>;
3
+ };
4
+ //# sourceMappingURL=rules.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.d.mts","sourceRoot":"","sources":["../../src/rules/rules.mts"],"names":[],"mappings":"AAGA,eAAO,MAAM,eAAe;;CAEc,CAAC"}
@@ -0,0 +1,8 @@
1
+ import { preferNonEmptyArray } from './prefer-non-empty-array.mjs';
2
+
3
+ const tsFortressRules = {
4
+ "prefer-non-empty-array": preferNonEmptyArray
5
+ };
6
+
7
+ export { tsFortressRules };
8
+ //# sourceMappingURL=rules.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.mjs","sources":["../../src/rules/rules.mts"],"sourcesContent":["import { type ESLintPlugin } from '../types.mjs';\nimport { preferNonEmptyArray } from './prefer-non-empty-array.mjs';\n\nexport const tsFortressRules = {\n 'prefer-non-empty-array': preferNonEmptyArray,\n} as const satisfies ESLintPlugin['rules'];\n"],"names":[],"mappings":";;AAGO,MAAM,eAAA,GAAkB;AAAA,EAC7B,wBAAA,EAA0B;AAC5B;;;;"}
@@ -0,0 +1,4 @@
1
+ import { type TSESLint } from '@typescript-eslint/utils';
2
+ import { type DeepReadonly } from 'ts-type-forge';
3
+ export type ESLintPlugin = DeepReadonly<TSESLint.FlatConfig.Plugin>;
4
+ //# sourceMappingURL=types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../src/types.mts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,eAAe,CAAC;AAElD,MAAM,MAAM,YAAY,GAAG,YAAY,CAAC,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC"}
package/dist/types.mjs ADDED
@@ -0,0 +1,2 @@
1
+
2
+ //# sourceMappingURL=types.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,77 @@
1
+ {
2
+ "name": "eslint-plugin-ts-fortress",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "description": "ESLint rules that steer schema definitions toward ts-fortress idioms.",
6
+ "keywords": [
7
+ "eslint",
8
+ "eslintplugin",
9
+ "eslint-plugin",
10
+ "ts-fortress",
11
+ "typescript",
12
+ "validation"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/noshiro-pf/ts-fortress.git",
17
+ "directory": "packages/eslint-plugin-ts-fortress"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "author": "noshiro-pf <noshiro.pf@gmail.com>",
21
+ "sideEffects": false,
22
+ "type": "module",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.mts",
26
+ "import": "./dist/index.mjs"
27
+ }
28
+ },
29
+ "module": "./dist/index.mjs",
30
+ "types": "./dist/index.d.mts",
31
+ "files": [
32
+ "src",
33
+ "dist",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "scripts": {
38
+ "build": "tsx ./scripts/cmd/build.mts",
39
+ "build:min": "tsx ./scripts/cmd/build.mts --skip-check",
40
+ "check:ext": "tsx ./scripts/cmd/check-ext.mts",
41
+ "fmt": "format-uncommitted --cwd .",
42
+ "fmt:diff": "format-diff-from origin/main --cwd .",
43
+ "fmt:full": "pnpm run z:prettier .",
44
+ "gen:rule-types": "tsx ./scripts/cmd/gen-rule-types.mts",
45
+ "lint": "eslint .",
46
+ "lint:fix": "eslint . --fix",
47
+ "test": "pnpm run z:vitest run",
48
+ "test:cov": "pnpm run z:vitest run --coverage",
49
+ "testw": "pnpm run z:vitest",
50
+ "tsc": "node ../../node_modules/typescript-native/bin/tsc --noEmit",
51
+ "tscw": "node ../../node_modules/typescript-native/bin/tsc --noEmit --watch -p ./tsconfig.json",
52
+ "type-check": "node ../../node_modules/typescript-native/bin/tsc --noEmit",
53
+ "z:prettier": "prettier --config ../../.prettierrc --ignore-path ../../.prettierignore --ignore-path ../../.gitignore --ignore-unknown --no-error-on-unmatched-pattern --write",
54
+ "z:vitest": "vitest --config ./configs/vitest.config.mts"
55
+ },
56
+ "dependencies": {
57
+ "@typescript-eslint/utils": "8.65.0",
58
+ "ts-type-forge": "7.x"
59
+ },
60
+ "devDependencies": {
61
+ "@typescript-eslint/parser": "8.65.0",
62
+ "@typescript-eslint/rule-tester": "8.65.0",
63
+ "dedent": "1.7.2"
64
+ },
65
+ "peerDependencies": {
66
+ "eslint": ">=9.0.0",
67
+ "typescript": ">=5.0.0"
68
+ },
69
+ "engines": {
70
+ "node": ">=22.22.2",
71
+ "pnpm": ">=9.0.0"
72
+ },
73
+ "publishConfig": {
74
+ "access": "public",
75
+ "provenance": true
76
+ }
77
+ }
package/src/index.mts ADDED
@@ -0,0 +1,7 @@
1
+ export { eslintPluginTsFortress } from './plugin.mjs';
2
+ export type {
3
+ EslintTsFortressRules,
4
+ EslintTsFortressRulesOption,
5
+ } from './rule-types.mjs';
6
+ export { tsFortressRules } from './rules/index.mjs';
7
+ export { type ESLintPlugin } from './types.mjs';
package/src/plugin.mts ADDED
@@ -0,0 +1,9 @@
1
+ import { tsFortressRules } from './rules/index.mjs';
2
+ import { type ESLintPlugin } from './types.mjs';
3
+
4
+ export const eslintPluginTsFortress: ESLintPlugin = {
5
+ meta: {
6
+ name: 'eslint-plugin-ts-fortress',
7
+ },
8
+ rules: tsFortressRules,
9
+ } as const;
@@ -0,0 +1,40 @@
1
+ /* cSpell:disable */
2
+
3
+ // This file is auto-generated by `pnpm run gen:rule-types`
4
+ // (`scripts/cmd/gen-rule-types.mts`). Do not edit it manually.
5
+
6
+ import { type Linter } from 'eslint';
7
+ import { type TypeEq } from 'ts-type-forge';
8
+ import { type tsFortressRules } from './rules/index.mjs';
9
+
10
+ /**
11
+ * @description Replace `minLengthArray(1, ...)` with `nonEmptyArray(...)` from ts-fortress.
12
+ *
13
+ * ```md
14
+ * | key | value |
15
+ * | :--------- | :--------- |
16
+ * | type | suggestion |
17
+ * | deprecated | false |
18
+ * | fixable | code |
19
+ * ```
20
+ */
21
+ namespace PreferNonEmptyArray {
22
+ export type RuleEntry = Linter.StringSeverity;
23
+ }
24
+
25
+ export type EslintTsFortressRules = Readonly<{
26
+ 'ts-fortress/prefer-non-empty-array': PreferNonEmptyArray.RuleEntry;
27
+ }>;
28
+
29
+ export type EslintTsFortressRulesOption = Readonly<Record<never, never>>;
30
+
31
+ // If this assertion fails to type-check, this generated file has drifted from
32
+ // the actual plugin rules — re-run `pnpm run gen:rule-types`.
33
+ type AssertTrue<B extends true> = B;
34
+
35
+ export type RuleNamesAreInSync = AssertTrue<
36
+ TypeEq<
37
+ keyof EslintTsFortressRules,
38
+ `ts-fortress/${keyof typeof tsFortressRules}`
39
+ >
40
+ >;
@@ -0,0 +1,5 @@
1
+ export const TS_FORTRESS_MODULE = 'ts-fortress';
2
+
3
+ export const MIN_LENGTH_ARRAY_FN = 'minLengthArray';
4
+
5
+ export const NON_EMPTY_ARRAY_FN = 'nonEmptyArray';
@@ -0,0 +1,185 @@
1
+ import {
2
+ AST_NODE_TYPES,
3
+ type TSESLint,
4
+ type TSESTree,
5
+ } from '@typescript-eslint/utils';
6
+ import { TS_FORTRESS_MODULE } from './constants.mjs';
7
+
8
+ /* eslint-disable @typescript-eslint/prefer-readonly-parameter-types */
9
+
10
+ export type ResolvedCallee = Readonly<{
11
+ /** The canonical (imported) ts-fortress name, regardless of local alias. */
12
+ canonicalName: string;
13
+ /** The identifier node to rewrite when replacing the callee name. */
14
+ propertyNode: TSESTree.Node;
15
+ /** Whether the call was made through a namespace import (`t.foo(...)`). */
16
+ isNamespace: boolean;
17
+ }>;
18
+
19
+ /** Every `import ... from 'ts-fortress'` declaration in the file. */
20
+ export const getTsFortressImports = (
21
+ program: TSESTree.Program,
22
+ ): readonly TSESTree.ImportDeclaration[] =>
23
+ program.body.filter(
24
+ (node): node is TSESTree.ImportDeclaration =>
25
+ node.type === AST_NODE_TYPES.ImportDeclaration &&
26
+ node.source.value === TS_FORTRESS_MODULE,
27
+ );
28
+
29
+ /**
30
+ * Returns the in-scope local name a given ts-fortress export is imported as
31
+ * (handling aliases such as `import { nonEmptyArray as nea }` → `'nea'`), or
32
+ * `undefined` when it is not imported. Used so autofixes reference the binding
33
+ * that actually exists rather than the canonical name.
34
+ */
35
+ export const getImportedLocalName = (
36
+ importDeclarations: readonly TSESTree.ImportDeclaration[],
37
+ importedName: string,
38
+ ): string | undefined =>
39
+ importDeclarations
40
+ .flatMap((declaration) => declaration.specifiers)
41
+ .find(
42
+ (specifier) =>
43
+ specifier.type === AST_NODE_TYPES.ImportSpecifier &&
44
+ (specifier.imported.type === AST_NODE_TYPES.Identifier
45
+ ? specifier.imported.name
46
+ : specifier.imported.value) === importedName,
47
+ )?.local.name;
48
+
49
+ /**
50
+ * Builds a resolver that maps a call expression's callee to the canonical
51
+ * ts-fortress function it refers to. Handles named imports (including aliases)
52
+ * and namespace imports (`import * as t` → `t.foo(...)`) — the latter being the
53
+ * idiomatic way to consume ts-fortress. Returns `undefined` for any callee that
54
+ * does not reference the given ts-fortress imports.
55
+ */
56
+ export const buildCalleeResolver = (
57
+ importDeclarations: readonly TSESTree.ImportDeclaration[],
58
+ ): ((callee: TSESTree.Expression) => ResolvedCallee | undefined) => {
59
+ const specifiers = importDeclarations.flatMap(
60
+ (declaration) => declaration.specifiers,
61
+ );
62
+
63
+ const namespaceNames = new Set(
64
+ specifiers
65
+ .filter(
66
+ (specifier) =>
67
+ specifier.type === AST_NODE_TYPES.ImportNamespaceSpecifier,
68
+ )
69
+ .map((specifier) => specifier.local.name),
70
+ );
71
+
72
+ const localToCanonical = new Map<string, string>(
73
+ specifiers.flatMap((specifier) => {
74
+ if (specifier.type !== AST_NODE_TYPES.ImportSpecifier) return [];
75
+
76
+ const importedName =
77
+ specifier.imported.type === AST_NODE_TYPES.Identifier
78
+ ? specifier.imported.name
79
+ : specifier.imported.value;
80
+
81
+ return typeof importedName === 'string'
82
+ ? [[specifier.local.name, importedName] as const]
83
+ : [];
84
+ }),
85
+ );
86
+
87
+ return (callee) => {
88
+ if (callee.type === AST_NODE_TYPES.Identifier) {
89
+ const canonicalName = localToCanonical.get(callee.name);
90
+
91
+ return canonicalName === undefined
92
+ ? undefined
93
+ : { canonicalName, propertyNode: callee, isNamespace: false };
94
+ }
95
+
96
+ return callee.type === AST_NODE_TYPES.MemberExpression &&
97
+ !callee.computed &&
98
+ callee.object.type === AST_NODE_TYPES.Identifier &&
99
+ namespaceNames.has(callee.object.name) &&
100
+ callee.property.type === AST_NODE_TYPES.Identifier
101
+ ? {
102
+ canonicalName: callee.property.name,
103
+ propertyNode: callee.property,
104
+ isNamespace: true,
105
+ }
106
+ : undefined;
107
+ };
108
+ };
109
+
110
+ /**
111
+ * Whether the file already binds `name` to something that is not the
112
+ * ts-fortress export of the same name — a local declaration or an import from
113
+ * another module. Autofixes that introduce `name` must bail out in that case,
114
+ * because the rewritten call would resolve to the wrong binding.
115
+ */
116
+ export const hasConflictingDeclaration = (
117
+ program: TSESTree.Program,
118
+ name: string,
119
+ ): boolean =>
120
+ program.body.some((node) => {
121
+ if (node.type === AST_NODE_TYPES.ImportDeclaration) {
122
+ return (
123
+ node.source.value !== TS_FORTRESS_MODULE &&
124
+ node.specifiers.some((specifier) => specifier.local.name === name)
125
+ );
126
+ }
127
+
128
+ return declaresName(
129
+ node.type === AST_NODE_TYPES.ExportNamedDeclaration ||
130
+ node.type === AST_NODE_TYPES.ExportDefaultDeclaration
131
+ ? node.declaration
132
+ : node,
133
+ name,
134
+ );
135
+ });
136
+
137
+ /**
138
+ * Inserts `import { <name> } from 'ts-fortress';` at the top of the file.
139
+ * Placement is deliberately naive: prettier-plugin-organize-imports (or any
140
+ * equivalent) merges and sorts it afterwards.
141
+ */
142
+ export const buildImportFix = (
143
+ fixer: TSESLint.RuleFixer,
144
+ program: TSESTree.Program,
145
+ name: string,
146
+ ): readonly TSESLint.RuleFix[] =>
147
+ [
148
+ fixer.insertTextBefore(
149
+ program,
150
+ `import { ${name} } from '${TS_FORTRESS_MODULE}';\n`,
151
+ ),
152
+ ] as const;
153
+
154
+ const declaresName = (
155
+ node: TSESTree.Node | null | undefined,
156
+ name: string,
157
+ ): boolean => {
158
+ if (node === null || node === undefined) return false;
159
+
160
+ if (
161
+ node.type === AST_NODE_TYPES.TSTypeAliasDeclaration ||
162
+ node.type === AST_NODE_TYPES.TSInterfaceDeclaration ||
163
+ node.type === AST_NODE_TYPES.TSEnumDeclaration
164
+ ) {
165
+ return node.id.name === name;
166
+ }
167
+
168
+ if (
169
+ node.type === AST_NODE_TYPES.ClassDeclaration ||
170
+ node.type === AST_NODE_TYPES.FunctionDeclaration
171
+ ) {
172
+ return node.id?.name === name;
173
+ }
174
+
175
+ return (
176
+ node.type === AST_NODE_TYPES.VariableDeclaration &&
177
+ node.declarations.some(
178
+ (declarator) =>
179
+ declarator.id.type === AST_NODE_TYPES.Identifier &&
180
+ declarator.id.name === name,
181
+ )
182
+ );
183
+ };
184
+
185
+ /* eslint-enable @typescript-eslint/prefer-readonly-parameter-types */
@@ -0,0 +1 @@
1
+ export * from './rules.mjs';
@@ -0,0 +1,190 @@
1
+ import {
2
+ AST_NODE_TYPES,
3
+ type TSESLint,
4
+ type TSESTree,
5
+ } from '@typescript-eslint/utils';
6
+ import { MIN_LENGTH_ARRAY_FN, NON_EMPTY_ARRAY_FN } from './constants.mjs';
7
+ import {
8
+ buildCalleeResolver,
9
+ buildImportFix,
10
+ getImportedLocalName,
11
+ getTsFortressImports,
12
+ hasConflictingDeclaration,
13
+ } from './import-utils.mjs';
14
+
15
+ type Options = readonly [];
16
+
17
+ type MessageIds = 'useNonEmptyArray';
18
+
19
+ export const preferNonEmptyArray: TSESLint.RuleModule<MessageIds, Options> = {
20
+ meta: {
21
+ type: 'suggestion',
22
+ docs: {
23
+ description:
24
+ 'Replace `minLengthArray(1, ...)` with `nonEmptyArray(...)` from ts-fortress.',
25
+ },
26
+ fixable: 'code',
27
+ schema: [],
28
+ messages: {
29
+ useNonEmptyArray:
30
+ 'Use `{{replacement}}(...)` instead of `{{original}}(1, ...)`: both build the same `NonEmptyArray` type, and `{{replacement}}` reports a clearer `typeName` on validation failure.',
31
+ },
32
+ },
33
+
34
+ create: (context) => {
35
+ const sourceCode = context.sourceCode;
36
+
37
+ const program = sourceCode.ast;
38
+
39
+ const tsFortressImports = getTsFortressImports(program);
40
+
41
+ const resolveCallee = buildCalleeResolver(tsFortressImports);
42
+
43
+ const importedLocalName = getImportedLocalName(
44
+ tsFortressImports,
45
+ NON_EMPTY_ARRAY_FN,
46
+ );
47
+
48
+ const mut_callsToFix: {
49
+ node: TSESTree.CallExpression;
50
+ propertyNode: TSESTree.Node;
51
+ isNamespace: boolean;
52
+ }[] = [];
53
+
54
+ return {
55
+ CallExpression: (node) => {
56
+ const resolved = resolveCallee(node.callee);
57
+
58
+ if (resolved === undefined) return;
59
+
60
+ if (
61
+ resolved.canonicalName !== MIN_LENGTH_ARRAY_FN ||
62
+ !isRewritableMinLengthOneCall(node)
63
+ ) {
64
+ return;
65
+ }
66
+
67
+ mut_callsToFix.push({
68
+ node,
69
+ propertyNode: resolved.propertyNode,
70
+ isNamespace: resolved.isNamespace,
71
+ });
72
+ },
73
+ 'Program:exit': () => {
74
+ if (mut_callsToFix.length === 0) return;
75
+
76
+ const needsNamedBinding = mut_callsToFix.some(
77
+ (call) => !call.isNamespace,
78
+ );
79
+
80
+ // A named-import rewrite introduces the identifier `nonEmptyArray`; if
81
+ // that name is already bound to something else in this file, the fix
82
+ // would silently call the wrong function. Namespace calls
83
+ // (`t.nonEmptyArray(...)`) are unaffected, so only bail out when a
84
+ // named binding is actually needed.
85
+ if (
86
+ needsNamedBinding &&
87
+ importedLocalName === undefined &&
88
+ hasConflictingDeclaration(program, NON_EMPTY_ARRAY_FN)
89
+ ) {
90
+ return;
91
+ }
92
+
93
+ const localName = importedLocalName ?? NON_EMPTY_ARRAY_FN;
94
+
95
+ // Only the first *named* call carries the import fix; a namespace call
96
+ // (`t.nonEmptyArray(...)`) needs no new binding, so it must not be the
97
+ // one that owns it.
98
+ const importFixIndex =
99
+ needsNamedBinding && importedLocalName === undefined
100
+ ? mut_callsToFix.findIndex((call) => !call.isNamespace)
101
+ : -1;
102
+
103
+ for (const [
104
+ index,
105
+ { node, propertyNode, isNamespace },
106
+ ] of mut_callsToFix.entries()) {
107
+ context.report({
108
+ node,
109
+ messageId: 'useNonEmptyArray',
110
+ data: {
111
+ original: MIN_LENGTH_ARRAY_FN,
112
+ replacement: isNamespace ? NON_EMPTY_ARRAY_FN : localName,
113
+ },
114
+ fix: (fixer) => [
115
+ ...(index === importFixIndex
116
+ ? buildImportFix(fixer, program, NON_EMPTY_ARRAY_FN)
117
+ : []),
118
+ fixer.replaceText(
119
+ propertyNode,
120
+ isNamespace ? NON_EMPTY_ARRAY_FN : localName,
121
+ ),
122
+ // Drop the leading `1` argument, from its start up to the start
123
+ // of the element-type argument, so any comments and whitespace
124
+ // in between go with it.
125
+ ...dropFirstArgumentFix(fixer, node),
126
+ ],
127
+ });
128
+ }
129
+ },
130
+ };
131
+ },
132
+ defaultOptions: [],
133
+ } as const;
134
+
135
+ /**
136
+ * Whether `node` is a `minLengthArray(1, elementType)` call that can be
137
+ * rewritten to `nonEmptyArray(elementType)` without changing types.
138
+ *
139
+ * `nonEmptyArray` takes its `defaultValue` as a `NonEmptyTuple<A>` while
140
+ * `minLengthArray` takes the branded `MinLengthArray<1, A>`, so calls that pass
141
+ * a `defaultValue` are left alone rather than risking a fix that does not
142
+ * type-check. A `typeName`-only options object is safe and still rewritten.
143
+ */
144
+ const isRewritableMinLengthOneCall = (
145
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
146
+ node: TSESTree.CallExpression,
147
+ ): boolean => {
148
+ const args = node.arguments;
149
+
150
+ if (args.length < 2 || args.length > 3) return false;
151
+
152
+ if (args.some((arg) => arg.type === AST_NODE_TYPES.SpreadElement)) {
153
+ return false;
154
+ }
155
+
156
+ const [minLength, , options] = args;
157
+
158
+ if (
159
+ minLength?.type !== AST_NODE_TYPES.Literal ||
160
+ minLength.value !== 1 ||
161
+ node.typeArguments !== undefined
162
+ ) {
163
+ return false;
164
+ }
165
+
166
+ if (options === undefined) return true;
167
+
168
+ return (
169
+ options.type === AST_NODE_TYPES.ObjectExpression &&
170
+ options.properties.every(
171
+ (property) =>
172
+ property.type === AST_NODE_TYPES.Property &&
173
+ !property.computed &&
174
+ property.key.type === AST_NODE_TYPES.Identifier &&
175
+ property.key.name !== 'defaultValue',
176
+ )
177
+ );
178
+ };
179
+
180
+ const dropFirstArgumentFix = (
181
+ fixer: TSESLint.RuleFixer,
182
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types
183
+ node: TSESTree.CallExpression,
184
+ ): readonly TSESLint.RuleFix[] => {
185
+ const [minLength, elementType] = node.arguments;
186
+
187
+ return minLength === undefined || elementType === undefined
188
+ ? []
189
+ : [fixer.removeRange([minLength.range[0], elementType.range[0]])];
190
+ };