@trackunit/eslint-plugin-trackunit 0.8.9 → 0.9.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 (33) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +7 -9
  3. package/package.json +3 -2
  4. package/src/lib/config/index.d.ts +2 -8
  5. package/src/lib/config/plugins.d.ts +2 -8
  6. package/src/lib/config/plugins.js +0 -4
  7. package/src/lib/config/presets/react.d.ts +2 -8
  8. package/src/lib/rules/one-component-per-file/one-component-per-file.js +1 -0
  9. package/src/lib/rules/require-component-directory/require-component-directory.js +26 -197
  10. package/src/lib/rules/require-component-directory/utils/component-directory-structure-utils/component-directory-structure-utils.d.ts +25 -25
  11. package/src/lib/rules/require-component-directory/utils/component-directory-structure-utils/component-directory-structure-utils.js +178 -78
  12. package/src/lib/rules/require-hook-util-directory/require-hook-util-directory.d.ts +5 -3
  13. package/src/lib/rules/require-hook-util-directory/require-hook-util-directory.js +17 -13
  14. package/src/lib/rules/require-hook-util-directory/utils/hook-util-directory-structure-utils/hook-util-directory-structure-utils.d.ts +13 -4
  15. package/src/lib/rules/require-hook-util-directory/utils/hook-util-directory-structure-utils/hook-util-directory-structure-utils.js +31 -15
  16. package/src/lib/rules/require-nested-components-directory/require-nested-components-directory.d.ts +2 -1
  17. package/src/lib/rules/require-nested-components-directory/require-nested-components-directory.js +7 -6
  18. package/src/lib/rules/require-nested-components-directory/utils/nested-component-directory-utils/nested-component-directory-utils.d.ts +13 -9
  19. package/src/lib/rules/require-nested-components-directory/utils/nested-component-directory-utils/nested-component-directory-utils.js +46 -162
  20. package/src/lib/utils/component-utils.d.ts +13 -4
  21. package/src/lib/utils/component-utils.js +170 -64
  22. package/src/lib/utils/react-module-summary/react-module-summary.d.ts +26 -0
  23. package/src/lib/utils/react-module-summary/react-module-summary.js +84 -0
  24. package/src/lib/utils/source-tree-utils/source-tree-utils.d.ts +0 -37
  25. package/src/lib/utils/source-tree-utils/source-tree-utils.js +6 -109
  26. package/src/lib/rules/require-nested-components-privacy/require-nested-components-privacy.d.ts +0 -9
  27. package/src/lib/rules/require-nested-components-privacy/require-nested-components-privacy.js +0 -63
  28. package/src/lib/rules/require-nested-components-privacy/utils/nested-component-privacy-utils/nested-component-privacy-utils.d.ts +0 -14
  29. package/src/lib/rules/require-nested-components-privacy/utils/nested-component-privacy-utils/nested-component-privacy-utils.js +0 -62
  30. package/src/lib/rules/require-page-directory/require-page-directory.d.ts +0 -8
  31. package/src/lib/rules/require-page-directory/require-page-directory.js +0 -44
  32. package/src/lib/rules/require-page-directory/utils/page-directory-structure-utils/page-directory-structure-utils.d.ts +0 -18
  33. package/src/lib/rules/require-page-directory/utils/page-directory-structure-utils/page-directory-structure-utils.js +0 -159
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ /**
3
+ * What a module exports, as the folder-structure rules and their codemods see it.
4
+ *
5
+ * Component detection is `createComponentFileTracker`, the same detection `one-component-per-file`
6
+ * uses, so a file counts as a component file exactly when that rule would count an exported
7
+ * component in it. A class counts only when it extends `Component` or `PureComponent` (bare or
8
+ * `React.*`).
9
+ *
10
+ * ## Main Functions
11
+ * - `summarizeReactModule()` - Summarize an already parsed program (inside a rule)
12
+ * - `summarizeReactModuleSource()` - Parse and summarize source text
13
+ * - `summarizeReactModuleFile()` - Read, parse, and summarize a file on disk
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.summarizeReactModuleFile = exports.summarizeReactModuleSource = exports.summarizeReactModule = void 0;
17
+ const tslib_1 = require("tslib");
18
+ const typescript_estree_1 = require("@typescript-eslint/typescript-estree");
19
+ const utils_1 = require("@typescript-eslint/utils");
20
+ const fs = tslib_1.__importStar(require("fs"));
21
+ const component_utils_1 = require("../component-utils");
22
+ const EMPTY_SUMMARY = {
23
+ exportedComponentNames: [],
24
+ exportsComponent: false,
25
+ createsContext: false,
26
+ };
27
+ const isCreateContextCall = (node) => {
28
+ if (node?.type !== utils_1.AST_NODE_TYPES.CallExpression) {
29
+ return false;
30
+ }
31
+ const { callee } = node;
32
+ if (callee.type === utils_1.AST_NODE_TYPES.Identifier) {
33
+ return callee.name === "createContext";
34
+ }
35
+ return (callee.type === utils_1.AST_NODE_TYPES.MemberExpression &&
36
+ callee.object.type === utils_1.AST_NODE_TYPES.Identifier &&
37
+ callee.object.name === "React" &&
38
+ callee.property.type === utils_1.AST_NODE_TYPES.Identifier &&
39
+ callee.property.name === "createContext");
40
+ };
41
+ const statementCreatesContext = (statement) => {
42
+ if (statement.type === utils_1.AST_NODE_TYPES.ExportDefaultDeclaration) {
43
+ return isCreateContextCall(statement.declaration);
44
+ }
45
+ const declaration = statement.type === utils_1.AST_NODE_TYPES.ExportNamedDeclaration ? statement.declaration : statement;
46
+ if (declaration?.type !== utils_1.AST_NODE_TYPES.VariableDeclaration) {
47
+ return false;
48
+ }
49
+ return declaration.declarations.some(declarator => isCreateContextCall(declarator.init));
50
+ };
51
+ const summarizeReactModule = (program) => {
52
+ const tracker = (0, component_utils_1.createComponentFileTracker)();
53
+ tracker.onProgramBody(program);
54
+ const exportedComponents = tracker.getExportedComponents();
55
+ return {
56
+ exportedComponentNames: exportedComponents.flatMap(component => (component.name === null ? [] : [component.name])),
57
+ exportsComponent: exportedComponents.length > 0,
58
+ createsContext: program.body.some(statementCreatesContext),
59
+ };
60
+ };
61
+ exports.summarizeReactModule = summarizeReactModule;
62
+ /** Unparsable source summarizes as an empty module. */
63
+ const summarizeReactModuleSource = (sourceText, filePath) => {
64
+ try {
65
+ return (0, exports.summarizeReactModule)((0, typescript_estree_1.parse)(sourceText, { jsx: true, filePath }));
66
+ }
67
+ catch {
68
+ return EMPTY_SUMMARY;
69
+ }
70
+ };
71
+ exports.summarizeReactModuleSource = summarizeReactModuleSource;
72
+ /** An unreadable or unparsable file summarizes as an empty module. */
73
+ const summarizeReactModuleFile = (filePath) => {
74
+ let sourceText;
75
+ try {
76
+ sourceText = fs.readFileSync(filePath, "utf8");
77
+ }
78
+ catch {
79
+ return EMPTY_SUMMARY;
80
+ }
81
+ return (0, exports.summarizeReactModuleSource)(sourceText, filePath);
82
+ };
83
+ exports.summarizeReactModuleFile = summarizeReactModuleFile;
84
+ //# sourceMappingURL=react-module-summary.js.map
@@ -1,43 +1,6 @@
1
- /**
2
- * Shared helpers for folder-structure rules that need to look beyond the file
3
- * ESLint is currently linting: walking a library's `src/` tree and resolving
4
- * relative imports.
5
- *
6
- * ## Main Functions
7
- * - `getSrcRoot()` - Locate the `src/` directory that owns a file
8
- * - `walkSourceFiles()` - List every non-spec/story source file under a directory
9
- * - `resolveRelativeImportPath()` - Resolve `./foo` the way TypeScript would (`.ts`, `.tsx`, `index.*`)
10
- * - `createSrcRootCache()` - Memoise an expensive per-`src/`-root computation
11
- * - `clearSourceTreeCaches()` - Reset every cache created here. Useful for testing.
12
- */
13
- export declare const SOURCE_FILE_EXTENSIONS: readonly [".ts", ".tsx", ".js", ".jsx"];
14
1
  export declare const PASCAL_CASE_PATTERN: RegExp;
