@gosukiwi/eslint-plugin-colocate 0.0.2
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 +21 -0
- package/README.md +197 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +12 -0
- package/dist/lib/derived.d.ts +4 -0
- package/dist/lib/derived.js +15 -0
- package/dist/lib/findings.d.ts +9 -0
- package/dist/lib/findings.js +96 -0
- package/dist/lib/fs-safe.d.ts +8 -0
- package/dist/lib/fs-safe.js +55 -0
- package/dist/lib/gates.d.ts +10 -0
- package/dist/lib/gates.js +46 -0
- package/dist/lib/graph-cache.d.ts +5 -0
- package/dist/lib/graph-cache.js +162 -0
- package/dist/lib/graph.d.ts +20 -0
- package/dist/lib/graph.js +109 -0
- package/dist/lib/named-door.d.ts +6 -0
- package/dist/lib/named-door.js +361 -0
- package/dist/lib/owners.d.ts +22 -0
- package/dist/lib/owners.js +386 -0
- package/dist/lib/parse.d.ts +4 -0
- package/dist/lib/parse.js +59 -0
- package/dist/lib/paths.d.ts +2 -0
- package/dist/lib/paths.js +8 -0
- package/dist/lib/require-binding.d.ts +5 -0
- package/dist/lib/require-binding.js +72 -0
- package/dist/lib/resolve.d.ts +9 -0
- package/dist/lib/resolve.js +161 -0
- package/dist/lib/root.d.ts +1 -0
- package/dist/lib/root.js +27 -0
- package/dist/lib/scope.d.ts +8 -0
- package/dist/lib/scope.js +58 -0
- package/dist/lib/subject.d.ts +16 -0
- package/dist/lib/subject.js +61 -0
- package/dist/lib/walk.d.ts +10 -0
- package/dist/lib/walk.js +97 -0
- package/dist/rules/entry.d.ts +3 -0
- package/dist/rules/entry.js +141 -0
- package/dist/rules/ownership.d.ts +3 -0
- package/dist/rules/ownership.js +45 -0
- package/package.json +45 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Federico Ramirez
|
|
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,197 @@
|
|
|
1
|
+
# eslint-plugin-colocate
|
|
2
|
+
|
|
3
|
+
Put files next to whoever uses them.
|
|
4
|
+
|
|
5
|
+
An ESLint plugin that enforces dependency-based file organization. A file used by one module belongs inside that module's folder. A file used by several belongs at their closest common ancestor — not buried in one of them, and not floating above them. Empty wrapper folders get flagged too.
|
|
6
|
+
|
|
7
|
+
The folders become a map of who uses what. Moving a file has a right answer. Reviewers and AI agents follow the same rule, so the layout stays consistent as the codebase grows.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install -D @gosukiwi/eslint-plugin-colocate
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Requires Node 20+ and ESLint 9+.
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
import colocate from "@gosukiwi/eslint-plugin-colocate";
|
|
21
|
+
|
|
22
|
+
export default [
|
|
23
|
+
{
|
|
24
|
+
plugins: {
|
|
25
|
+
colocate,
|
|
26
|
+
},
|
|
27
|
+
rules: {
|
|
28
|
+
"colocate/ownership": [
|
|
29
|
+
"error",
|
|
30
|
+
{
|
|
31
|
+
root: "src",
|
|
32
|
+
layers: ["src/ui"],
|
|
33
|
+
ignore: ["**/*.generated.ts"],
|
|
34
|
+
},
|
|
35
|
+
],
|
|
36
|
+
"colocate/entry": ["error", { root: "src" }],
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
];
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Examples
|
|
43
|
+
|
|
44
|
+
**Private — only `MyPage` imports `helper`**
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
# BAD
|
|
48
|
+
src/pages/helper.ts
|
|
49
|
+
src/pages/MyPage/MyPage.ts
|
|
50
|
+
|
|
51
|
+
# GOOD
|
|
52
|
+
src/pages/MyPage/MyPage.ts
|
|
53
|
+
src/pages/MyPage/helper.ts
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
**Shared — `A` and `B` both import `fmt`**
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
# BAD — buried in one owner
|
|
60
|
+
src/pages/A/A.ts
|
|
61
|
+
src/pages/A/fmt.ts
|
|
62
|
+
src/pages/B/B.ts
|
|
63
|
+
|
|
64
|
+
# BAD — sitting above their common ancestor
|
|
65
|
+
src/fmt.ts
|
|
66
|
+
src/pages/A/A.ts
|
|
67
|
+
src/pages/B/B.ts
|
|
68
|
+
|
|
69
|
+
# GOOD — at pages/, the common ancestor
|
|
70
|
+
src/pages/fmt.ts
|
|
71
|
+
src/pages/A/A.ts
|
|
72
|
+
src/pages/B/B.ts
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
**Singleton folder — a wrapper around one file**
|
|
76
|
+
|
|
77
|
+
```
|
|
78
|
+
# BAD
|
|
79
|
+
src/Foo/Foo.ts
|
|
80
|
+
|
|
81
|
+
# GOOD — flatten
|
|
82
|
+
src/Foo.ts
|
|
83
|
+
|
|
84
|
+
# GOOD — or colocate a stylesheet
|
|
85
|
+
src/Foo/Foo.ts
|
|
86
|
+
src/Foo/Foo.module.css
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
**App shell — `App` imports `Home`; it does not own it**
|
|
90
|
+
|
|
91
|
+
```
|
|
92
|
+
# GOOD
|
|
93
|
+
src/main.ts ← entry (nothing imports it)
|
|
94
|
+
src/App.ts ← imported only by main
|
|
95
|
+
src/pages/Home/Home.ts ← stays a page, not pulled into App
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
**Layers — `layers: ["src/ui"]` makes `Button` a public peer**
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
# GOOD even if only Home imports Button
|
|
102
|
+
src/ui/Button/Button.ts
|
|
103
|
+
src/pages/Home/Home.ts
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## The model
|
|
107
|
+
|
|
108
|
+
The plugin builds an import graph over `root` and checks that each file's location matches its consumers.
|
|
109
|
+
|
|
110
|
+
**Owners.** A directory is an owner when it has an entry file: one named after the directory (`pages/MyPage/MyPage.ts`), or an `index` that outside code imports through. A barrel that only groups loose helpers does not make its directory an owner. A file with no such folder around it owns only itself.
|
|
111
|
+
|
|
112
|
+
**Private files.** Imported by exactly one owner → belong inside that owner's folder.
|
|
113
|
+
|
|
114
|
+
**Shared files.** Imported by two or more owners → belong at their closest common ancestor, not above it and not inside one of them.
|
|
115
|
+
|
|
116
|
+
A folder's own entry file is never flagged for sitting in its own folder. If the folder itself is in the wrong place, the folders above it report that.
|
|
117
|
+
|
|
118
|
+
**The app shell.** Entry points (files nothing imports) and what they import directly do not own those imports. So `main.ts → App.ts → pages/Home/Home.ts` leaves `Home` where it is, with no configuration.
|
|
119
|
+
|
|
120
|
+
For a longer bootstrap chain (`main → router → App → pages/...`), or a shell that imports loose top-level modules, declare those directories as `layers`.
|
|
121
|
+
|
|
122
|
+
## What it reports
|
|
123
|
+
|
|
124
|
+
*This covers `colocate/ownership`'s findings. `colocate/entry` reports `reachesPastEntry` and `namedDoorReexport` — see [The entry rule](#the-entry-rule).*
|
|
125
|
+
|
|
126
|
+
| message | meaning | usual fix |
|
|
127
|
+
| --- | --- | --- |
|
|
128
|
+
| `privateOutsideOwner` | One owner imports this file, and it sits outside that owner's folder. | Move it inside the folder, or convert the owner into a folder with a matching entry file. |
|
|
129
|
+
| `sharedTooHigh` | Several owners import it, and it sits above their common ancestor. | Move it down to the common ancestor. |
|
|
130
|
+
| `sharedInsideOwner` | Several owners import it, and it sits inside one of theirs. | Hoist it to the common ancestor. |
|
|
131
|
+
| `singletonFolder` | A directory holds a single source file named after the directory (or `index`), and no stylesheet beside it. | Flatten the directory, or colocate something with the file. |
|
|
132
|
+
|
|
133
|
+
`singletonFolder` looks for a companion stylesheet only in the same directory (`.css`, `.scss`, `.sass`, `.less`, `.styl`).
|
|
134
|
+
|
|
135
|
+
An `index` that re-exports two or more siblings is a namespace barrel and is left alone.
|
|
136
|
+
|
|
137
|
+
## Options
|
|
138
|
+
|
|
139
|
+
*These apply to `colocate/ownership`. See [The entry rule](#the-entry-rule) for `colocate/entry`'s options.* Unknown option names are rejected.
|
|
140
|
+
|
|
141
|
+
### `root`
|
|
142
|
+
|
|
143
|
+
Directory to walk, and the ceiling for ownership. Default `"."`. Set `"src"` for a typical app.
|
|
144
|
+
|
|
145
|
+
A relative `root` is resolved from the working directory, then searched upward so `eslint` still works from a subdirectory. The search stops at the nearest `package.json` or `.git`. Files outside `root` are never reported.
|
|
146
|
+
|
|
147
|
+
### `layers`
|
|
148
|
+
|
|
149
|
+
Directories whose immediate children are public peers: they may have one consumer or many, and they stay where they are. With `layers: ["src/ui"]`, `src/ui/Button` is not expected to move into the page that uses it.
|
|
150
|
+
|
|
151
|
+
Paths are matched relative to `root` and to the working directory, so with `root: "src"` both `["ui"]` and `["src/ui"]` work.
|
|
152
|
+
|
|
153
|
+
Only the layer's own files and each child folder's entry (`Button/Button.ts` or `Button/index.ts`) get this treatment. Files deeper in (`ui/Button/internals/state.ts`) are still checked.
|
|
154
|
+
|
|
155
|
+
This is also how a deeper app shell is described:
|
|
156
|
+
|
|
157
|
+
```js
|
|
158
|
+
layers: ["src", "src/pages"] // top-level modules and pages are public peers
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### `ignore`
|
|
162
|
+
|
|
163
|
+
Globs relative to `root`. Ignored files are not reported and do not count as consumers. A glob naming a directory excludes everything under it. Negation (`!`) is not supported — list what to exclude.
|
|
164
|
+
|
|
165
|
+
## The entry rule
|
|
166
|
+
|
|
167
|
+
`colocate/ownership` decides where a file belongs. `colocate/entry` decides how you get in.
|
|
168
|
+
|
|
169
|
+
A directory containing an **entry file** — one named after the directory, or an `index` — is a module with a front door. Imports from outside must land on a door. Reaching past every door into the internals is an error.
|
|
170
|
+
|
|
171
|
+
```
|
|
172
|
+
src/pages/Inbox/Inbox.ts
|
|
173
|
+
src/pages/Inbox/state.ts
|
|
174
|
+
|
|
175
|
+
// BAD — reaches past the door into an internal file
|
|
176
|
+
import { loadThread } from "../pages/Inbox/state.ts";
|
|
177
|
+
|
|
178
|
+
// GOOD — enters through the door
|
|
179
|
+
import { loadThread } from "../pages/Inbox/Inbox.ts";
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
**Nested doors count.** A nested module's own door is a legal landing place, so `pages/Inbox/FilterPanel/FilterPanel.ts` is reachable from anywhere. Only a file that is nobody's door is off limits.
|
|
183
|
+
|
|
184
|
+
**A directory with no entry file is not a module.** It gates nothing, and the rule demands nothing of it — a folder of independent siblings (`lib/`, `tabs/`) stays exactly as it is. The rule is a ratchet: add a door when a directory deserves one, and from then on it's the only way in.
|
|
185
|
+
|
|
186
|
+
**Unlike `ownership`, entry points get no exemption.** A file nothing imports still may not reach past a door; a shell burrowing into a feature's internals is exactly the finding worth having.
|
|
187
|
+
|
|
188
|
+
**Two kinds of door.** A file named after its folder (`Foo/Foo.ts`) is the shortcut door: the public module is that file, and it may export only what it declares. `index.ts` is the barrel door: the public surface may come from more than one file. `colocate/entry` reports `namedDoorReexport` when a named door identity-re-exports another source file in the graph — the usual fix is to add or use `index.ts`, or stop re-exporting. Re-exporting siblings from `index` is allowed; type-only re-exports are not this finding. Reaching past a door is still `reachesPastEntry` (unchanged).
|
|
189
|
+
|
|
190
|
+
Options are `root` and `ignore`, with the same meaning as `ownership`. There is no `layers` option — layers are about placement, and say nothing about access. Do not ignore an entry file: that removes the door, and reaching into that folder stops being an error. There is no autofix: rewriting a specifier would produce code that doesn't compile whenever the door doesn't already re-export the symbol, so widening the door is left to the user.
|
|
191
|
+
|
|
192
|
+
## Notes
|
|
193
|
+
|
|
194
|
+
- Resolution uses the TypeScript compiler, so `paths` and `baseUrl` from the nearest `tsconfig.json` are honoured. Extensionless imports and `./x.js` → `x.ts` work the way bundlers do.
|
|
195
|
+
- Tests, `node_modules`, `dist`, coverage, VCS dirs, and `.d.ts` files are skipped.
|
|
196
|
+
- Code reachable only through an import cycle is not checked. Breaking the cycle restores the reports.
|
|
197
|
+
- On a case-insensitive filesystem, config paths (`root: "SRC"` vs `src`) still have to match disk casing.
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export function derivedFromGraph(build) {
|
|
2
|
+
const table = new WeakMap();
|
|
3
|
+
const get = (graph, ...args) => {
|
|
4
|
+
let value = table.get(graph);
|
|
5
|
+
if (value === undefined) {
|
|
6
|
+
value = build(graph, ...args);
|
|
7
|
+
table.set(graph, value);
|
|
8
|
+
}
|
|
9
|
+
return value;
|
|
10
|
+
};
|
|
11
|
+
get.prime = (graph, value) => {
|
|
12
|
+
table.set(graph, value);
|
|
13
|
+
};
|
|
14
|
+
return get;
|
|
15
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Graph } from "./graph.js";
|
|
2
|
+
import type { Subject } from "./subject.js";
|
|
3
|
+
export interface SingletonDirectoryStats {
|
|
4
|
+
sourceCount: number;
|
|
5
|
+
hasStylesheet: boolean;
|
|
6
|
+
}
|
|
7
|
+
export type OwnershipFinding = "singletonFolder" | "privateOutsideOwner" | "sharedTooHigh" | "sharedInsideOwner";
|
|
8
|
+
export declare function singletonDirectoryStats(dir: string, rootDir: string, ignore: string[], graph: Graph): SingletonDirectoryStats;
|
|
9
|
+
export declare function ownershipFindings(subject: Subject, cwd: string, layers: string[]): OwnershipFinding[];
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { derivedFromGraph } from "./derived.js";
|
|
3
|
+
import { classifyDirEntry, safeReaddir, safeStat } from "./fs-safe.js";
|
|
4
|
+
import { getSharedColocationIssue, isPrivateOutsideOwner, resolveLayerDirectories, } from "./owners.js";
|
|
5
|
+
import { isSourceFile, isTestFile, matchesIgnore, SKIP_DIRS, } from "./scope.js";
|
|
6
|
+
const singletonStatsByGraph = derivedFromGraph(() => new Map());
|
|
7
|
+
const STYLESHEET_EXTS = [".css", ".scss", ".sass", ".less", ".styl"];
|
|
8
|
+
function isStylesheet(filePath) {
|
|
9
|
+
const basename = path.basename(filePath);
|
|
10
|
+
return STYLESHEET_EXTS.some((ext) => basename.endsWith(ext));
|
|
11
|
+
}
|
|
12
|
+
function countSubdirectorySourceFiles(entry, fullPath, rootDir, ignore) {
|
|
13
|
+
if (SKIP_DIRS.has(entry.name)) {
|
|
14
|
+
return 0;
|
|
15
|
+
}
|
|
16
|
+
return countSourceFilesRecursive(fullPath, rootDir, ignore);
|
|
17
|
+
}
|
|
18
|
+
function countEntrySourceFiles(entry, dir, rootDir, ignore) {
|
|
19
|
+
const fullPath = path.join(dir, entry.name);
|
|
20
|
+
const relPath = path.relative(rootDir, fullPath);
|
|
21
|
+
if (matchesIgnore(relPath, ignore)) {
|
|
22
|
+
return 0;
|
|
23
|
+
}
|
|
24
|
+
const kind = classifyDirEntry(entry, fullPath);
|
|
25
|
+
if (kind === "directory") {
|
|
26
|
+
return countSubdirectorySourceFiles(entry, fullPath, rootDir, ignore);
|
|
27
|
+
}
|
|
28
|
+
if (kind === "file" && isSourceFile(fullPath) && !isTestFile(relPath)) {
|
|
29
|
+
return 1;
|
|
30
|
+
}
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
function countSourceFilesRecursive(dir, rootDir, ignore) {
|
|
34
|
+
let sourceCount = 0;
|
|
35
|
+
for (const entry of safeReaddir(dir)) {
|
|
36
|
+
sourceCount += countEntrySourceFiles(entry, dir, rootDir, ignore);
|
|
37
|
+
if (sourceCount > 1) {
|
|
38
|
+
return sourceCount;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return sourceCount;
|
|
42
|
+
}
|
|
43
|
+
export function singletonDirectoryStats(dir, rootDir, ignore, graph) {
|
|
44
|
+
const cache = singletonStatsByGraph(graph);
|
|
45
|
+
const cached = cache.get(dir);
|
|
46
|
+
if (cached !== undefined) {
|
|
47
|
+
return cached;
|
|
48
|
+
}
|
|
49
|
+
const sourceCount = countSourceFilesRecursive(dir, rootDir, ignore);
|
|
50
|
+
const hasStylesheet = sourceCount === 1 && hasCompanionStylesheet(dir);
|
|
51
|
+
const stats = { sourceCount, hasStylesheet };
|
|
52
|
+
cache.set(dir, stats);
|
|
53
|
+
return stats;
|
|
54
|
+
}
|
|
55
|
+
function hasCompanionStylesheet(dir) {
|
|
56
|
+
return safeReaddir(dir).some((entry) => {
|
|
57
|
+
if (!isStylesheet(entry.name)) {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
return entry.isSymbolicLink()
|
|
61
|
+
? (safeStat(path.join(dir, entry.name))?.isFile() ?? false)
|
|
62
|
+
: entry.isFile();
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
function isSingletonWrapperDirectory(dir, filename, rootDir, ignore, graph) {
|
|
66
|
+
const { sourceCount, hasStylesheet } = singletonDirectoryStats(dir, rootDir, ignore, graph);
|
|
67
|
+
if (sourceCount !== 1 || hasStylesheet) {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
const dirName = path.basename(dir);
|
|
71
|
+
const fileBasename = path.basename(filename, path.extname(filename));
|
|
72
|
+
return fileBasename === dirName || fileBasename === "index";
|
|
73
|
+
}
|
|
74
|
+
export function ownershipFindings(subject, cwd, layers) {
|
|
75
|
+
const { realRootDir: rootDir, file, ignore } = subject;
|
|
76
|
+
const dir = path.dirname(file);
|
|
77
|
+
const graph = subject.graph();
|
|
78
|
+
const ctx = {
|
|
79
|
+
graph,
|
|
80
|
+
rootDir,
|
|
81
|
+
layerDirs: resolveLayerDirectories(graph, cwd, layers, rootDir),
|
|
82
|
+
};
|
|
83
|
+
const findings = [];
|
|
84
|
+
if (dir !== rootDir &&
|
|
85
|
+
isSingletonWrapperDirectory(dir, file, rootDir, ignore, graph)) {
|
|
86
|
+
findings.push("singletonFolder");
|
|
87
|
+
}
|
|
88
|
+
if (isPrivateOutsideOwner(file, ctx)) {
|
|
89
|
+
findings.push("privateOutsideOwner");
|
|
90
|
+
}
|
|
91
|
+
const sharedIssue = getSharedColocationIssue(file, ctx);
|
|
92
|
+
if (sharedIssue !== undefined) {
|
|
93
|
+
findings.push(sharedIssue);
|
|
94
|
+
}
|
|
95
|
+
return findings;
|
|
96
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
export declare function safeRealpath(filePath: string): string | undefined;
|
|
3
|
+
export declare function safeStat(filePath: string): fs.Stats | undefined;
|
|
4
|
+
export declare function safeReadFile(filePath: string): string | undefined;
|
|
5
|
+
export declare function safeReaddir(dir: string): fs.Dirent[];
|
|
6
|
+
export type DirEntryKind = "directory" | "file" | "other";
|
|
7
|
+
export declare function symlinkEntryKind(fullPath: string): DirEntryKind;
|
|
8
|
+
export declare function classifyDirEntry(entry: fs.Dirent, fullPath: string): DirEntryKind;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
export function safeRealpath(filePath) {
|
|
3
|
+
try {
|
|
4
|
+
return fs.realpathSync(filePath);
|
|
5
|
+
}
|
|
6
|
+
catch {
|
|
7
|
+
return undefined;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export function safeStat(filePath) {
|
|
11
|
+
try {
|
|
12
|
+
return fs.statSync(filePath);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function safeReadFile(filePath) {
|
|
19
|
+
try {
|
|
20
|
+
return fs.readFileSync(filePath, "utf8");
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export function safeReaddir(dir) {
|
|
27
|
+
try {
|
|
28
|
+
return fs.readdirSync(dir, { withFileTypes: true });
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return [];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export function symlinkEntryKind(fullPath) {
|
|
35
|
+
const stat = safeStat(fullPath);
|
|
36
|
+
if (stat?.isDirectory() ?? false) {
|
|
37
|
+
return "directory";
|
|
38
|
+
}
|
|
39
|
+
if (stat?.isFile() ?? false) {
|
|
40
|
+
return "file";
|
|
41
|
+
}
|
|
42
|
+
return "other";
|
|
43
|
+
}
|
|
44
|
+
export function classifyDirEntry(entry, fullPath) {
|
|
45
|
+
if (entry.isSymbolicLink()) {
|
|
46
|
+
return symlinkEntryKind(fullPath);
|
|
47
|
+
}
|
|
48
|
+
if (entry.isDirectory()) {
|
|
49
|
+
return "directory";
|
|
50
|
+
}
|
|
51
|
+
if (entry.isFile()) {
|
|
52
|
+
return "file";
|
|
53
|
+
}
|
|
54
|
+
return "other";
|
|
55
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Graph } from "./graph.js";
|
|
2
|
+
export declare function isEntryFile(filePath: string): boolean;
|
|
3
|
+
export declare const getGates: ((graph: Graph) => ReadonlyMap<string, string>) & {
|
|
4
|
+
prime: (graph: Graph, value: ReadonlyMap<string, string>) => void;
|
|
5
|
+
};
|
|
6
|
+
export interface CrossedGate {
|
|
7
|
+
dir: string;
|
|
8
|
+
entry: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function findCrossedGate(target: string, importer: string, graph: Graph, rootDir: string): CrossedGate | undefined;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { derivedFromGraph } from "./derived.js";
|
|
3
|
+
import { isInsideDir } from "./paths.js";
|
|
4
|
+
export function isEntryFile(filePath) {
|
|
5
|
+
const base = path.basename(filePath, path.extname(filePath));
|
|
6
|
+
return base === "index" || base === path.basename(path.dirname(filePath));
|
|
7
|
+
}
|
|
8
|
+
export const getGates = derivedFromGraph((graph) => {
|
|
9
|
+
const gates = new Map();
|
|
10
|
+
for (const file of graph.files) {
|
|
11
|
+
if (!isEntryFile(file)) {
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
const dir = path.dirname(file);
|
|
15
|
+
const isIndex = path.basename(file, path.extname(file)) === "index";
|
|
16
|
+
const existing = gates.get(dir);
|
|
17
|
+
const existingIsIndex = existing !== undefined &&
|
|
18
|
+
path.basename(existing, path.extname(existing)) === "index";
|
|
19
|
+
if (existing === undefined || (isIndex && !existingIsIndex)) {
|
|
20
|
+
gates.set(dir, file);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return gates;
|
|
24
|
+
});
|
|
25
|
+
export function findCrossedGate(target, importer, graph, rootDir) {
|
|
26
|
+
if (isEntryFile(target)) {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
const gates = getGates(graph);
|
|
30
|
+
let dir = path.dirname(target);
|
|
31
|
+
while (true) {
|
|
32
|
+
const entry = gates.get(dir);
|
|
33
|
+
if (entry !== undefined && !isInsideDir(importer, dir)) {
|
|
34
|
+
return { dir, entry };
|
|
35
|
+
}
|
|
36
|
+
if (dir === rootDir) {
|
|
37
|
+
break;
|
|
38
|
+
}
|
|
39
|
+
const parent = path.dirname(dir);
|
|
40
|
+
if (parent === dir) {
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
dir = parent;
|
|
44
|
+
}
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type Graph } from "./graph.js";
|
|
2
|
+
export type VisitToken = object;
|
|
3
|
+
export declare const REVALIDATE_AFTER_MS = 100;
|
|
4
|
+
export declare function stampIsAmbiguous(mtimeMs: number, builtAt: number, coarseTimestamps: boolean, stampedAt: number): boolean;
|
|
5
|
+
export declare function getGraph(rootDir: string, ignoreGlobs: string[], currentFile: string, visitToken?: VisitToken): Graph;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { safeRealpath, safeStat } from "./fs-safe.js";
|
|
3
|
+
import { buildGraphFromFiles } from "./graph.js";
|
|
4
|
+
import { findTsconfig } from "./resolve.js";
|
|
5
|
+
import { isInGraphScope, isSourceFile } from "./scope.js";
|
|
6
|
+
import { collectSourceFiles } from "./walk.js";
|
|
7
|
+
export const REVALIDATE_AFTER_MS = 100;
|
|
8
|
+
let cache;
|
|
9
|
+
function cacheKey(rootDir, ignoreGlobs) {
|
|
10
|
+
return rootDir + "\0" + ignoreGlobs.join("\0");
|
|
11
|
+
}
|
|
12
|
+
function stampFiles(files) {
|
|
13
|
+
const stamps = new Map();
|
|
14
|
+
for (const file of files) {
|
|
15
|
+
const stat = safeStat(file);
|
|
16
|
+
if (stat !== undefined) {
|
|
17
|
+
stamps.set(file, {
|
|
18
|
+
mtimeMs: stat.mtimeMs,
|
|
19
|
+
ctimeMs: stat.ctimeMs,
|
|
20
|
+
size: stat.size,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return stamps;
|
|
25
|
+
}
|
|
26
|
+
function hasCoarseTimestamps(stamps) {
|
|
27
|
+
if (stamps.size === 0) {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
return [...stamps.values()].every((stamp) => stamp.mtimeMs % 1000 === 0);
|
|
31
|
+
}
|
|
32
|
+
function stampConfigs(configPaths) {
|
|
33
|
+
const stamps = [];
|
|
34
|
+
for (const configPath of configPaths) {
|
|
35
|
+
const stat = safeStat(configPath);
|
|
36
|
+
stamps.push({ path: configPath, mtimeMs: stat?.mtimeMs ?? 0 });
|
|
37
|
+
}
|
|
38
|
+
return stamps;
|
|
39
|
+
}
|
|
40
|
+
export function stampIsAmbiguous(mtimeMs, builtAt, coarseTimestamps, stampedAt) {
|
|
41
|
+
if (!coarseTimestamps) {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
const buildSecond = Math.floor(builtAt / 1000) * 1000;
|
|
45
|
+
const stampedSecond = Math.floor(stampedAt / 1000) * 1000 + 1000;
|
|
46
|
+
return mtimeMs >= buildSecond && mtimeMs < stampedSecond;
|
|
47
|
+
}
|
|
48
|
+
function tsconfigNeedsRebuild(snapshot, rootDir) {
|
|
49
|
+
const currentPath = findTsconfig(safeRealpath(rootDir) ?? rootDir);
|
|
50
|
+
const previousPath = snapshot.configs[0]?.path;
|
|
51
|
+
if (currentPath !== previousPath) {
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
return snapshot.configs.some((stamp) => {
|
|
55
|
+
const stat = safeStat(stamp.path);
|
|
56
|
+
return (stat?.mtimeMs ?? 0) !== stamp.mtimeMs;
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
function trackedFilesChanged(snapshot) {
|
|
60
|
+
for (const [file, prev] of snapshot.stamps) {
|
|
61
|
+
const stat = safeStat(file);
|
|
62
|
+
if (stat === undefined ||
|
|
63
|
+
stat.mtimeMs !== prev.mtimeMs ||
|
|
64
|
+
stat.ctimeMs !== prev.ctimeMs ||
|
|
65
|
+
stat.size !== prev.size) {
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
if (stampIsAmbiguous(stat.mtimeMs, snapshot.builtAt, snapshot.coarseTimestamps, snapshot.stampedAt)) {
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
function isProductionGraphFile(currentFile, rootDir, ignoreGlobs) {
|
|
75
|
+
const realRoot = safeRealpath(rootDir);
|
|
76
|
+
if (realRoot === undefined || !isSourceFile(currentFile)) {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
return isInGraphScope(path.relative(realRoot, currentFile), ignoreGlobs);
|
|
80
|
+
}
|
|
81
|
+
function isSameVisit(pass, currentFile, visitToken) {
|
|
82
|
+
return (visitToken !== undefined &&
|
|
83
|
+
pass.lastFile === currentFile &&
|
|
84
|
+
pass.lastToken?.deref() === visitToken);
|
|
85
|
+
}
|
|
86
|
+
function isFresh(entry, currentFile, visitToken, rootDir, ignoreGlobs) {
|
|
87
|
+
const { snapshot, pass } = entry;
|
|
88
|
+
const now = Date.now();
|
|
89
|
+
const sameVisit = isSameVisit(pass, currentFile, visitToken);
|
|
90
|
+
const idle = now - pass.lastVisitAt >= REVALIDATE_AFTER_MS;
|
|
91
|
+
if (sameVisit && !idle) {
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
if (tsconfigNeedsRebuild(snapshot, rootDir)) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
const newPass = !sameVisit && (pass.visited.has(currentFile) || idle);
|
|
98
|
+
if (newPass) {
|
|
99
|
+
pass.visited.clear();
|
|
100
|
+
}
|
|
101
|
+
if ((newPass || sameVisit) && trackedFilesChanged(snapshot)) {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
pass.lastVisitAt = Date.now();
|
|
105
|
+
pass.visited.add(currentFile);
|
|
106
|
+
if (snapshot.stamps.has(currentFile)) {
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
return !isProductionGraphFile(currentFile, rootDir, ignoreGlobs);
|
|
110
|
+
}
|
|
111
|
+
function markVisit(pass, currentFile, visitToken) {
|
|
112
|
+
pass.lastFile = currentFile;
|
|
113
|
+
pass.lastToken =
|
|
114
|
+
visitToken === undefined ? undefined : new WeakRef(visitToken);
|
|
115
|
+
}
|
|
116
|
+
export function getGraph(rootDir, ignoreGlobs, currentFile, visitToken) {
|
|
117
|
+
const key = cacheKey(rootDir, ignoreGlobs);
|
|
118
|
+
if (cache !== undefined &&
|
|
119
|
+
cache.key === key &&
|
|
120
|
+
isFresh(cache.entry, currentFile, visitToken, rootDir, ignoreGlobs)) {
|
|
121
|
+
markVisit(cache.entry.pass, currentFile, visitToken);
|
|
122
|
+
return cache.entry.snapshot.graph;
|
|
123
|
+
}
|
|
124
|
+
const builtAt = Date.now();
|
|
125
|
+
const resolvedRoot = safeRealpath(rootDir);
|
|
126
|
+
let graph;
|
|
127
|
+
let configPaths;
|
|
128
|
+
let stamps;
|
|
129
|
+
if (resolvedRoot === undefined) {
|
|
130
|
+
graph = { importers: new Map(), files: [] };
|
|
131
|
+
configPaths = [];
|
|
132
|
+
stamps = new Map();
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
const { files, dirStamps } = collectSourceFiles(resolvedRoot, ignoreGlobs);
|
|
136
|
+
stamps = stampFiles(files);
|
|
137
|
+
for (const [dir, stamp] of dirStamps) {
|
|
138
|
+
stamps.set(dir, stamp);
|
|
139
|
+
}
|
|
140
|
+
({ graph, configPaths } = buildGraphFromFiles(files, resolvedRoot));
|
|
141
|
+
}
|
|
142
|
+
const stampedAt = Date.now();
|
|
143
|
+
const entry = {
|
|
144
|
+
snapshot: {
|
|
145
|
+
graph,
|
|
146
|
+
stamps,
|
|
147
|
+
configs: stampConfigs(configPaths),
|
|
148
|
+
builtAt,
|
|
149
|
+
stampedAt,
|
|
150
|
+
coarseTimestamps: hasCoarseTimestamps(stamps),
|
|
151
|
+
},
|
|
152
|
+
pass: {
|
|
153
|
+
visited: new Set([currentFile]),
|
|
154
|
+
lastFile: undefined,
|
|
155
|
+
lastToken: undefined,
|
|
156
|
+
lastVisitAt: stampedAt,
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
cache = { key, entry };
|
|
160
|
+
markVisit(entry.pass, currentFile, visitToken);
|
|
161
|
+
return graph;
|
|
162
|
+
}
|