@seanningtatum/software-factory-lint 0.0.0-stage → 0.4.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/dist/index.js ADDED
@@ -0,0 +1,68 @@
1
+ // src/files.ts
2
+ import { readdirSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { join, relative, sep } from "node:path";
5
+ var toSlash = (path, separator = sep) => path.split(separator).join("/");
6
+ var walk = (root, dir) => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
7
+ if (entry.name === "node_modules" || entry.name.startsWith("."))
8
+ return [];
9
+ const path = join(dir, entry.name);
10
+ return entry.isDirectory() ? walk(root, path) : [toSlash(relative(root, path))];
11
+ });
12
+ var ts;
13
+ var importSpecifiers = (text) => {
14
+ ts ??= createRequire(import.meta.url)("@typescript/typescript6");
15
+ return ts.preProcessFile(text, true, true).importedFiles.map((f) => f.fileName);
16
+ };
17
+ var TEST_FILE = /\.(test|spec)\.tsx?$/;
18
+ var byCodeUnit = (a, b) => Number(a > b) - Number(a < b);
19
+ // src/timeline-doc.ts
20
+ var TIMELINE_FILE = "TIMELINE.md";
21
+ var GENERATED_START = "<!-- generated:start -->";
22
+ var GENERATED_END = "<!-- generated:end -->";
23
+ var MACHINES_START = "<!-- machines:start -->";
24
+ var MACHINES_END = "<!-- machines:end -->";
25
+ var span = (text, start, end) => {
26
+ const from = text.indexOf(start);
27
+ const to = from < 0 ? -1 : text.indexOf(end, from);
28
+ return to < 0 ? undefined : { from, to: to + end.length };
29
+ };
30
+ var handWritten = (text) => [
31
+ [GENERATED_START, GENERATED_END],
32
+ [MACHINES_START, MACHINES_END]
33
+ ].reduce((acc, [start = "", end = ""]) => {
34
+ const s = span(acc, start, end);
35
+ return s ? acc.slice(0, s.from) + acc.slice(s.to) : acc;
36
+ }, text);
37
+ var withBlock = (text, start, end, block, anchor) => {
38
+ const s = span(text, start, end);
39
+ if (s) {
40
+ if (block)
41
+ return text.slice(0, s.from) + block + text.slice(s.to);
42
+ const from = text.slice(s.from - 2, s.from) === `
43
+
44
+ ` ? s.from - 2 : s.from;
45
+ return text.slice(0, from) + text.slice(s.to);
46
+ }
47
+ if (!block)
48
+ return text;
49
+ const at = text.indexOf(anchor);
50
+ if (at < 0)
51
+ return `${text.trimEnd()}
52
+
53
+ ${block}
54
+ `;
55
+ const after = at + anchor.length;
56
+ return `${text.slice(0, after)}
57
+
58
+ ${block}${text.slice(after)}`;
59
+ };
60
+ export {
61
+ GENERATED_END,
62
+ GENERATED_START,
63
+ TIMELINE_FILE,
64
+ byCodeUnit,
65
+ importSpecifiers,
66
+ toSlash,
67
+ walk
68
+ };
@@ -0,0 +1,211 @@
1
+ // src/files.ts
2
+ import { readdirSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { join, relative, sep } from "node:path";
5
+ var toSlash = (path, separator = sep) => path.split(separator).join("/");
6
+ var walk = (root, dir) => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
7
+ if (entry.name === "node_modules" || entry.name.startsWith("."))
8
+ return [];
9
+ const path = join(dir, entry.name);
10
+ return entry.isDirectory() ? walk(root, path) : [toSlash(relative(root, path))];
11
+ });
12
+ var ts;
13
+ var importSpecifiers = (text) => {
14
+ ts ??= createRequire(import.meta.url)("@typescript/typescript6");
15
+ return ts.preProcessFile(text, true, true).importedFiles.map((f) => f.fileName);
16
+ };
17
+ var TEST_FILE = /\.(test|spec)\.tsx?$/;
18
+ var byCodeUnit = (a, b) => Number(a > b) - Number(a < b);
19
+
20
+ // src/timeline-doc.ts
21
+ var TIMELINE_FILE = "TIMELINE.md";
22
+ var GENERATED_START = "<!-- generated:start -->";
23
+ var GENERATED_END = "<!-- generated:end -->";
24
+ var MACHINES_START = "<!-- machines:start -->";
25
+ var MACHINES_END = "<!-- machines:end -->";
26
+ var span = (text, start, end) => {
27
+ const from = text.indexOf(start);
28
+ const to = from < 0 ? -1 : text.indexOf(end, from);
29
+ return to < 0 ? undefined : { from, to: to + end.length };
30
+ };
31
+ var handWritten = (text) => [
32
+ [GENERATED_START, GENERATED_END],
33
+ [MACHINES_START, MACHINES_END]
34
+ ].reduce((acc, [start = "", end = ""]) => {
35
+ const s = span(acc, start, end);
36
+ return s ? acc.slice(0, s.from) + acc.slice(s.to) : acc;
37
+ }, text);
38
+ var withBlock = (text, start, end, block, anchor) => {
39
+ const s = span(text, start, end);
40
+ if (s) {
41
+ if (block)
42
+ return text.slice(0, s.from) + block + text.slice(s.to);
43
+ const from = text.slice(s.from - 2, s.from) === `
44
+
45
+ ` ? s.from - 2 : s.from;
46
+ return text.slice(0, from) + text.slice(s.to);
47
+ }
48
+ if (!block)
49
+ return text;
50
+ const at = text.indexOf(anchor);
51
+ if (at < 0)
52
+ return `${text.trimEnd()}
53
+
54
+ ${block}
55
+ `;
56
+ const after = at + anchor.length;
57
+ return `${text.slice(0, after)}
58
+
59
+ ${block}${text.slice(after)}`;
60
+ };
61
+
62
+ // src/machines.ts
63
+ var children = (node) => Object.values(node.states);
64
+ var descendants = (node) => children(node).flatMap((child) => [child, ...descendants(child)]);
65
+ var initialTargets = (node) => node.type === "parallel" ? children(node) : node.initial?.target ?? [];
66
+ var historyTargets = (node) => {
67
+ const parent = node.parent;
68
+ const targets = [node.config.target ?? []].flat();
69
+ if (!targets.length)
70
+ return parent.type === "parallel" ? [parent] : initialTargets(parent);
71
+ return targets.map((t) => t.startsWith("#") ? node.machine.getStateNodeById(t.slice(1)) : t.split(".").reduce((n, key) => n.states[key], parent));
72
+ };
73
+ var entered = (node) => node.type === "history" ? [node, ...historyTargets(node).flatMap(entered)] : [node, ...initialTargets(node).flatMap(entered)];
74
+ var label = (eventType) => {
75
+ if (eventType.startsWith("xstate.done.actor."))
76
+ return `done: ${eventType.slice(18)}`;
77
+ if (eventType.startsWith("xstate.error.actor."))
78
+ return `error: ${eventType.slice(19)}`;
79
+ if (eventType.startsWith("xstate.after."))
80
+ return "after";
81
+ return eventType;
82
+ };
83
+ var edgesOf = (node) => {
84
+ const out = [];
85
+ for (const [eventType, transitions] of Object.entries(node.on ?? {})) {
86
+ for (const t of transitions) {
87
+ for (const to of t.target ?? [])
88
+ out.push({ from: node, to, label: label(eventType) });
89
+ }
90
+ }
91
+ for (const t of node.always ?? [])
92
+ for (const to of t.target ?? [])
93
+ out.push({ from: node, to, label: "always" });
94
+ return out;
95
+ };
96
+ var ancestors = (node) => node.parent ? [node.parent, ...ancestors(node.parent)] : [];
97
+ var isParallelDone = (e) => e.from.type === "parallel" && e.label.startsWith("xstate.done.state.");
98
+ var next = (node, inRegion = false) => [node, ...ancestors(node)].flatMap(edgesOf).filter((e) => !(inRegion && isParallelDone(e))).flatMap((e) => entered(e.to));
99
+ var reachableFrom = (starts, inRegion = false) => {
100
+ const seen = new Set;
101
+ const queue = [...starts];
102
+ while (queue.length) {
103
+ const node = queue.shift();
104
+ if (seen.has(node))
105
+ continue;
106
+ seen.add(node);
107
+ queue.push(...next(node, inRegion), ...initialTargets(node));
108
+ }
109
+ return seen;
110
+ };
111
+ var isFinal = (node) => node.type === "final";
112
+ var name = (node) => node.path.join(".") || "(root)";
113
+ var settled = (nodes) => {
114
+ const out = new Set;
115
+ const queue = nodes.flatMap(entered);
116
+ while (queue.length) {
117
+ const node = queue.shift();
118
+ if (out.has(node))
119
+ continue;
120
+ out.add(node);
121
+ for (const edge of edgesOf(node))
122
+ if (edge.label === "always")
123
+ queue.push(...entered(edge.to));
124
+ }
125
+ return [...out];
126
+ };
127
+ var checkMachine = (machine) => {
128
+ const problems = [];
129
+ const root = machine.root;
130
+ const all = descendants(root);
131
+ const initial = initialTargets(root);
132
+ const start = settled(initial);
133
+ const reached = reachableFrom(initial.flatMap(entered));
134
+ const reachable = new Set([...reached].flatMap((n) => [n, ...ancestors(n)]));
135
+ for (const node of all) {
136
+ if (!reachable.has(node))
137
+ problems.push({ state: name(node), message: "cannot be reached from the start" });
138
+ }
139
+ const atomic = all.filter((n) => n.type === "atomic" || n.type === "final");
140
+ for (const node of atomic) {
141
+ if (!reachable.has(node) || isFinal(node) || start.includes(node))
142
+ continue;
143
+ const onward = reachableFrom(next(node, true), true);
144
+ const recovers = [...onward].some((n) => start.includes(n) || isFinal(n));
145
+ if (!recovers) {
146
+ problems.push({
147
+ state: name(node),
148
+ message: "is a trap: it is not final and cannot reach the start or a final state"
149
+ });
150
+ }
151
+ }
152
+ for (const node of [root, ...start]) {
153
+ if (node.invoke.length) {
154
+ problems.push({
155
+ state: name(node),
156
+ message: "invokes an actor in the initial state; start it from an event instead"
157
+ });
158
+ }
159
+ }
160
+ return problems;
161
+ };
162
+ var mermaidId = (node) => node.path.join("_");
163
+ var renderNode = (node, depth) => {
164
+ const pad = " ".repeat(depth);
165
+ const lines = [];
166
+ const kids = children(node);
167
+ const init = initialTargets(node);
168
+ if (node.type !== "parallel")
169
+ for (const target of init)
170
+ lines.push(`${pad}[*] --> ${mermaidId(target)}`);
171
+ for (const child of kids) {
172
+ if (children(child).length) {
173
+ lines.push(`${pad}state ${mermaidId(child)} {`, ...renderNode(child, depth + 1), `${pad}}`);
174
+ }
175
+ if (isFinal(child))
176
+ lines.push(`${pad}${mermaidId(child)} --> [*]`);
177
+ for (const edge of edgesOf(child))
178
+ lines.push(`${pad}${mermaidId(edge.from)} --> ${mermaidId(edge.to)} : ${edge.label}`);
179
+ }
180
+ return lines;
181
+ };
182
+ var toMermaid = (machine) => [
183
+ "stateDiagram-v2",
184
+ ...renderNode(machine.root, 1),
185
+ ...edgesOf(machine.root).map((e) => ` ${mermaidId(e.from) || "root"} --> ${mermaidId(e.to)} : ${e.label}`)
186
+ ].join(`
187
+ `);
188
+ var machinesBlock = (docs) => {
189
+ if (!docs.length)
190
+ return "";
191
+ const sorted = [...docs].sort((a, b) => byCodeUnit(a.source, b.source) || byCodeUnit(a.machine.id, b.machine.id));
192
+ const sections = sorted.map(({ source, machine }) => `### ${machine.id}
193
+
194
+ Source: \`${source}\`
195
+
196
+ \`\`\`mermaid
197
+ ${toMermaid(machine)}
198
+ \`\`\``);
199
+ const intro = "Written by `bun run machines:print`. `bun run test` fails when a diagram is out of date.";
200
+ return [MACHINES_START, "## Machines", intro, ...sections, MACHINES_END].join(`
201
+
202
+ `);
203
+ };
204
+ var withMachines = (timeline, docs) => withBlock(timeline, MACHINES_START, MACHINES_END, machinesBlock(docs), GENERATED_END);
205
+ export {
206
+ checkMachine,
207
+ edgesOf,
208
+ machinesBlock,
209
+ toMermaid,
210
+ withMachines
211
+ };
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@seanningtatum/software-factory-lint",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "House lint rules for software-factory projects: Effect rules, the test map and the state machine gate",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "files": [
8
+ "dist",
9
+ "src"
10
+ ],
11
+ "exports": {
12
+ ".": {
13
+ "types": "./src/index.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./machines": {
17
+ "types": "./src/machines.ts",
18
+ "default": "./dist/machines.js"
19
+ }
20
+ },
21
+ "bin": {
22
+ "software-factory-lint": "./dist/bin.js"
23
+ },
24
+ "scripts": {
25
+ "build": "bun build src/index.ts src/machines.ts src/bin.ts --outdir dist --target node --packages external",
26
+ "typecheck": "tsc -p .",
27
+ "test": "bun test"
28
+ },
29
+ "dependencies": {
30
+ "@typescript/typescript6": "^6.0.2"
31
+ },
32
+ "devDependencies": {
33
+ "@seanningtatum/software-factory-tsconfig": "workspace:*",
34
+ "@types/bun": "latest",
35
+ "xstate": "5.33.4"
36
+ },
37
+ "peerDependencies": {
38
+ "xstate": "^5.0.0"
39
+ }
40
+ }
package/src/bin.ts ADDED
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ import { lint, projectRules, rules } from "./lint.ts";
3
+ import { runTimeline } from "./timeline-git.ts";
4
+
5
+ const args = process.argv.slice(2);
6
+
7
+ const usage = `software-factory-lint [command]
8
+
9
+ (none) run the house rules on this project
10
+ --rules list the rules
11
+ timeline [--base <ref>] fail when a feature changed since <ref> (default origin/staging,
12
+ [--skip] else origin/main, else HEAD~1) without a new line in its
13
+ TIMELINE.md; --skip or TIMELINE_SKIP=1 skips it`;
14
+
15
+ const runLint = () => {
16
+ const findings = lint(process.cwd());
17
+ for (const f of findings) console.error(`${f.file}:${f.line} ${f.rule} ${f.message}`);
18
+ if (!findings.length) {
19
+ console.log("software-factory-lint: no problems.");
20
+ return 0;
21
+ }
22
+ console.error(
23
+ `\n${findings.length} problem(s). Allow a file only in software-factory-lint.json "allow", with a reason in review.`,
24
+ );
25
+ return 1;
26
+ };
27
+
28
+ const timeline = () => {
29
+ const at = args.indexOf("--base");
30
+ const base = at >= 0 ? args[at + 1] : undefined;
31
+ const skip = args.includes("--skip") || ["1", "true"].includes(process.env.TIMELINE_SKIP ?? "");
32
+ const result = runTimeline(process.cwd(), { base, skip });
33
+ for (const line of result.lines) (result.code ? console.error : console.log)(line);
34
+ return result.code;
35
+ };
36
+
37
+ const main = () => {
38
+ if (args.includes("--help") || args.includes("-h")) {
39
+ console.log(usage);
40
+ return 0;
41
+ }
42
+ if (args.includes("--rules")) {
43
+ for (const rule of [...rules, ...projectRules]) {
44
+ console.log(`${rule.id.padEnd(20)} ${rule.description}`);
45
+ }
46
+ return 0;
47
+ }
48
+ if (args[0] === "timeline") return timeline();
49
+ if (args[0]) {
50
+ console.error(`Unknown command "${args[0]}".\n\n${usage}`);
51
+ return 1;
52
+ }
53
+ return runLint();
54
+ };
55
+
56
+ process.exitCode = main();
package/src/config.ts ADDED
@@ -0,0 +1,146 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ export const CONFIG_FILE = "software-factory-lint.json";
5
+
6
+ export interface TestMapEntry {
7
+ /** Source files this entry covers. Every matching entry applies. */
8
+ readonly files: string;
9
+ /**
10
+ * Test files that must exist. `{dir}`, `{file}` (no extension), `{name}` (also no `.machine`)
11
+ * and `{feature}` (the feature's folder under src/features, e.g. `auth` or `core/kv`) come from
12
+ * the source file. `{route}` is a route file's path under its `routes/` folder, without the
13
+ * extension, `/` as `.` and `$` dropped (`api/uploads/$id.ts` is `api.uploads.id`, `api/auth/$.ts`
14
+ * is `api.auth.splat`).
15
+ */
16
+ readonly requires: ReadonlyArray<string>;
17
+ /** Applies to files in `testExempt` too; the exemption then skips only the other entries. */
18
+ readonly always?: boolean;
19
+ }
20
+
21
+ /**
22
+ * The core group: shared modules of one kind each, and shared pure helpers. A module with both
23
+ * components and services, or with a page, is a feature and lives outside the group.
24
+ */
25
+ export interface CoreLayout {
26
+ /** The group folder, under the features dir. Each folder in it is one core module. */
27
+ readonly dir: string;
28
+ /** The shared helpers folder inside the group: flat `.ts` files, no feature.json. */
29
+ readonly lib: string;
30
+ /** Folders a components module may have (shared React and the helpers it needs). */
31
+ readonly componentFolders: ReadonlyArray<string>;
32
+ /** Top-level files a components module may have, each with an optional sibling test. */
33
+ readonly componentFiles: ReadonlyArray<string>;
34
+ /** Folders a services module may have. */
35
+ readonly serviceFolders: ReadonlyArray<string>;
36
+ /** The folder of `routes/` that a services module may serve from: server routes only. */
37
+ readonly serverRoutes: string;
38
+ }
39
+
40
+ export interface FeatureLayout {
41
+ /** Where features live. Each folder under it is one feature, except the core group. */
42
+ readonly dir: string;
43
+ /** Folders a feature may have. Anything may sit inside them. */
44
+ readonly folders: ReadonlyArray<string>;
45
+ /** Files a feature may have at its top level. A sibling `*.test.ts` of a `.ts` one is allowed too. */
46
+ readonly files: ReadonlyArray<string>;
47
+ /** Files every feature must have. */
48
+ readonly required: ReadonlyArray<string>;
49
+ /** File patterns that may sit only in the listed folders, e.g. `*.spec.ts` only in `e2e`. */
50
+ readonly placement: Readonly<Record<string, ReadonlyArray<string>>>;
51
+ /** The core group and what its modules may hold. */
52
+ readonly core: CoreLayout;
53
+ }
54
+
55
+ export interface LintConfig {
56
+ /** Folders and files to lint. */
57
+ readonly include: ReadonlyArray<string>;
58
+ readonly exclude: ReadonlyArray<string>;
59
+ /** Files where a rule is allowed, keyed by rule id. Keep these lists short. */
60
+ readonly allow: Readonly<Record<string, ReadonlyArray<string>>>;
61
+ readonly maxLines: number;
62
+ /** Most lines CLAUDE.md may have. */
63
+ readonly maxRulesLines: number;
64
+ readonly testMap: ReadonlyArray<TestMapEntry>;
65
+ /** Source files that need no test of their own: declarations, wiring, UI primitives. */
66
+ readonly testExempt: ReadonlyArray<string>;
67
+ /** The fixed vocabulary of folders and files inside a feature. */
68
+ readonly featureLayout: FeatureLayout;
69
+ }
70
+
71
+ export const defaultFeatureLayout: FeatureLayout = {
72
+ dir: "src/features",
73
+ folders: ["api", "routes", "components", "machines", "lib", "e2e"],
74
+ files: [
75
+ "feature.json",
76
+ "TIMELINE.md",
77
+ "constants.ts",
78
+ "schema.ts",
79
+ "events.ts",
80
+ "errors.ts",
81
+ "layer.ts",
82
+ "nav.ts",
83
+ "viewer.ts",
84
+ "auth-plugins.ts",
85
+ "workflows.ts",
86
+ ],
87
+ required: ["feature.json", "TIMELINE.md"],
88
+ placement: {
89
+ "*.machine.ts": ["components", "machines"],
90
+ "*.spec.ts": ["e2e"],
91
+ },
92
+ core: {
93
+ dir: "core",
94
+ lib: "lib",
95
+ componentFolders: ["components", "lib"],
96
+ componentFiles: ["feature.json", "TIMELINE.md", "constants.ts"],
97
+ serviceFolders: ["api", "lib", "machines", "routes"],
98
+ serverRoutes: "api",
99
+ },
100
+ };
101
+
102
+ export const defaults: LintConfig = {
103
+ include: ["src/**/*.{ts,tsx}"],
104
+ exclude: ["src/gen/**", "src/routeTree.gen.ts", "**/*.d.ts"],
105
+ allow: {},
106
+ maxLines: 400,
107
+ maxRulesLines: 80,
108
+ testMap: [
109
+ { files: "src/**/*.machine.ts", requires: ["{dir}/{file}.test.ts"] },
110
+ {
111
+ files: "src/features/*/components/*.machine.ts",
112
+ requires: ["src/features/{feature}/e2e/{name}.paths.spec.ts"],
113
+ },
114
+ { files: "src/{app,features}/**/*.ts", requires: ["{dir}/{file}.test.ts"] },
115
+ {
116
+ files: "src/features/*/routes/**/*.{ts,tsx}",
117
+ requires: ["src/features/{feature}/e2e/{route}.route.spec.ts"],
118
+ always: true,
119
+ },
120
+ // A core module has no e2e/, so `home`, which is required and always there, holds its specs.
121
+ {
122
+ files: "src/features/core/*/routes/**/*.{ts,tsx}",
123
+ requires: ["src/features/home/e2e/{route}.route.spec.ts"],
124
+ always: true,
125
+ },
126
+ ],
127
+ testExempt: ["**/*.test.ts", "**/*.spec.ts"],
128
+ featureLayout: defaultFeatureLayout,
129
+ };
130
+
131
+ export const loadConfig = (root: string): LintConfig => {
132
+ const path = join(root, CONFIG_FILE);
133
+ if (!existsSync(path)) return defaults;
134
+ const user = JSON.parse(readFileSync(path, "utf8")) as Partial<LintConfig>;
135
+ return {
136
+ ...defaults,
137
+ ...user,
138
+ exclude: [...defaults.exclude, ...(user.exclude ?? [])],
139
+ testExempt: [...defaults.testExempt, ...(user.testExempt ?? [])],
140
+ featureLayout: {
141
+ ...defaults.featureLayout,
142
+ ...user.featureLayout,
143
+ core: { ...defaults.featureLayout.core, ...user.featureLayout?.core },
144
+ },
145
+ };
146
+ };