15
2
  export declare const isSourceFile: (filePath: string) => boolean;
16
3
  /** `useFoo.spec.tsx` → `useFoo.spec`; `Button.tsx` → `Button`. */
17
4
  export declare const getBaseName: (fileName: string) => string;
18
5
  /** The innermost `…/src` directory containing `filePath`, or `null` when there is none. */
19
6
  export declare const getSrcRoot: (filePath: string) => string | null;
20
- export declare const readSourceFile: (filePath: string) => string | null;
21
- export declare const walkSourceFiles: (directory: string) => ReadonlyArray<string>;
22
- /**
23
- * Resolve a relative import the way TypeScript does: exact path, then each
24
- * source extension, then a directory `index.*`. Non-relative specifiers
25
- * (packages, path aliases) resolve to `null`.
26
- */
27
- export declare const resolveRelativeImportPath: (importerFilePath: string, importSource: string) => string | null;
28
- type SrcRootCache<TValue> = {
29
- readonly get: (srcRoot: string) => TValue;
30
- };
31
- /**
32
- * Memoise `compute` per `src/` root for the lifetime of the ESLint process.
33
- *
34
- * Rules that inspect the whole tree would otherwise redo the same walk for every
35
- * file they lint. The trade-off is that a long-lived editor ESLint server sees a
36
- * snapshot from its first lint of each library until it is restarted.
37
- */
38
- export declare const createSrcRootCache: <TValue>(compute: (srcRoot: string) => TValue) => SrcRootCache<TValue>;
39
- /**
40
- * Clear every cache created with `createSrcRootCache`. Useful for testing.
41
- */
42
- export declare const clearSourceTreeCaches: () => void;
43
- export {};
@@ -1,26 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.clearSourceTreeCaches = exports.createSrcRootCache = exports.resolveRelativeImportPath = exports.walkSourceFiles = exports.readSourceFile = exports.getSrcRoot = exports.getBaseName = exports.isSourceFile = exports.PASCAL_CASE_PATTERN = exports.SOURCE_FILE_EXTENSIONS = void 0;
3
+ exports.getSrcRoot = exports.getBaseName = exports.isSourceFile = exports.PASCAL_CASE_PATTERN = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const fs = tslib_1.__importStar(require("fs"));
6
5
  const path = tslib_1.__importStar(require("path"));
