@md-code/follow-architecture 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.
- package/README.md +168 -0
- package/ast.js +107 -0
- package/bin/follow-architecture.js +6 -0
- package/config.js +82 -0
- package/entities/aliases.js +10 -0
- package/entities/invariants.js +134 -0
- package/entities/nodes.js +112 -0
- package/main.js +95 -0
- package/package.json +49 -0
- package/report.js +73 -0
- package/utils.js +104 -0
package/README.md
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
# follow-architecture
|
|
2
|
+
|
|
3
|
+
ESLint rule + CLI that validates code against a declarative architecture skeleton. The tool knows nothing about your project — everything (paths, names, rules, fixes) lives in `architecture.json`.
|
|
4
|
+
|
|
5
|
+
Two kinds of checks:
|
|
6
|
+
|
|
7
|
+
- **nodes** — where files may live and what names they may have (a folder tree with closed/open lists and per-name reports).
|
|
8
|
+
- **invariants** — per-file content rules: forbidden text, forbidden imports, and conditional checks driven by the file's AST.
|
|
9
|
+
|
|
10
|
+
## `architecture.json`
|
|
11
|
+
|
|
12
|
+
```jsonc
|
|
13
|
+
{
|
|
14
|
+
"aliases": { "#_db": "core/ehr/_db" },
|
|
15
|
+
"nodes": [
|
|
16
|
+
{
|
|
17
|
+
"slug": "slice",
|
|
18
|
+
"name": "{slice}.v",
|
|
19
|
+
"parent": "ehr",
|
|
20
|
+
"closed": true,
|
|
21
|
+
"report": { "message": "…", "fix": "…" },
|
|
22
|
+
"children": [
|
|
23
|
+
"{kebab-case}.types.ts",
|
|
24
|
+
"index.ts",
|
|
25
|
+
{ "name": "{kebab-case}.resource.tsx", "forbidden": true, "report": { "message": "…", "fix": "…" } }
|
|
26
|
+
]
|
|
27
|
+
},
|
|
28
|
+
{ "slug": "ehr", "name": "core/ehr", "children": ["slice", "db"] }
|
|
29
|
+
],
|
|
30
|
+
"invariants": [
|
|
31
|
+
{
|
|
32
|
+
"id": "rm-no-bypass",
|
|
33
|
+
"where": "core/ehr/{slice}.v/**/*.rm.ts",
|
|
34
|
+
"forbid": [
|
|
35
|
+
{ "key": "client", "pattern": "new AppMedplumClient", "report": { "message": "…", "fix": "…" }, "except": ["**/legacy/**"] },
|
|
36
|
+
{ "type": "imports", "key": "no-vscode", "pattern": "vscode", "report": { "message": "…" } }
|
|
37
|
+
],
|
|
38
|
+
"when": "(ctx) => { /* AST-level check, returns null | true | finding | finding[] */ }",
|
|
39
|
+
"except": ["core/ehr/catalog.v/**/*.rm.ts"],
|
|
40
|
+
"report": { "message": "…", "fix": "…" }
|
|
41
|
+
}
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Top-level options: `files` (globs scanned by the CLI, default `**/*.ts`, `**/*.tsx`), `exts` (default `.ts`, `.tsx`, `.js`, `.jsx`), `ignores` (file globs skipped by the CLI).
|
|
47
|
+
|
|
48
|
+
## Nodes
|
|
49
|
+
|
|
50
|
+
A **node** is a folder (or folder prefix) in the tree. Nodes reference each other by `slug` to form the tree; the path of a node is its `parent`'s path + its `name`.
|
|
51
|
+
|
|
52
|
+
- `slug` — unique name, used as `parent` by children and as `node` by invariants.
|
|
53
|
+
- `name` — the path segment (relative to the parent). `{name}` placeholders capture path segments (e.g. `{slice}` in `{slice}.v` captures `allergies`). Captures are available in reports of every finding inside the node.
|
|
54
|
+
- `parent` (optional) — the `slug` of the containing node. A node without `parent` is a root.
|
|
55
|
+
- `closed` (optional, default `false`) — when `true`, a file directly inside the node must match one of its `children`; otherwise it gets the node's `report`. A folder (a child that is a folder) that is not in the list is also a violation.
|
|
56
|
+
- `report` (optional) — the finding for "file does not belong here" (closed nodes) — see [report](#report).
|
|
57
|
+
- `children` (optional) — the list of allowed names inside the node. Each entry is either:
|
|
58
|
+
- a **string** — a name template (`{kebab-case}`, `*`, `?` work; a name without an extension is a folder, with an extension is a file);
|
|
59
|
+
- an **object** — `{ name, forbidden?, report?, description? }`. `forbidden: true` names a shape that must **never** exist (e.g. `{kebab-case}.resource.tsx` in a sub-feature folder) and reports `report` when it does.
|
|
60
|
+
|
|
61
|
+
A node with no `children` is **open** — anything inside is fine. The deepest matching node wins: a file is checked against the most specific node whose path prefix matches.
|
|
62
|
+
|
|
63
|
+
## Invariants
|
|
64
|
+
|
|
65
|
+
An **invariant** is a per-file rule. Fields:
|
|
66
|
+
|
|
67
|
+
- `id` — unique name.
|
|
68
|
+
- `node` (optional) — a node `slug`; the invariant only runs for files that captured that node. Default `*` (all files).
|
|
69
|
+
- `where` (optional) — a glob the file path must match; `{name}` captures work and are available in reports. No `where` = all files.
|
|
70
|
+
- `except` (optional) — file globs the invariant does not apply to.
|
|
71
|
+
- `report` (optional) — a finding emitted for **every** matching file (a "this file, as it exists, is a problem" rule).
|
|
72
|
+
- `when` (optional) — a gate or an AST-level check, called as `when(ctx)` with the full file context (see [ctx](#ctx)). Return values:
|
|
73
|
+
- `null` / `false` — the invariant (and its `forbid` list) is off for this file;
|
|
74
|
+
- `true` — on;
|
|
75
|
+
- an object or array of objects — emitted as finding(s) and the `forbid` list is skipped.
|
|
76
|
+
- `forbid` (optional) — array of entries, each with a `type`:
|
|
77
|
+
- `type: "fileContent"` (default) — `{ key?, pattern, except?, report? }`. `pattern` is a **regex** tested against every line of the file; every matching line is a finding. `except` is a list of file globs where this entry does not apply.
|
|
78
|
+
- `type: "imports"` — `{ key?, pattern, except?, report? }`. `pattern` is a **glob** (with `{name}` captures) tested against each import's **resolved path** — or the raw source for external modules that cannot be resolved. Every matching import is a finding.
|
|
79
|
+
- `type: "syntax"` — `{ key?, kind, pattern?, except?, report? }`. `kind` is a ts-morph node kind name (e.g. `ImportDeclaration`, `FunctionDeclaration`, `VariableStatement`); every AST node of that kind is a finding, optionally narrowed by `pattern` (a regex tested against the node's full text). Use it when a line-based regex cannot express the rule (e.g. "no `export default`", "no function declarations").
|
|
80
|
+
- `children` (optional) — nested invariants; they run after the parent and inherit its captures.
|
|
81
|
+
|
|
82
|
+
`key` (on the invariant or a `forbid` entry) is a stable dedup key: findings with the same `key` are collapsed to one per file.
|
|
83
|
+
|
|
84
|
+
### `ctx`
|
|
85
|
+
|
|
86
|
+
`when(ctx)` receives, per file:
|
|
87
|
+
|
|
88
|
+
| field | meaning |
|
|
89
|
+
| --- | --- |
|
|
90
|
+
| `ctx.file` | the full ts-morph `SourceFile` — the whole AST is available (`getImportDeclarations`, `getFunctions`, `getDescendantsOfKind`, …) |
|
|
91
|
+
| `ctx.path` | repo-relative path (posix) |
|
|
92
|
+
| `ctx.basename` | file name |
|
|
93
|
+
| `ctx.dir` | directory (repo-relative) |
|
|
94
|
+
| `ctx.slice` | the `{slice}` capture if the path matches `…/<slice>.v/…`, else `null` |
|
|
95
|
+
| `ctx.captures` | all `{name}` captures from the invariant's `where` and the matched node |
|
|
96
|
+
| `ctx.imports` | the file's import declarations: `{ source, named, defaultName, namespaceName, typeOnly, resolved }` — `resolved` is the repo-relative path after alias expansion, `null` for external modules |
|
|
97
|
+
| `ctx.siblings` | basenames of the other files in the same folder (the folder listing the CLI walked) — for rules like "at most N files per folder" or "no duplicated basename prefixes" |
|
|
98
|
+
| `ctx.arch` | the loaded architecture (nodes, invariants, aliases) |
|
|
99
|
+
| `ctx.enclosingFunctionName(line)` | name of the function containing the 1-based `line`, or `null` |
|
|
100
|
+
|
|
101
|
+
`when` may be a function (in a `.js` config) or a string — either a full function body (`"(ctx) => …"` / `"function(ctx) { … }"`) or an expression evaluated with `ctx` in scope — so it can live in JSON.
|
|
102
|
+
|
|
103
|
+
## report
|
|
104
|
+
|
|
105
|
+
`report` is a **field**, not a check. It is `null`, a string, a function `(vars) => string`, or `{ message, fix, level? }`. `message` is the finding text as the reader sees it; `fix` is the "instead do this" part. Both support multiline Markdown (fenced code blocks, lists, bold). The report prints them verbatim; the ESLint message is a single-line variant of `message`.
|
|
106
|
+
|
|
107
|
+
### Variables
|
|
108
|
+
|
|
109
|
+
`{name}` placeholders are substituted before the text is printed.
|
|
110
|
+
|
|
111
|
+
**From the file path** (every finding):
|
|
112
|
+
|
|
113
|
+
| variable | meaning |
|
|
114
|
+
| --- | --- |
|
|
115
|
+
| `{file}` | repo-relative path of the flagged file |
|
|
116
|
+
| `{basename}` | file name without directory |
|
|
117
|
+
| `{dir}` | directory of the file (repo-relative) |
|
|
118
|
+
|
|
119
|
+
**Captures** — any `{name}` used in a node `name`, invariant `where`, or `forbid` (imports) pattern. E.g. `{slice}` in `core/ehr/{slice}.v/**/*.rm.ts` captures `allergies` and is available as `{slice}` in that file's findings.
|
|
120
|
+
|
|
121
|
+
**Match context** (text-forbid findings only):
|
|
122
|
+
|
|
123
|
+
| variable | meaning |
|
|
124
|
+
| --- | --- |
|
|
125
|
+
| `{count}` | how many lines matched the pattern |
|
|
126
|
+
| `{plural}` | `""` if count is 1, `"s"` otherwise — for `time{plural}` |
|
|
127
|
+
| `{line}` | first matching line number |
|
|
128
|
+
| `{lines}` | all matching line numbers, comma-separated |
|
|
129
|
+
| `{snippet}` | the first matching line, trimmed |
|
|
130
|
+
| `{match}` | the exact matched text on the first line |
|
|
131
|
+
| `{where}` | ` in `functionName`` if the match is inside a named function, empty otherwise |
|
|
132
|
+
|
|
133
|
+
Without `report`, the tool composes a fallback from the rule's shape.
|
|
134
|
+
|
|
135
|
+
## Aliases
|
|
136
|
+
|
|
137
|
+
`aliases` maps import specifiers to paths for import resolution (e.g. `"#_db": "core/ehr/_db"`). Used by `type: "imports"` forbid entries and by `ctx.imports[].resolved`.
|
|
138
|
+
|
|
139
|
+
## CLI
|
|
140
|
+
|
|
141
|
+
```sh
|
|
142
|
+
node follow-architecture/bin/follow-architecture.js [options]
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
| flag | default | meaning |
|
|
146
|
+
| --- | --- | --- |
|
|
147
|
+
| `[cwd]` | `.` | repo root (positional) |
|
|
148
|
+
| `--config <path>` | `architecture.json` / `architecture.config.js` found by walking up | architecture JSON or JS module |
|
|
149
|
+
| `--out <path>` | print to stdout | report output |
|
|
150
|
+
| `--ignore <glob>` | — | extra file globs to skip (repeatable) |
|
|
151
|
+
| `--check` | off | exit 1 if there are findings |
|
|
152
|
+
|
|
153
|
+
The report (`--out`) groups findings by file and prints each finding as the full `message` followed by a **Fix.** section with the `fix` text.
|
|
154
|
+
|
|
155
|
+
## ESLint
|
|
156
|
+
|
|
157
|
+
The package exports a `flatConfig` factory:
|
|
158
|
+
|
|
159
|
+
```js
|
|
160
|
+
// eslint.config.js
|
|
161
|
+
const { flatConfig } = require("./follow-architecture/config.js");
|
|
162
|
+
|
|
163
|
+
module.exports = flatConfig(require("./architecture.json"), {
|
|
164
|
+
files: ["core/ehr/**/*.ts", "core/ehr/**/*.tsx"],
|
|
165
|
+
});
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`flatConfig(architecture, { parser, files, ignores })` returns a flat-config array. `architecture` is the object (or `{ file: "architecture.json" }` — it is resolved lazily per file so the repo root is found from the file being linted). `parser` defaults to `@typescript-eslint/parser`. The rule is `md-code/follow-architecture`.
|
package/ast.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const { Project, ts } = require("ts-morph");
|
|
6
|
+
const { pipe, filter, map } = require("remeda");
|
|
7
|
+
|
|
8
|
+
const norm = (p) => String(p).replace(/\\/g, "/");
|
|
9
|
+
|
|
10
|
+
const toRel = (repoRoot, filePath) => norm(path.relative(repoRoot, filePath));
|
|
11
|
+
|
|
12
|
+
const createTsProject = () =>
|
|
13
|
+
new Project({
|
|
14
|
+
useInMemoryFileSystem: true,
|
|
15
|
+
skipAddingFilesFromTsConfig: true,
|
|
16
|
+
compilerOptions: {
|
|
17
|
+
allowJs: true,
|
|
18
|
+
jsx: ts.JsxEmit.Preserve,
|
|
19
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
20
|
+
module: ts.ModuleKind.ESNext,
|
|
21
|
+
target: ts.ScriptTarget.ESNext,
|
|
22
|
+
esModuleInterop: true,
|
|
23
|
+
skipLibCheck: true,
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const importEntry = (imp) => {
|
|
28
|
+
const source = imp.getModuleSpecifierValue();
|
|
29
|
+
const entry = { source, named: [], defaultName: null, namespaceName: null, typeOnly: imp.isTypeOnly() };
|
|
30
|
+
for (const el of imp.getNamedImports()) entry.named.push(el.getName());
|
|
31
|
+
const def = imp.getDefaultImport();
|
|
32
|
+
if (def) entry.defaultName = def.getText();
|
|
33
|
+
const ns = imp.getNamespaceImport();
|
|
34
|
+
if (ns) entry.namespaceName = ns.getText();
|
|
35
|
+
return entry;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const resolveImport = (sf, source, repoRoot, aliases) => {
|
|
39
|
+
const tryFile = (rel) => {
|
|
40
|
+
if (!rel) return null;
|
|
41
|
+
const abs = path.resolve(repoRoot, rel);
|
|
42
|
+
if (fs.existsSync(abs) && fs.statSync(abs).isFile()) return rel;
|
|
43
|
+
return null;
|
|
44
|
+
};
|
|
45
|
+
const candidates = (rel) => [rel, `${rel}.ts`, `${rel}.tsx`, `${rel}.js`, `${rel}.jsx`, `${rel}/index.ts`, `${rel}/index.tsx`, `${rel}/index.js`];
|
|
46
|
+
const resolveBase = (base) => pipe(candidates(base), map(tryFile), filter(Boolean), (r) => (r.length ? r[0] : null));
|
|
47
|
+
const alias = Object.keys(aliases).find((a) => source === a || source.startsWith(`${a}/`));
|
|
48
|
+
if (alias) return resolveBase(`${aliases[alias]}/${source.slice(alias.length).replace(/^\//, "")}`);
|
|
49
|
+
return resolveBase(toRel(repoRoot, path.resolve(path.dirname(sf.getFilePath()), source)));
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const sliceOf = (relPath) => {
|
|
53
|
+
const m = relPath.replace(/\\/g, "/").match(/\/([^/]+)\.v(\/|$)/);
|
|
54
|
+
return m ? m[1] : null;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const enclosingFunctionName = (sf, line) => {
|
|
58
|
+
let node = sf;
|
|
59
|
+
try {
|
|
60
|
+
const pos = sf.getPositionAtLineAndCharacter(line, 0);
|
|
61
|
+
node = sf.getDescendantAtPosition(pos, (n) => n.getStart() <= pos && n.getEnd() >= pos);
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
let cur = node;
|
|
66
|
+
while (cur) {
|
|
67
|
+
if (cur.isFunctionDeclaration() && cur.getName()) return cur.getName();
|
|
68
|
+
if (cur.isMethodDeclaration()) {
|
|
69
|
+
const n = cur.getName();
|
|
70
|
+
if (n) return n;
|
|
71
|
+
}
|
|
72
|
+
if (cur.isFunctionExpression() || cur.isArrowFunction()) {
|
|
73
|
+
const p = cur.getParent();
|
|
74
|
+
if (p && (p.isVariableDeclaration() || p.isPropertyAssignment() || p.isPropertyDeclaration() || p.isMethodDeclaration())) {
|
|
75
|
+
const n = p.getName();
|
|
76
|
+
if (n) return n;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
cur = cur.getParent();
|
|
80
|
+
}
|
|
81
|
+
return null;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const buildContext = (project, filePath, text, repoRoot, aliases, siblings = []) => {
|
|
85
|
+
const sf = project.createSourceFile(filePath, text, { overwrite: true });
|
|
86
|
+
const relPath = toRel(repoRoot, filePath);
|
|
87
|
+
const imports = pipe(
|
|
88
|
+
sf.getImportDeclarations(),
|
|
89
|
+
map((imp) => {
|
|
90
|
+
const entry = importEntry(imp);
|
|
91
|
+
return { ...entry, resolved: resolveImport(sf, entry.source, repoRoot, aliases) };
|
|
92
|
+
}),
|
|
93
|
+
);
|
|
94
|
+
return {
|
|
95
|
+
file: sf,
|
|
96
|
+
path: relPath,
|
|
97
|
+
basename: path.posix.basename(relPath),
|
|
98
|
+
dir: path.posix.dirname(relPath),
|
|
99
|
+
captures: {},
|
|
100
|
+
imports,
|
|
101
|
+
slice: sliceOf(relPath),
|
|
102
|
+
siblings,
|
|
103
|
+
enclosingFunctionName: (line) => enclosingFunctionName(sf, line),
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
module.exports = { createTsProject, buildContext, toRel };
|
package/config.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const { buildArchitecture } = require("./main");
|
|
6
|
+
const { checkFile } = require("./utils");
|
|
7
|
+
const { createTsProject } = require("./ast");
|
|
8
|
+
const pkg = require("./package.json");
|
|
9
|
+
|
|
10
|
+
const findRepoRoot = (from) => {
|
|
11
|
+
let dir = from;
|
|
12
|
+
while (true) {
|
|
13
|
+
for (const name of ["architecture.json", "architecture.config.js"]) {
|
|
14
|
+
if (fs.existsSync(path.join(dir, name))) return dir;
|
|
15
|
+
}
|
|
16
|
+
const parent = path.dirname(dir);
|
|
17
|
+
if (parent === dir) return from;
|
|
18
|
+
dir = parent;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const rule = {
|
|
23
|
+
meta: {
|
|
24
|
+
type: "problem",
|
|
25
|
+
docs: { description: "Enforces the vertical-slice architecture defined in architecture.json" },
|
|
26
|
+
schema: [{ type: "object" }],
|
|
27
|
+
},
|
|
28
|
+
create(context) {
|
|
29
|
+
const arch = buildArchitecture(context.options[0] ?? {});
|
|
30
|
+
const filePath = context.filename ?? context.getFilename();
|
|
31
|
+
const repoRoot = findRepoRoot(path.dirname(filePath));
|
|
32
|
+
const project = createTsProject();
|
|
33
|
+
const findings = checkFile(filePath, fs.readFileSync(filePath, "utf8"), repoRoot, arch, project);
|
|
34
|
+
for (const f of findings) {
|
|
35
|
+
context.report({
|
|
36
|
+
message: f.message,
|
|
37
|
+
loc: { start: { line: f.pos.line, column: f.pos.column - 1 }, end: { line: f.pos.line, column: f.pos.column } },
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return {};
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const plugin = {
|
|
45
|
+
meta: { name: pkg.name, version: pkg.version },
|
|
46
|
+
rules: { "follow-architecture": rule },
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const flatConfig = (architecture, opts = {}) => {
|
|
50
|
+
const { parser, files, ignores, plugins } = opts;
|
|
51
|
+
const list = [];
|
|
52
|
+
if (ignores?.length) list.push({ ignores });
|
|
53
|
+
list.push({
|
|
54
|
+
files: files ?? architecture.files,
|
|
55
|
+
languageOptions: {
|
|
56
|
+
parser: parser ?? require("@typescript-eslint/parser"),
|
|
57
|
+
parserOptions: { ecmaVersion: "latest", sourceType: "module" },
|
|
58
|
+
},
|
|
59
|
+
linterOptions: { reportUnusedDisableDirectives: "off" },
|
|
60
|
+
plugins: plugins ?? { "md-code": plugin },
|
|
61
|
+
rules: { "md-code/follow-architecture": ["error", architecture.raw ?? architecture] },
|
|
62
|
+
});
|
|
63
|
+
return list;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const parseArgs = (argv) => {
|
|
67
|
+
const args = { config: null, ignore: [], out: null, check: false, help: false, cwd: null };
|
|
68
|
+
const rest = [];
|
|
69
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
70
|
+
const a = argv[i];
|
|
71
|
+
if (a === "--config" || a === "-c") args.config = argv[++i];
|
|
72
|
+
else if (a === "--ignore") args.ignore.push(argv[++i]);
|
|
73
|
+
else if (a === "--out" || a === "-o") args.out = argv[++i];
|
|
74
|
+
else if (a === "--check") args.check = true;
|
|
75
|
+
else if (a === "--help" || a === "-h") args.help = true;
|
|
76
|
+
else rest.push(a);
|
|
77
|
+
}
|
|
78
|
+
if (rest.length) args.cwd = rest[0];
|
|
79
|
+
return args;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
module.exports = { flatConfig, parseArgs, plugin };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { pipe, map, entries } = require("remeda");
|
|
4
|
+
|
|
5
|
+
const normalizeAliases = (raw) => {
|
|
6
|
+
const entriesRaw = raw && typeof raw === "object" ? raw : {};
|
|
7
|
+
return pipe(entries(entriesRaw), map(([k, v]) => [String(k), String(v).replace(/\\/g, "/").replace(/\/+$/, "")]));
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
module.exports = { normalizeAliases };
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { pipe, map, filter, unique } = require("remeda");
|
|
4
|
+
const { minimatch } = require("minimatch");
|
|
5
|
+
const { asReport, compilePattern, compileWhen, checkRegex } = require("../utils");
|
|
6
|
+
|
|
7
|
+
const FORBID_TYPES = ["fileContent", "imports", "syntax"];
|
|
8
|
+
|
|
9
|
+
const normalizeInvariant = (i, slugs) => {
|
|
10
|
+
if (!i || typeof i !== "object") throw new Error("architecture.invariants: entry is not an object");
|
|
11
|
+
if (!i.id) throw new Error("architecture.invariants: entry without id");
|
|
12
|
+
if (i.node && i.node !== "*" && !slugs.includes(i.node)) throw new Error(`invariant ${i.id}: unknown node \`${i.node}\``);
|
|
13
|
+
const contentSpec = (p) => {
|
|
14
|
+
checkRegex(p.pattern, `invariant ${i.id}: forbid`);
|
|
15
|
+
return { type: "fileContent", key: p.key ?? null, pattern: p.pattern, except: p.except ?? [], report: asReport(p.report) };
|
|
16
|
+
};
|
|
17
|
+
const syntaxSpec = (p) => {
|
|
18
|
+
if (!p.kind) throw new Error(`invariant ${i.id}: forbid syntax entry requires \`kind\``);
|
|
19
|
+
if (p.pattern != null) checkRegex(p.pattern, `invariant ${i.id}: forbid syntax`);
|
|
20
|
+
return { type: "syntax", key: p.key ?? null, kind: p.kind, pattern: p.pattern ?? null, except: p.except ?? [], report: asReport(p.report) };
|
|
21
|
+
};
|
|
22
|
+
const importsSpec = (p) => {
|
|
23
|
+
const { re, names } = compilePattern(p.pattern);
|
|
24
|
+
return { type: "imports", key: p.key ?? null, pattern: p.pattern, re, names, except: p.except ?? [], report: asReport(p.report) };
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
id: i.id,
|
|
28
|
+
key: i.key ?? null,
|
|
29
|
+
node: i.node ?? "*",
|
|
30
|
+
where: i.where == null ? null : (() => {
|
|
31
|
+
const { re, names } = compilePattern(i.where);
|
|
32
|
+
return { re, names, pattern: i.where };
|
|
33
|
+
})(),
|
|
34
|
+
when: compileWhen(i.when),
|
|
35
|
+
except: i.except ?? [],
|
|
36
|
+
report: asReport(i.report),
|
|
37
|
+
forbid: [
|
|
38
|
+
...pipe(i.forbid ?? [], map((f) => {
|
|
39
|
+
const type = f.type ?? "fileContent";
|
|
40
|
+
if (!FORBID_TYPES.includes(type)) throw new Error(`invariant ${i.id}: forbid entry has unknown type \`${type}\` (expected ${FORBID_TYPES.join(" | ")})`);
|
|
41
|
+
return type === "imports" ? importsSpec(f) : type === "syntax" ? syntaxSpec(f) : contentSpec(f);
|
|
42
|
+
})),
|
|
43
|
+
...pipe(i.must ?? [], map(importsSpec)),
|
|
44
|
+
],
|
|
45
|
+
children: pipe(i.children ?? [], map((c) => normalizeInvariant(c, slugs))),
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const matchNode = (inv, ctx) => inv.node === "*" || !!ctx.captures[inv.node];
|
|
50
|
+
|
|
51
|
+
const matchWhere = (inv, ctx) => !inv.where || inv.where.re.test(ctx.path);
|
|
52
|
+
|
|
53
|
+
const fileVars = (ctx) => ({ slice: ctx.slice, path: ctx.path, dir: ctx.dir, basename: ctx.basename, ...ctx.captures });
|
|
54
|
+
|
|
55
|
+
const runWhen = (inv, ctx, baseCaps, out, findingFrom) => {
|
|
56
|
+
if (!inv.when) return true;
|
|
57
|
+
const res = inv.when(ctx);
|
|
58
|
+
if (res == null || res === false) return false;
|
|
59
|
+
if (res === true) return true;
|
|
60
|
+
if (Array.isArray(res)) {
|
|
61
|
+
for (const f of res) out.push(findingFrom(f, inv.key ?? inv.id, inv.node, `when:${inv.id}`, { ...baseCaps }));
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
out.push(findingFrom(res, inv.key ?? inv.id, inv.node, `when:${inv.id}`, { ...baseCaps }));
|
|
65
|
+
return true;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const checkForbidImports = (f, ctx, baseCaps, inv, out, findingFrom) => {
|
|
69
|
+
const hits = pipe(ctx.imports, filter((imp) => {
|
|
70
|
+
const target = imp.resolved ?? imp.source;
|
|
71
|
+
return target != null && f.re.test(target);
|
|
72
|
+
}), map((imp) => ({ imp, caps: f.re.exec(imp.resolved ?? imp.source) })));
|
|
73
|
+
for (const { imp, caps } of hits) {
|
|
74
|
+
out.push(findingFrom({ key: f.key ?? "forbid", message: `import \`${imp.source}\` is not allowed here`, fix: null, pattern: imp.source, report: f.report }, inv.key ?? inv.id, inv.node, `forbid:${inv.id}`, { ...baseCaps, ...Object.fromEntries((caps ?? []).map((v, idx) => [idx, v])) }));
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const checkForbidContent = (f, ctx, baseCaps, inv, out, findingFrom) => {
|
|
79
|
+
const lines = ctx.file.getFullText().split("\n");
|
|
80
|
+
const hits = [];
|
|
81
|
+
lines.forEach((line, i) => {
|
|
82
|
+
const m = new RegExp(f.pattern).exec(line);
|
|
83
|
+
if (m) hits.push({ line: i + 1, snippet: line.trim(), match: m[0] });
|
|
84
|
+
});
|
|
85
|
+
for (const h of hits) {
|
|
86
|
+
const where = ctx.enclosingFunctionName(h.line) ? ` in \`${ctx.enclosingFunctionName(h.line)}\`` : "";
|
|
87
|
+
const vars = { ...baseCaps, line: h.line, lines: pipe(hits, map((x) => String(x.line)), unique(), (ls) => ls.join(", ")), count: hits.length, plural: hits.length > 1 ? "s" : "", snippet: h.snippet, match: h.match, where };
|
|
88
|
+
out.push(findingFrom({ key: f.key ?? "forbid", ...vars, report: f.report }, inv.key ?? inv.id, inv.node, `forbid:${inv.id}`, vars));
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const checkForbidSyntax = (f, ctx, baseCaps, inv, out, findingFrom) => {
|
|
93
|
+
const re = f.pattern == null ? null : new RegExp(f.pattern);
|
|
94
|
+
const hits = [];
|
|
95
|
+
const visit = (node) => {
|
|
96
|
+
if (node.getKindName() === f.kind) {
|
|
97
|
+
const text = node.getText();
|
|
98
|
+
const m = re == null ? text : re.exec(text);
|
|
99
|
+
if (m) {
|
|
100
|
+
const line = node.getStartLineNumber();
|
|
101
|
+
hits.push({ line, snippet: text.split("\n")[0].trim().slice(0, 120), match: m[0] });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
node.forEachChild(visit);
|
|
105
|
+
};
|
|
106
|
+
visit(ctx.file);
|
|
107
|
+
for (const h of hits) {
|
|
108
|
+
const where = ctx.enclosingFunctionName(h.line) ? ` in \`${ctx.enclosingFunctionName(h.line)}\`` : "";
|
|
109
|
+
const vars = { ...baseCaps, line: h.line, lines: pipe(hits, map((x) => String(x.line)), unique(), (ls) => ls.join(", ")), count: hits.length, plural: hits.length > 1 ? "s" : "", snippet: h.snippet, match: h.match, where };
|
|
110
|
+
out.push(findingFrom({ key: f.key ?? "forbid", ...vars, report: f.report }, inv.key ?? inv.id, inv.node, `forbid:${inv.id}`, vars));
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const checkForbid = (inv, ctx, baseCaps, out, findingFrom) => {
|
|
115
|
+
for (const f of inv.forbid) {
|
|
116
|
+
if (f.except.some((g) => minimatch(ctx.path, g))) continue;
|
|
117
|
+
if (f.type === "imports") checkForbidImports(f, ctx, baseCaps, inv, out, findingFrom);
|
|
118
|
+
else if (f.type === "syntax") checkForbidSyntax(f, ctx, baseCaps, inv, out, findingFrom);
|
|
119
|
+
else checkForbidContent(f, ctx, baseCaps, inv, out, findingFrom);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const checkInvariant = (inv, ctx, caps, out, findingFrom) => {
|
|
124
|
+
if (inv.except.some((g) => minimatch(ctx.path, g))) return;
|
|
125
|
+
if (!matchNode(inv, ctx)) return;
|
|
126
|
+
if (!matchWhere(inv, ctx)) return;
|
|
127
|
+
const baseCaps = { ...caps, ...fileVars(ctx) };
|
|
128
|
+
if (inv.report) out.push(findingFrom({ key: null, report: inv.report }, inv.key ?? inv.id, inv.node, `root:${inv.id}`, baseCaps));
|
|
129
|
+
const gated = runWhen(inv, ctx, baseCaps, out, findingFrom);
|
|
130
|
+
if (gated) checkForbid(inv, ctx, baseCaps, out, findingFrom);
|
|
131
|
+
for (const child of inv.children) checkInvariant(child, ctx, { ...caps, ...baseCaps }, out, findingFrom);
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
module.exports = { normalizeInvariant, checkInvariant };
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { pipe, map, filter, sort, flatMap, unique } = require("remeda");
|
|
4
|
+
const { asReport, nodePrefixRe, compileChild } = require("../utils");
|
|
5
|
+
|
|
6
|
+
const isFolderName = (name) => !/[^/]+\.[A-Za-z0-9]+$/.test(String(name).split("/").pop());
|
|
7
|
+
|
|
8
|
+
const normalizeChild = (c) => {
|
|
9
|
+
if (typeof c === "string") {
|
|
10
|
+
const { re, captures } = compileChild(c);
|
|
11
|
+
return { name: c, re, captures, folder: isFolderName(c), forbidden: false, report: null, description: null };
|
|
12
|
+
}
|
|
13
|
+
const { re, captures } = compileChild(c.name);
|
|
14
|
+
return { name: c.name, re, captures, folder: isFolderName(c.name), forbidden: !!c.forbidden, report: asReport(c.report), description: c.description == null ? null : String(c.description) };
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const buildTree = (rawNodes) => {
|
|
18
|
+
const list = Array.isArray(rawNodes) ? rawNodes : Object.values(rawNodes);
|
|
19
|
+
const bySlugRaw = Object.fromEntries(list.map((n) => [n.slug, n]));
|
|
20
|
+
const slugs = Object.keys(bySlugRaw);
|
|
21
|
+
if (new Set(slugs).size !== slugs.length) throw new Error("duplicate node slug in architecture.nodes");
|
|
22
|
+
const computePath = (slug, depth = 0) => {
|
|
23
|
+
const n = bySlugRaw[slug];
|
|
24
|
+
if (!n) throw new Error(`node ${slug}: unknown parent`);
|
|
25
|
+
if (depth > 10) throw new Error(`node ${slug}: parent chain too deep (cycle?)`);
|
|
26
|
+
if (!n.parent) return n.name;
|
|
27
|
+
const parent = computePath(n.parent, depth + 1);
|
|
28
|
+
return `${parent}/${n.name}`;
|
|
29
|
+
};
|
|
30
|
+
const make = (slug) => {
|
|
31
|
+
const n = bySlugRaw[slug];
|
|
32
|
+
const path = computePath(slug);
|
|
33
|
+
const { re, names } = nodePrefixRe(path);
|
|
34
|
+
return {
|
|
35
|
+
slug,
|
|
36
|
+
name: n.name,
|
|
37
|
+
parent: n.parent ?? null,
|
|
38
|
+
path,
|
|
39
|
+
prefixRe: re,
|
|
40
|
+
prefixNames: names,
|
|
41
|
+
closed: !!n.closed,
|
|
42
|
+
description: n.description == null ? null : String(n.description),
|
|
43
|
+
report: asReport(n.report),
|
|
44
|
+
children: pipe(n.children ?? [], map((c) => normalizeChild(c))),
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
const all = pipe(slugs, map(make));
|
|
48
|
+
const bySlug = Object.fromEntries(all.map((n) => [n.slug, n]));
|
|
49
|
+
for (const n of all) {
|
|
50
|
+
if (n.parent && !bySlug[n.parent]) throw new Error(`node ${n.slug}: unknown parent \`${n.parent}\``);
|
|
51
|
+
}
|
|
52
|
+
const roots = all.filter((n) => !n.parent);
|
|
53
|
+
return { roots, all, bySlug, slugs };
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const matchNode = (relPath, node) => {
|
|
57
|
+
const m = node.prefixRe.exec(relPath);
|
|
58
|
+
if (!m) return null;
|
|
59
|
+
const segIdx = node.prefixNames.length;
|
|
60
|
+
const caps = Object.fromEntries(node.prefixNames.map((n, i) => [n, m[i + 1]]));
|
|
61
|
+
return { node, seg: m[segIdx + 1], isFile: m[segIdx + 2] == null, caps };
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const deepestMatch = (relPath, arch) => {
|
|
65
|
+
const matches = pipe(
|
|
66
|
+
arch.nodes.all,
|
|
67
|
+
map((node) => matchNode(relPath, node)),
|
|
68
|
+
filter(Boolean),
|
|
69
|
+
sort((x) => x.node.path.length),
|
|
70
|
+
);
|
|
71
|
+
return matches.length ? matches[matches.length - 1] : null;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const findChild = (children, seg, isFile) => pipe(children, filter((c) => c.folder === !isFile && c.re.test(seg)), (r) => (r.length ? r[0] : null));
|
|
75
|
+
|
|
76
|
+
const checkEntry = (match, child, out, findingFrom) => {
|
|
77
|
+
const vars = { basename: match.seg, ...match.caps };
|
|
78
|
+
if (child && child.forbidden) {
|
|
79
|
+
out.push(findingFrom({ key: "forbidden", report: child.report }, "nodes", match.node.slug, `nodes:${match.node.slug}:forbidden`, vars));
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (!child && match.node.closed) {
|
|
83
|
+
out.push(findingFrom({ key: "closed", report: match.node.report }, "nodes", match.node.slug, `nodes:${match.node.slug}:closed`, vars));
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const checkTree = (relPath, arch, out, finding) => {
|
|
88
|
+
const match = deepestMatch(relPath, arch);
|
|
89
|
+
if (!match) return;
|
|
90
|
+
if (match.isFile) {
|
|
91
|
+
checkEntry(match, findChild(match.node.children, match.seg, true), out, finding);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const m = match.node.prefixRe.exec(relPath);
|
|
95
|
+
const parts = m[match.node.prefixNames.length + 2].split("/");
|
|
96
|
+
let node = match.node;
|
|
97
|
+
for (const part of parts) {
|
|
98
|
+
const child = findChild(node.children, part, false);
|
|
99
|
+
checkEntry({ node, seg: part, isFile: false }, child, out, finding);
|
|
100
|
+
node = child ? arch.nodes.bySlug[child.name] ?? null : null;
|
|
101
|
+
if (!node) break;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const matchers = (arch) => {
|
|
106
|
+
const nodeRes = arch.nodes.all.map((n) => n.prefixRe);
|
|
107
|
+
const invRes = arch.invariants.map((i) => i.where?.re).filter(Boolean);
|
|
108
|
+
const all = [...nodeRes, ...invRes];
|
|
109
|
+
return (rel) => all.some((re) => re.test(rel));
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
module.exports = { buildTree, checkTree, matchers };
|
package/main.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const { pipe, map, filter, flatMap } = require("remeda");
|
|
6
|
+
const { minimatch } = require("minimatch");
|
|
7
|
+
const { buildTree, matchers } = require("./entities/nodes");
|
|
8
|
+
const { normalizeInvariant } = require("./entities/invariants");
|
|
9
|
+
const { normalizeAliases } = require("./entities/aliases");
|
|
10
|
+
const { checkFile } = require("./utils");
|
|
11
|
+
const { renderReport } = require("./report");
|
|
12
|
+
const { createTsProject, toRel } = require("./ast");
|
|
13
|
+
|
|
14
|
+
const buildArchitecture = (raw) => {
|
|
15
|
+
if (!raw || typeof raw !== "object") throw new Error("architecture: expected an object");
|
|
16
|
+
if (!raw.nodes || !Object.keys(raw.nodes).length) throw new Error("architecture.nodes: must be a non-empty object");
|
|
17
|
+
const tree = buildTree(raw.nodes);
|
|
18
|
+
const invariants = pipe(raw.invariants ?? [], map((i) => normalizeInvariant(i, tree.slugs)));
|
|
19
|
+
const ids = invariants.map((i) => i.id);
|
|
20
|
+
if (new Set(ids).size !== ids.length) throw new Error("architecture.invariants: ids must be unique");
|
|
21
|
+
return {
|
|
22
|
+
nodes: tree,
|
|
23
|
+
invariants,
|
|
24
|
+
aliases: normalizeAliases(raw.aliases ?? {}),
|
|
25
|
+
files: raw.files ?? ["**/*.ts", "**/*.tsx"],
|
|
26
|
+
ignores: raw.ignores ?? [],
|
|
27
|
+
exts: raw.exts ?? [".ts", ".tsx", ".js", ".jsx"],
|
|
28
|
+
raw,
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const loadArchitecture = (config) => {
|
|
33
|
+
if (typeof config === "string") {
|
|
34
|
+
const p = path.resolve(process.cwd(), config);
|
|
35
|
+
const text = fs.readFileSync(p, "utf8");
|
|
36
|
+
if (p.endsWith(".js") || p.endsWith(".cjs")) return buildArchitecture(require(p));
|
|
37
|
+
return buildArchitecture(JSON.parse(text));
|
|
38
|
+
}
|
|
39
|
+
if (config && typeof config === "object" && typeof config.file === "string") return loadArchitecture(config.file);
|
|
40
|
+
return buildArchitecture(config);
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const collectFiles = (repoRoot, { exts, ignoreDirs, ignoreGlobs }) => {
|
|
44
|
+
const extSet = new Set(exts);
|
|
45
|
+
const ignoreSet = new Set(ignoreDirs);
|
|
46
|
+
const out = [];
|
|
47
|
+
const walk = (dir) => {
|
|
48
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
49
|
+
const abs = path.join(dir, entry.name);
|
|
50
|
+
if (entry.isDirectory()) {
|
|
51
|
+
if (!ignoreSet.has(entry.name)) walk(abs);
|
|
52
|
+
} else if (extSet.has(path.extname(entry.name))) {
|
|
53
|
+
if (!ignoreGlobs.some((g) => minimatch(toRel(repoRoot, abs), g))) out.push(abs);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
walk(repoRoot);
|
|
58
|
+
return out;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const main = (argv) => {
|
|
62
|
+
const { parseArgs } = require("./config");
|
|
63
|
+
const args = parseArgs(argv);
|
|
64
|
+
if (args.help) {
|
|
65
|
+
console.log("usage: follow-architecture [--config <path>] [--ignore <glob>]... [--out <path>] [--check]");
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
const repoRoot = path.resolve(args.cwd ?? process.cwd());
|
|
69
|
+
const arch = loadArchitecture(args.config);
|
|
70
|
+
const project = createTsProject();
|
|
71
|
+
const shouldCheck = matchers(arch);
|
|
72
|
+
const files = pipe(
|
|
73
|
+
collectFiles(repoRoot, { exts: arch.exts, ignoreDirs: ["node_modules", ".git", "dist", "build", "_medplum"], ignoreGlobs: [...(arch.ignores ?? []), ...(args.ignore ?? [])] }),
|
|
74
|
+
map((abs) => ({ abs, rel: toRel(repoRoot, abs) })),
|
|
75
|
+
filter((f) => shouldCheck(f.rel)),
|
|
76
|
+
);
|
|
77
|
+
const byDir = new Map();
|
|
78
|
+
for (const f of files) {
|
|
79
|
+
const dir = path.posix.dirname(f.rel);
|
|
80
|
+
if (!byDir.has(dir)) byDir.set(dir, []);
|
|
81
|
+
byDir.get(dir).push(f.rel);
|
|
82
|
+
}
|
|
83
|
+
const findings = pipe(files, flatMap((f) => checkFile(f.abs, fs.readFileSync(f.abs, "utf8"), repoRoot, arch, project, byDir.get(path.posix.dirname(f.rel)) ?? [])));
|
|
84
|
+
const text = renderReport(findings, repoRoot);
|
|
85
|
+
if (args.out) {
|
|
86
|
+
fs.writeFileSync(args.out, text);
|
|
87
|
+
console.log(`wrote ${args.out} (${findings.length} findings)`);
|
|
88
|
+
} else {
|
|
89
|
+
console.log(text);
|
|
90
|
+
}
|
|
91
|
+
if (args.check && findings.length > 0) return 1;
|
|
92
|
+
return 0;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
module.exports = { main, loadArchitecture, buildArchitecture };
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@md-code/follow-architecture",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "ESLint rule + CLI that enforces the vertical-slice architecture: every slice has a .resource.ts CRUD binding, every .rm.ts imports and calls it, and nothing bypasses it.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"main": "config.js",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=18"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"follow-architecture": "bin/follow-architecture.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"config.js",
|
|
15
|
+
"main.js",
|
|
16
|
+
"utils.js",
|
|
17
|
+
"report.js",
|
|
18
|
+
"ast.js",
|
|
19
|
+
"entities",
|
|
20
|
+
"bin",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"exports": {
|
|
24
|
+
".": "./config.js",
|
|
25
|
+
"./config": "./config.js",
|
|
26
|
+
"./main": "./main.js",
|
|
27
|
+
"./package.json": "./package.json"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@typescript-eslint/parser": "^8.71.0",
|
|
31
|
+
"remeda": "^2.50.0",
|
|
32
|
+
"minimatch": "^9.0.4",
|
|
33
|
+
"ts-morph": "^24.0.0"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"eslint": ">=8.40.0"
|
|
37
|
+
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"keywords": [
|
|
42
|
+
"eslint",
|
|
43
|
+
"eslint-rule",
|
|
44
|
+
"architecture",
|
|
45
|
+
"vertical-slice",
|
|
46
|
+
"fhir",
|
|
47
|
+
"typescript"
|
|
48
|
+
]
|
|
49
|
+
}
|
package/report.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { unique } = require("remeda");
|
|
4
|
+
|
|
5
|
+
const substitute = (text, vars) => String(text).replace(/\{([A-Za-z][A-Za-z0-9_]*)\}/g, (_, k) => (vars[k] != null ? String(vars[k]) : `\{${k}\}`));
|
|
6
|
+
|
|
7
|
+
const subText = (t, vars) => {
|
|
8
|
+
if (t == null) return null;
|
|
9
|
+
if (typeof t === "function") return t(vars);
|
|
10
|
+
return substitute(t, vars);
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const oneLine = (s) => String(s ?? "").replace(/\s+/g, " ").trim();
|
|
14
|
+
|
|
15
|
+
const renderSpec = (r, vars) => {
|
|
16
|
+
if (r == null) return null;
|
|
17
|
+
if (typeof r === "function") return r(vars);
|
|
18
|
+
if (typeof r === "string") return { message: substitute(r, vars), fix: null };
|
|
19
|
+
return { message: subText(r.message, vars), fix: subText(r.fix, vars) };
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const finding = (key, rule, node, message, fix, pos) => {
|
|
23
|
+
const rep = message != null && typeof message === "object" ? renderSpec(message, {}) : null;
|
|
24
|
+
return {
|
|
25
|
+
node,
|
|
26
|
+
rule,
|
|
27
|
+
key,
|
|
28
|
+
message: rep?.message ?? String(message ?? ""),
|
|
29
|
+
fix: rep?.fix ?? fix ?? null,
|
|
30
|
+
pos: pos && pos.line ? pos : { line: 1, column: 1 },
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const findingFrom = (f, rule, nodeId, keyPrefix, caps) => {
|
|
35
|
+
const vars = { ...caps, ...f };
|
|
36
|
+
const rep = f.report != null ? renderSpec(f.report, vars) : f.message != null || f.fix != null ? { message: subText(f.message, vars), fix: subText(f.fix, vars) } : null;
|
|
37
|
+
const message = rep?.message ?? vars.message ?? "architecture violation";
|
|
38
|
+
const fix = rep?.fix ?? vars.fix ?? null;
|
|
39
|
+
const pos = f.line ? { line: f.line, column: 1 } : { line: 1, column: 1 };
|
|
40
|
+
const key = `${keyPrefix}:${f.key || oneLine(message).slice(0, 40)}`;
|
|
41
|
+
return finding(key, rule, nodeId, message, fix, pos);
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const renderReport = (findings, repoRoot) => {
|
|
45
|
+
const files = unique(findings.map((f) => f.file)).sort();
|
|
46
|
+
const lines = [];
|
|
47
|
+
lines.push(`# follow-architecture report`);
|
|
48
|
+
lines.push(``);
|
|
49
|
+
lines.push(`Generated against \`${repoRoot}\`.`);
|
|
50
|
+
lines.push(``);
|
|
51
|
+
lines.push(`## Findings`);
|
|
52
|
+
for (const file of files) {
|
|
53
|
+
lines.push(``);
|
|
54
|
+
lines.push(`### \`${file}\``);
|
|
55
|
+
const list = findings.filter((x) => x.file === file);
|
|
56
|
+
for (const f of list) {
|
|
57
|
+
lines.push(``);
|
|
58
|
+
lines.push(f.message);
|
|
59
|
+
if (f.fix) {
|
|
60
|
+
lines.push(``);
|
|
61
|
+
lines.push(`**Fix.**`);
|
|
62
|
+
lines.push(``);
|
|
63
|
+
lines.push(f.fix);
|
|
64
|
+
}
|
|
65
|
+
lines.push(``);
|
|
66
|
+
lines.push(`---`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
lines.push(``);
|
|
70
|
+
return lines.join("\n");
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
module.exports = { finding, findingFrom, renderReport };
|
package/utils.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { pipe, map, uniqueBy } = require("remeda");
|
|
4
|
+
|
|
5
|
+
const asReport = (r) => {
|
|
6
|
+
if (r == null) return null;
|
|
7
|
+
if (typeof r === "string" || typeof r === "function") return r;
|
|
8
|
+
const out = {};
|
|
9
|
+
if (r.level != null) out.level = String(r.level);
|
|
10
|
+
if (r.message != null) out.message = r.message;
|
|
11
|
+
if (r.fix != null) out.fix = r.fix;
|
|
12
|
+
return Object.keys(out).length ? out : null;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const globToRegex = (glob) => {
|
|
16
|
+
let out = "";
|
|
17
|
+
for (let i = 0; i < glob.length; i += 1) {
|
|
18
|
+
const c = glob[i];
|
|
19
|
+
if (c === "*" && glob[i + 1] === "*" && glob[i + 2] === "/") {
|
|
20
|
+
out += "(?:.*/)?";
|
|
21
|
+
i += 2;
|
|
22
|
+
} else if (c === "*" && glob[i + 1] === "*") {
|
|
23
|
+
out += ".*";
|
|
24
|
+
i += 1;
|
|
25
|
+
} else if (c === "*") {
|
|
26
|
+
out += "[^/]*";
|
|
27
|
+
} else if (c === "?") {
|
|
28
|
+
out += "[^/]";
|
|
29
|
+
} else if ("\\.+^$|()[]".includes(c)) {
|
|
30
|
+
out += `\\${c}`;
|
|
31
|
+
} else {
|
|
32
|
+
out += c;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const nodePrefixRe = (template) => {
|
|
39
|
+
const names = [];
|
|
40
|
+
const body = String(template)
|
|
41
|
+
.replace(/\{([A-Za-z-]+)\}/g, (_, n) => {
|
|
42
|
+
names.push(n);
|
|
43
|
+
return "\u0000";
|
|
44
|
+
})
|
|
45
|
+
.replace(/[.*+?^${}()|[\]\\]/g, (c) => `\\${c}`)
|
|
46
|
+
.replace(/\u0000/g, "([^/]+)");
|
|
47
|
+
return { re: new RegExp(`^${body}/([^/]+)(?:/(.*))?$`), names };
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const compilePattern = (pattern) => {
|
|
51
|
+
const names = [];
|
|
52
|
+
const glob = String(pattern).replace(/\\/g, "/").replace(/\{([A-Za-z][A-Za-z0-9_]*)\}/g, (_, n) => {
|
|
53
|
+
names.push(n);
|
|
54
|
+
return `\u0000${n}\u0000`;
|
|
55
|
+
});
|
|
56
|
+
const body = globToRegex(glob).replace(/\u0000([A-Za-z][A-Za-z0-9_]*)\u0000/g, "([^/]+)");
|
|
57
|
+
return { re: new RegExp(`^${body}$`), names };
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const compileChild = (name) => {
|
|
61
|
+
const captures = [];
|
|
62
|
+
const glob = String(name).replace(/\{([A-Za-z-]+)\}/g, (_, n) => {
|
|
63
|
+
captures.push(n);
|
|
64
|
+
return "\u0000";
|
|
65
|
+
});
|
|
66
|
+
const body = globToRegex(glob).replace(/\u0000/g, "([^/]+)");
|
|
67
|
+
return { re: new RegExp(`^${body}$`), captures };
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const checkRegex = (p, where) => {
|
|
71
|
+
try {
|
|
72
|
+
new RegExp(p);
|
|
73
|
+
} catch (err) {
|
|
74
|
+
throw new Error(`${where}: invalid pattern \`${p}\` — ${err.message}`);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const FUNCTION_FORM = /^\s*(function\b|\(?\s*ctx\s*\)?\s*=>)/;
|
|
79
|
+
|
|
80
|
+
const compileWhen = (w) => {
|
|
81
|
+
if (w == null) return null;
|
|
82
|
+
if (typeof w === "function") return w;
|
|
83
|
+
if (typeof w === "string") {
|
|
84
|
+
if (FUNCTION_FORM.test(w)) return new Function("ctx", `"use strict"; return (${w})(ctx);`);
|
|
85
|
+
return new Function("ctx", `"use strict"; return (${w});`);
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const checkFile = (filePath, text, repoRoot, arch, project, siblings = []) => {
|
|
91
|
+
const { buildContext, toRel } = require("./ast");
|
|
92
|
+
const { checkTree } = require("./entities/nodes");
|
|
93
|
+
const { checkInvariant } = require("./entities/invariants");
|
|
94
|
+
const { findingFrom } = require("./report");
|
|
95
|
+
const relPath = toRel(repoRoot, filePath);
|
|
96
|
+
const ctx = buildContext(project, filePath, text, repoRoot, arch.aliases, siblings);
|
|
97
|
+
ctx.arch = arch;
|
|
98
|
+
const out = [];
|
|
99
|
+
checkTree(relPath, arch, out, findingFrom);
|
|
100
|
+
for (const inv of arch.invariants) checkInvariant(inv, ctx, {}, out, findingFrom);
|
|
101
|
+
return pipe(out, uniqueBy((f) => f.key), map((f) => ({ ...f, file: relPath })));
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
module.exports = { asReport, nodePrefixRe, compilePattern, compileChild, checkRegex, compileWhen, checkFile };
|