7
6
  /**
8
- * Shared helpers for folder-structure rules that need to look beyond the file
9
- * ESLint is currently linting: walking a library's `src/` tree and resolving
10
- * relative imports.
7
+ * Shared path helpers for folder-structure rules.
11
8
  *
12
9
  * ## Main Functions
13
10
  * - `getSrcRoot()` - Locate the `src/` directory that owns a file
14
- * - `walkSourceFiles()` - List every non-spec/story source file under a directory
15
- * - `resolveRelativeImportPath()` - Resolve `./foo` the way TypeScript would (`.ts`, `.tsx`, `index.*`)
16
- * - `createSrcRootCache()` - Memoise an expensive per-`src/`-root computation
17
- * - `clearSourceTreeCaches()` - Reset every cache created here. Useful for testing.
11
+ * - `isSourceFile()` - A TS/JS file that is not a spec or story
12
+ * - `getBaseName()` - A file name without its last extension
18
13
  */
19
- exports.SOURCE_FILE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
14
+ const SOURCE_FILE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
20
15
  exports.PASCAL_CASE_PATTERN = /^[A-Z][a-zA-Z0-9]*$/;
21
16
  const TEST_OR_STORY_FILE_PATTERN = /\.(spec|stories)\.(tsx?|jsx?)$/;
22
- const IGNORED_DIRECTORY_NAMES = new Set(["node_modules", "dist", "generated"]);
23
- const isSourceExtension = (extension) => exports.SOURCE_FILE_EXTENSIONS.some(sourceExtension => sourceExtension === extension);
17
+ const isSourceExtension = (extension) => SOURCE_FILE_EXTENSIONS.some(sourceExtension => sourceExtension === extension);
24
18
  const isSourceFile = (filePath) => isSourceExtension(path.extname(filePath)) && !TEST_OR_STORY_FILE_PATTERN.test(filePath);
25
19
  exports.isSourceFile = isSourceFile;
26
20
  /** `useFoo.spec.tsx` → `useFoo.spec`; `Button.tsx` → `Button`. */
@@ -36,101 +30,4 @@ const getSrcRoot = (filePath) => {
36
30
  return parts.slice(0, srcIndex + 1).join(path.sep);
37
31
  };
38
32
  exports.getSrcRoot = getSrcRoot;
39
- const readSourceFile = (filePath) => {
40
- try {
41
- return fs.readFileSync(filePath, "utf8");
42
- }
43
- catch {
44
- return null;
45
- }
46
- };
47
- exports.readSourceFile = readSourceFile;
48
- const walkSourceFiles = (directory) => {
49
- const files = [];
50
- const visit = (currentDirectory) => {
51
- let entries;
52
- try {
53
- entries = fs.readdirSync(currentDirectory, { withFileTypes: true });
54
- }
55
- catch {
56
- return;
57
- }
58
- for (const entry of entries) {
59
- const entryPath = path.join(currentDirectory, entry.name);
60
- if (entry.isDirectory()) {
61
- if (!IGNORED_DIRECTORY_NAMES.has(entry.name)) {
62
- visit(entryPath);
63
- }
64
- continue;
65
- }
66
- if (entry.isFile() && (0, exports.isSourceFile)(entryPath)) {
67
- files.push(entryPath);
68
- }
69
- }
70
- };
71
- visit(directory);
72
- return files;
73
- };
74
- exports.walkSourceFiles = walkSourceFiles;
75
- /**
76
- * Resolve a relative import the way TypeScript does: exact path, then each
77
- * source extension, then a directory `index.*`. Non-relative specifiers
78
- * (packages, path aliases) resolve to `null`.
79
- */
80
- const resolveRelativeImportPath = (importerFilePath, importSource) => {
81
- if (!importSource.startsWith(".")) {
82
- return null;
83
- }
84
- const resolvedBase = path.normalize(path.resolve(path.dirname(importerFilePath), importSource));
85
- const candidates = [
86
- resolvedBase,
87
- ...exports.SOURCE_FILE_EXTENSIONS.map(extension => `${resolvedBase}${extension}`),
88
- ...exports.SOURCE_FILE_EXTENSIONS.map(extension => path.join(resolvedBase, `index${extension}`)),
89
- ];
90
- for (const candidate of candidates) {
91
- try {
92
- if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
93
- return path.normalize(candidate);
94
- }
95
- }
96
- catch {
97
- continue;
98
- }
99
- }
100
- return null;
101
- };
102
- exports.resolveRelativeImportPath = resolveRelativeImportPath;
103
- const cacheResets = [];
104
- /**
105
- * Memoise `compute` per `src/` root for the lifetime of the ESLint process.
106
- *
107
- * Rules that inspect the whole tree would otherwise redo the same walk for every
108
- * file they lint. The trade-off is that a long-lived editor ESLint server sees a
109
- * snapshot from its first lint of each library until it is restarted.
110
- */
111
- const createSrcRootCache = (compute) => {
112
- const cache = new Map();
113
- cacheResets.push(() => cache.clear());
114
- return {
115
- get: srcRoot => {
116
- const cached = cache.get(srcRoot);
117
- if (cached !== undefined) {
118
- return cached;
119
- }
120
- const computed = compute(srcRoot);
121
- cache.set(srcRoot, computed);
122
- return computed;
123
- },
124
- };
125
- };
126
- exports.createSrcRootCache = createSrcRootCache;
127
- /**
128
- * Clear every cache created with `createSrcRootCache`. Useful for testing.
129
- */
130
- const clearSourceTreeCaches = () => {
131
- for (const reset of cacheResets) {
132
- reset();
133
- }
134
- };
135
- exports.clearSourceTreeCaches = clearSourceTreeCaches;
136
33
  //# sourceMappingURL=source-tree-utils.js.map
@@ -1,9 +0,0 @@
1
- /**
2
- * ESLint rule: require-nested-components-privacy
3
- *
4
- * Child components under `<Parent>/components/` are private to the parent module.
5
- * Blocks relative imports and re-exports of those children from outside the parent.
6
- */
7
- export declare const requireNestedComponentsPrivacy: import("@typescript-eslint/utils/ts-eslint").RuleModule<"nestedComponentUsedOutsideParent", [], unknown, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
8
- name: string;
9
- };
@@ -1,63 +0,0 @@
1
- "use strict";
2
- /**
3
- * ESLint rule: require-nested-components-privacy
4
- *
5
- * Child components under `<Parent>/components/` are private to the parent module.
6
- * Blocks relative imports and re-exports of those children from outside the parent.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.requireNestedComponentsPrivacy = void 0;
10
- const create_rule_1 = require("../../utils/create-rule/create-rule");
11
- const nested_component_privacy_utils_1 = require("./utils/nested-component-privacy-utils/nested-component-privacy-utils");
12
- exports.requireNestedComponentsPrivacy = (0, create_rule_1.createRule)({
13
- name: "require-nested-components-privacy",
14
- meta: {
15
- type: "suggestion",
16
- docs: {
17
- description: "Disallow importing child components from another component module's private `components/` subfolder.",
18
- },
19
- schema: [],
20
- messages: {
21
- nestedComponentUsedOutsideParent: "`{{childComponentName}}` is private to `{{parentComponentName}}`. Import it from a shared " +
22
- "location instead of `{{parentComponentName}}/components/`.",
23
- },
24
- },
25
- defaultOptions: [],
26
- create(context) {
27
- const reportPrivateImport = (source) => {
28
- if (source.type !== "Literal" || typeof source.value !== "string") {
29
- return;
30
- }
31
- const violation = (0, nested_component_privacy_utils_1.analyzeNestedComponentImport)(context.filename, source.value);
32
- if (violation === null) {
33
- return;
34
- }
35
- context.report({
36
- node: source,
37
- messageId: "nestedComponentUsedOutsideParent",
38
- data: {
39
- parentComponentName: violation.parentComponentName,
40
- childComponentName: violation.childComponentName,
41
- },
42
- });
43
- };
44
- return {
45
- ImportDeclaration(node) {
46
- reportPrivateImport(node.source);
47
- },
48
- ImportExpression(node) {
49
- reportPrivateImport(node.source);
50
- },
51
- ExportNamedDeclaration(node) {
52
- if (node.source === null) {
53
- return;
54
- }
55
- reportPrivateImport(node.source);
56
- },
57
- ExportAllDeclaration(node) {
58
- reportPrivateImport(node.source);
59
- },
60
- };
61
- },
62
- });
63
- //# sourceMappingURL=require-nested-components-privacy.js.map
@@ -1,14 +0,0 @@
1
- export type NestedComponentPrivacyViolation = {
2
- readonly parentComponentName: string;
3
- readonly childComponentName: string;
4
- };
5
- /**
6
- * Returns a violation when `importerFilePath` imports a component from another
7
- * component module's private `components/` subfolder via a relative specifier.
8
- *
9
- * Scope (by design):
10
- * - Only `components/<Parent>/<Parent>.tsx` modules that contain a matching component file count as owners.
11
- * - Only paths under `…/<Parent>/components/<Child>/` are treated as private children.
12
- * - Does not cover `pages/`, `hooks/`, `utils/`, or package imports — promote shared UI to module `components/`.
13
- */
14
- export declare const analyzeNestedComponentImport: (importerFilePath: string, importSource: string) => NestedComponentPrivacyViolation | null;
@@ -1,62 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.analyzeNestedComponentImport = void 0;
4
- const tslib_1 = require("tslib");
5
- const path = tslib_1.__importStar(require("path"));
6
- const source_tree_utils_1 = require("../../../../utils/source-tree-utils/source-tree-utils");
7
- const nested_component_directory_utils_1 = require("../../../require-nested-components-directory/utils/nested-component-directory-utils/nested-component-directory-utils");
8
- const AGGREGATION_FOLDERS = new Set(["shared"]);
9
- /**
10
- * Returns a violation when `importerFilePath` imports a component from another
11
- * component module's private `components/` subfolder via a relative specifier.
12
- *
13
- * Scope (by design):
14
- * - Only `components/<Parent>/<Parent>.tsx` modules that contain a matching component file count as owners.
15
- * - Only paths under `…/<Parent>/components/<Child>/` are treated as private children.
16
- * - Does not cover `pages/`, `hooks/`, `utils/`, or package imports — promote shared UI to module `components/`.
17
- */
18
- const analyzeNestedComponentImport = (importerFilePath, importSource) => {
19
- if (!importSource.startsWith(".")) {
20
- return null;
21
- }
22
- const normalizedImporterPath = path.normalize(importerFilePath);
23
- const importerDirectory = path.dirname(normalizedImporterPath);
24
- const resolvedImportPath = path.normalize(path.resolve(importerDirectory, importSource));
25
- const segments = resolvedImportPath.split(path.sep);
26
- let parentComponentName;
27
- let childComponentName;
28
- let parentComponentDirectory = "";
29
- for (let index = 1; index < segments.length - 1; index += 1) {
30
- const childName = segments[index + 1];
31
- const parentName = segments[index - 1];
32
- if (segments[index] !== "components" || parentName === undefined || childName === undefined) {
33
- continue;
34
- }
35
- if (!source_tree_utils_1.PASCAL_CASE_PATTERN.test(childName) || !source_tree_utils_1.PASCAL_CASE_PATTERN.test(parentName)) {
36
- continue;
37
- }
38
- const ownerComponentDirectory = segments.slice(0, index).join(path.sep);
39
- if (path.basename(path.dirname(ownerComponentDirectory)) !== "components" ||
40
- !(0, nested_component_directory_utils_1.isParentComponentModule)(ownerComponentDirectory) ||
41
- AGGREGATION_FOLDERS.has(parentName)) {
42
- continue;
43
- }
44
- parentComponentName = parentName;
45
- childComponentName = childName;
46
- parentComponentDirectory = ownerComponentDirectory;
47
- }
48
- if (parentComponentName === undefined || childComponentName === undefined) {
49
- return null;
50
- }
51
- const importerWithinParent = normalizedImporterPath === parentComponentDirectory ||
52
- normalizedImporterPath.startsWith(`${parentComponentDirectory}${path.sep}`);
53
- if (importerWithinParent) {
54
- return null;
55
- }
56
- return {
57
- parentComponentName,
58
- childComponentName,
59
- };
60
- };
61
- exports.analyzeNestedComponentImport = analyzeNestedComponentImport;
62
- //# sourceMappingURL=nested-component-privacy-utils.js.map
@@ -1,8 +0,0 @@
1
- /**
2
- * ESLint rule: require-page-directory
3
- *
4
- * Components passed to a route as `component` must live under a `pages/` directory.
5
- */
6
- export declare const requirePageDirectory: import("@typescript-eslint/utils/ts-eslint").RuleModule<"routeComponentOutsidePagesFolder", [], unknown, import("@typescript-eslint/utils/ts-eslint").RuleListener> & {
7
- name: string;
8
- };
@@ -1,44 +0,0 @@
1
- "use strict";
2
- /**
3
- * ESLint rule: require-page-directory
4
- *
5
- * Components passed to a route as `component` must live under a `pages/` directory.
6
- */
7
- Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.requirePageDirectory = void 0;
9
- const create_rule_1 = require("../../utils/create-rule/create-rule");
10
- const page_directory_structure_utils_1 = require("./utils/page-directory-structure-utils/page-directory-structure-utils");
11
- exports.requirePageDirectory = (0, create_rule_1.createRule)({
12
- name: "require-page-directory",
13
- meta: {
14
- type: "suggestion",
15
- docs: {
16
- description: "Require route components to live under a `pages/` directory.",
17
- },
18
- schema: [],
19
- messages: {
20
- routeComponentOutsidePagesFolder: "`{{pageComponentName}}` is used as a route component in `{{routeFilePath}}`. Move it to `{{suggestedRelativePath}}`.",
21
- },
22
- },
23
- defaultOptions: [],
24
- create(context) {
25
- return {
26
- Program(node) {
27
- const violation = (0, page_directory_structure_utils_1.analyzePageFolderStructure)(context.filename);
28
- if (violation?.kind !== "routeComponentOutsidePagesFolder") {
29
- return;
30
- }
31
- context.report({
32
- node,
33
- messageId: "routeComponentOutsidePagesFolder",
34
- data: {
35
- pageComponentName: violation.pageComponentName,
36
- routeFilePath: violation.routeFilePath,
37
- suggestedRelativePath: violation.suggestedRelativePath,
38
- },
39
- });
40
- },
41
- };
42
- },
43
- });
44
- //# sourceMappingURL=require-page-directory.js.map
@@ -1,18 +0,0 @@
1
- type PageFolderViolation = {
2
- readonly kind: "routeComponentOutsidePagesFolder";
3
- readonly pageComponentName: string;
4
- readonly routeFilePath: string;
5
- readonly suggestedRelativePath: string;
6
- };
7
- /** True when `filePath` is the file a route registers as `component`. */
8
- export declare const isRegisteredRouteComponentFile: (filePath: string) => boolean;
9
- /**
10
- * Returns a violation when `filePath` is the `component` of a route but does not
11
- * live in `pages/<Name>/<Name>.tsx` (including `<Scope>/pages/<Name>/`).
12
- *
13
- * `App` is not treated as a page. A nested file stays exempt only while the route
14
- * component file is still in that folder. After the page moves, a child left
15
- * behind is outside `pages/`.
16
- */
17
- export declare const analyzePageFolderStructure: (filePath: string) => PageFolderViolation | null;
18
- export {};
@@ -1,159 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.analyzePageFolderStructure = exports.isRegisteredRouteComponentFile = void 0;
4
- const tslib_1 = require("tslib");
5
- const path = tslib_1.__importStar(require("path"));
6
- const ts = tslib_1.__importStar(require("typescript"));
7
- const source_tree_utils_1 = require("../../../../utils/source-tree-utils/source-tree-utils");
8
- const ROUTE_FILE_NAMES = new Set(["router.tsx", "routeTree.tsx", "routes.tsx"]);
9
- const isRouteDefinitionFile = (filePath) => {
10
- const fileName = path.basename(filePath);
11
- return (ROUTE_FILE_NAMES.has(fileName) ||
12
- fileName.endsWith(".routes.ts") ||
13
- fileName.endsWith(".routes.tsx") ||
14
- fileName.endsWith("Routes.tsx") ||
15
- fileName.endsWith("Route.tsx"));
16
- };
17
- const isPageComponentName = (componentName) => componentName !== "App";
18
- const isNamedPageFile = (srcRoot, filePath) => {
19
- const segments = path.relative(srcRoot, filePath).split(path.sep);
20
- const pagesIndex = segments.lastIndexOf("pages");
21
- const fileName = segments.at(-1);
22
- const folderName = segments.at(-2);
23
- if (pagesIndex === -1 || fileName === undefined || folderName === undefined) {
24
- return false;
25
- }
26
- return folderName === (0, source_tree_utils_1.getBaseName)(fileName);
27
- };
28
- const parseRouteFile = (filePath, content) => {
29
- const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
30
- const importMap = new Map();
31
- const localComponentBindings = new Map();
32
- const componentNames = [];
33
- const visit = (node) => {
34
- if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier) && node.importClause !== undefined) {
35
- const source = node.moduleSpecifier.text;
36
- if (node.importClause.name !== undefined) {
37
- importMap.set(node.importClause.name.text, source);
38
- }
39
- const bindings = node.importClause.namedBindings;
40
- if (bindings !== undefined && ts.isNamedImports(bindings)) {
41
- for (const element of bindings.elements) {
42
- importMap.set(element.name.text, source);
43
- }
44
- }
45
- }
46
- if (ts.isVariableDeclaration(node) &&
47
- ts.isIdentifier(node.name) &&
48
- node.initializer !== undefined &&
49
- ts.isIdentifier(node.initializer)) {
50
- localComponentBindings.set(node.name.text, node.initializer.text);
51
- }
52
- if (ts.isPropertyAssignment(node) &&
53
- ts.isIdentifier(node.name) &&
54
- node.name.text === "component" &&
55
- ts.isIdentifier(node.initializer)) {
56
- componentNames.push(node.initializer.text);
57
- }
58
- if (ts.isShorthandPropertyAssignment(node) && node.name.text === "component") {
59
- const resolvedName = localComponentBindings.get("component") ?? node.name.text;
60
- componentNames.push(resolvedName);
61
- }
62
- ts.forEachChild(node, visit);
63
- };
64
- visit(sourceFile);
65
- return { importMap, componentNames };
66
- };
67
- const buildRouteComponentIndex = (srcRoot) => {
68
- const routeFileByComponent = new Map();
69
- for (const sourceFile of (0, source_tree_utils_1.walkSourceFiles)(srcRoot)) {
70
- if (!isRouteDefinitionFile(sourceFile)) {
71
- continue;
72
- }
73
- const content = (0, source_tree_utils_1.readSourceFile)(sourceFile);
74
- if (content === null) {
75
- continue;
76
- }
77
- const { importMap, componentNames } = parseRouteFile(sourceFile, content);
78
- for (const componentName of componentNames) {
79
- if (!isPageComponentName(componentName)) {
80
- continue;
81
- }
82
- const importSource = importMap.get(componentName);
83
- const resolvedPath = importSource === undefined ? null : (0, source_tree_utils_1.resolveRelativeImportPath)(sourceFile, importSource);
84
- if (resolvedPath !== null && !routeFileByComponent.has(resolvedPath)) {
85
- routeFileByComponent.set(resolvedPath, sourceFile);
86
- }
87
- }
88
- }
89
- return routeFileByComponent;
90
- };
91
- const routeComponentIndexCache = (0, source_tree_utils_1.createSrcRootCache)(buildRouteComponentIndex);
92
- /** True when `filePath` is the file a route registers as `component`. */
93
- const isRegisteredRouteComponentFile = (filePath) => {
94
- const srcRoot = (0, source_tree_utils_1.getSrcRoot)(filePath);
95
- if (srcRoot === null) {
96
- return false;
97
- }
98
- return routeComponentIndexCache.get(srcRoot).has(path.normalize(filePath));
99
- };
100
- exports.isRegisteredRouteComponentFile = isRegisteredRouteComponentFile;
101
- const isNestedUnderRouteComponentModuleFolder = (srcRoot, filePath, routeFileByComponent) => {
102
- const routeComponentNames = new Set();
103
- for (const routeComponentPath of routeFileByComponent.keys()) {
104
- routeComponentNames.add((0, source_tree_utils_1.getBaseName)(path.basename(routeComponentPath)));
105
- }
106
- const relativeDirectory = path.relative(srcRoot, path.dirname(filePath));
107
- const segments = relativeDirectory.split(path.sep).filter(segment => segment.length > 0);
108
- for (let index = 0; index < segments.length; index += 1) {
109
- const segment = segments[index];
110
- if (segment === undefined || !routeComponentNames.has(segment)) {
111
- continue;
112
- }
113
- const moduleFolder = path.join(srcRoot, ...segments.slice(0, index + 1));
114
- const routeComponentFile = path.join(moduleFolder, `${segment}.tsx`);
115
- if (!routeFileByComponent.has(routeComponentFile)) {
116
- continue;
117
- }
118
- if (filePath !== routeComponentFile && filePath.startsWith(`${moduleFolder}${path.sep}`)) {
119
- return true;
120
- }
121
- }
122
- return false;
123
- };
124
- const getSuggestedPagePath = (srcRoot, componentFilePath) => {
125
- const relativeSegments = path.relative(srcRoot, componentFilePath).split(path.sep);
126
- const fileName = path.basename(componentFilePath);
127
- const componentsIndex = relativeSegments.indexOf("components");
128
- const scope = componentsIndex > 0 ? relativeSegments.slice(0, componentsIndex) : [];
129
- return path.join(...scope, "pages", (0, source_tree_utils_1.getBaseName)(fileName), fileName);
130
- };
131
- /**
132
- * Returns a violation when `filePath` is the `component` of a route but does not
133
- * live in `pages/<Name>/<Name>.tsx` (including `<Scope>/pages/<Name>/`).
134
- *
135
- * `App` is not treated as a page. A nested file stays exempt only while the route
136
- * component file is still in that folder. After the page moves, a child left
137
- * behind is outside `pages/`.
138
- */
139
- const analyzePageFolderStructure = (filePath) => {
140
- const normalizedPath = path.normalize(filePath);
141
- const srcRoot = (0, source_tree_utils_1.getSrcRoot)(normalizedPath);
142
- if (srcRoot === null || isNamedPageFile(srcRoot, normalizedPath)) {
143
- return null;
144
- }
145
- const routeFileByComponent = routeComponentIndexCache.get(srcRoot);
146
- const routeFilePath = routeFileByComponent.get(normalizedPath);
147
- if (routeFilePath === undefined ||
148
- isNestedUnderRouteComponentModuleFolder(srcRoot, normalizedPath, routeFileByComponent)) {
149
- return null;
150
- }
151
- return {
152
- kind: "routeComponentOutsidePagesFolder",
153
- pageComponentName: (0, source_tree_utils_1.getBaseName)(path.basename(normalizedPath)),
154
- routeFilePath: path.relative(srcRoot, routeFilePath),
155
- suggestedRelativePath: getSuggestedPagePath(srcRoot, normalizedPath),
156
- };
157
- };
158
- exports.analyzePageFolderStructure = analyzePageFolderStructure;
159
- //# sourceMappingURL=page-directory-structure-utils.js.map