chore(template): clean-slate template snapshot from bb4a0c7
Curated, product-agnostic snapshot of the post-story-04 tree: demo content deleted, auth-only reference feature, web-next shell, all gates green. Product-specific docs, ADRs 027-029, PRDs/epics/archive, editor library traces, and product naming are curated out; generic template repairs (coverage provider devDeps, root test:coverage script, live lint fixes, root-only release-please) are kept. See TEMPLATE.md for provenance, curation list, and usage. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016j8z4VHjedXDTjEDNg7qHK
This commit is contained in:
99
packages/core-eslint/rules/_event-ast.js
Normal file
99
packages/core-eslint/rules/_event-ast.js
Normal file
@@ -0,0 +1,99 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { parse } from "@typescript-eslint/parser";
|
||||
|
||||
/** Unwrap `as`/`satisfies` expressions, return a string literal's value. */
|
||||
function stringFromNode(node) {
|
||||
if (!node) return null;
|
||||
if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression") {
|
||||
return stringFromNode(node.expression);
|
||||
}
|
||||
if (node.type === "Literal" && typeof node.value === "string") {
|
||||
return node.value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the event `name` from an event-descriptor initializer. Handles the
|
||||
* two shapes the codebase and `pnpm turbo gen event` produce:
|
||||
* - `defineEvent("feature.event", schema)` — the core-events helper
|
||||
* - `{ name: "feature.event" as const, schema }` — the inline descriptor
|
||||
* (used when core-events is not installed)
|
||||
*/
|
||||
function nameFromInit(init) {
|
||||
if (!init) return null;
|
||||
if (init.type === "TSAsExpression" || init.type === "TSSatisfiesExpression") {
|
||||
return nameFromInit(init.expression);
|
||||
}
|
||||
if (
|
||||
init.type === "CallExpression" &&
|
||||
init.callee.type === "Identifier" &&
|
||||
init.callee.name === "defineEvent" &&
|
||||
init.arguments.length > 0
|
||||
) {
|
||||
return stringFromNode(init.arguments[0]);
|
||||
}
|
||||
if (init.type === "ObjectExpression") {
|
||||
const nameProp = init.properties.find(
|
||||
(p) =>
|
||||
p.type === "Property" &&
|
||||
p.key.type === "Identifier" &&
|
||||
p.key.name === "name",
|
||||
);
|
||||
return nameProp ? stringFromNode(nameProp.value) : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a relative import source (evaluated from `fromFile`) to a `.ts`
|
||||
* file on disk. Returns null for bare/package specifiers or paths that don't
|
||||
* resolve — callers treat null as "can't analyse, skip".
|
||||
*/
|
||||
export function resolveRelativeImport(source, fromFile) {
|
||||
if (typeof source !== "string" || !source.startsWith(".")) return null;
|
||||
const base = path.resolve(path.dirname(fromFile), source);
|
||||
for (const candidate of [`${base}.ts`, path.join(base, "index.ts")]) {
|
||||
if (fs.existsSync(candidate)) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an event-contract file and return the `name` of the event descriptor
|
||||
* exported under `exportName`. Returns null when the file can't be read or
|
||||
* parsed, or doesn't export a recognised descriptor under that name.
|
||||
*/
|
||||
export function eventNameFromFile(filePath, exportName) {
|
||||
let source;
|
||||
try {
|
||||
source = fs.readFileSync(filePath, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
let ast;
|
||||
try {
|
||||
ast = parse(source, { loc: false, range: false });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
for (const stmt of ast.body) {
|
||||
let varDecl = null;
|
||||
if (
|
||||
stmt.type === "ExportNamedDeclaration" &&
|
||||
stmt.declaration?.type === "VariableDeclaration"
|
||||
) {
|
||||
varDecl = stmt.declaration;
|
||||
} else if (stmt.type === "VariableDeclaration") {
|
||||
varDecl = stmt;
|
||||
}
|
||||
if (!varDecl) continue;
|
||||
for (const d of varDecl.declarations) {
|
||||
if (d.id.type === "Identifier" && d.id.name === exportName) {
|
||||
return nameFromInit(d.init);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
270
packages/core-eslint/rules/_manifest-ast.js
Normal file
270
packages/core-eslint/rules/_manifest-ast.js
Normal file
@@ -0,0 +1,270 @@
|
||||
import fs from "node:fs";
|
||||
import { parse } from "@typescript-eslint/parser";
|
||||
|
||||
function extractStringLiterals(arrayExpr) {
|
||||
return arrayExpr.elements
|
||||
.filter((el) => el && el.type === "Literal" && typeof el.value === "string")
|
||||
.map((el) => el.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract budget names from a rateLimit array that contains either string
|
||||
* literals ("ip") or RateLimitBudget objects ({ name: "ip", window: "1m", budget: 5 }).
|
||||
*/
|
||||
function extractRateLimitNames(arrayExpr) {
|
||||
const names = [];
|
||||
for (const el of arrayExpr.elements) {
|
||||
if (!el) continue;
|
||||
if (el.type === "Literal" && typeof el.value === "string") {
|
||||
names.push(el.value);
|
||||
} else if (el.type === "ObjectExpression") {
|
||||
const nameProp = el.properties.find(
|
||||
(p) =>
|
||||
p.type === "Property" &&
|
||||
p.key.type === "Identifier" &&
|
||||
p.key.name === "name" &&
|
||||
p.value.type === "Literal" &&
|
||||
typeof p.value.value === "string",
|
||||
);
|
||||
if (nameProp) names.push(nameProp.value.value);
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a feature.manifest.ts file and extract per-use-case attributes.
|
||||
* Walks the AST to find the `defineFeature({...} as const)` call expression
|
||||
* and reads literal values from its argument object.
|
||||
*
|
||||
* Returns: { [useCaseName]: { mutates, audits[], publishes[], consumes[] } }
|
||||
* Returns null if the file is missing or doesn't match the expected shape.
|
||||
*/
|
||||
export function parseManifestUseCases(manifestPath) {
|
||||
let src;
|
||||
try {
|
||||
src = fs.readFileSync(manifestPath, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
let ast;
|
||||
try {
|
||||
ast = parse(src, {
|
||||
sourceType: "module",
|
||||
ecmaVersion: "latest",
|
||||
loc: false,
|
||||
range: false,
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const defineCall = findDefineFeatureCall(ast);
|
||||
if (!defineCall) return null;
|
||||
const arg = unwrapAsConst(defineCall.arguments[0]);
|
||||
if (!arg || arg.type !== "ObjectExpression") return null;
|
||||
const useCasesProp = arg.properties.find(
|
||||
(p) =>
|
||||
p.type === "Property" &&
|
||||
p.key.type === "Identifier" &&
|
||||
p.key.name === "useCases",
|
||||
);
|
||||
if (!useCasesProp || useCasesProp.value.type !== "ObjectExpression")
|
||||
return {};
|
||||
const result = {};
|
||||
for (const entry of useCasesProp.value.properties) {
|
||||
if (entry.type !== "Property" || entry.value.type !== "ObjectExpression")
|
||||
continue;
|
||||
const name =
|
||||
entry.key.type === "Identifier" ? entry.key.name : entry.key.value;
|
||||
result[name] = extractUseCaseEntry(entry.value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function findDefineFeatureCall(ast) {
|
||||
for (const node of ast.body) {
|
||||
if (node.type !== "ExportNamedDeclaration" || !node.declaration) continue;
|
||||
if (node.declaration.type !== "VariableDeclaration") continue;
|
||||
for (const decl of node.declaration.declarations) {
|
||||
const init = decl.init;
|
||||
if (!init) continue;
|
||||
if (
|
||||
init.type === "CallExpression" &&
|
||||
init.callee.type === "Identifier" &&
|
||||
init.callee.name === "defineFeature"
|
||||
) {
|
||||
return init;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function unwrapAsConst(node) {
|
||||
if (node && node.type === "TSAsExpression") return node.expression;
|
||||
return node;
|
||||
}
|
||||
|
||||
function extractUseCaseEntry(objExpr) {
|
||||
const entry = {
|
||||
mutates: false,
|
||||
audits: [],
|
||||
publishes: [],
|
||||
consumes: [],
|
||||
analyticsEvents: [],
|
||||
rateLimit: [],
|
||||
};
|
||||
for (const prop of objExpr.properties) {
|
||||
if (prop.type !== "Property" || prop.key.type !== "Identifier") continue;
|
||||
const key = prop.key.name;
|
||||
if (key === "mutates" && prop.value.type === "Literal") {
|
||||
entry.mutates = prop.value.value === true;
|
||||
} else if (
|
||||
(key === "audits" ||
|
||||
key === "publishes" ||
|
||||
key === "consumes" ||
|
||||
key === "analyticsEvents") &&
|
||||
prop.value.type === "ArrayExpression"
|
||||
) {
|
||||
entry[key] = extractStringLiterals(prop.value);
|
||||
} else if (key === "rateLimit" && prop.value.type === "ArrayExpression") {
|
||||
entry[key] = extractRateLimitNames(prop.value);
|
||||
}
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a feature.manifest.ts and return the full manifest shape:
|
||||
* { name, requiredCores: string[], useCases: { [name]: {...} } }
|
||||
*
|
||||
* Same AST walking as parseManifestUseCases but additionally extracts
|
||||
* the top-level name + requiredCores fields. Returns null on parse failure.
|
||||
*/
|
||||
export function parseManifestFully(manifestPath) {
|
||||
// Reuse the AST parser used by parseManifestUseCases by inlining the
|
||||
// file-read + AST walk. We need access to the manifest's top-level
|
||||
// argument object beyond just useCases.
|
||||
let src;
|
||||
try {
|
||||
src = fs.readFileSync(manifestPath, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
let ast;
|
||||
try {
|
||||
ast = parse(src, {
|
||||
sourceType: "module",
|
||||
ecmaVersion: "latest",
|
||||
loc: false,
|
||||
range: false,
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const defineCall = findDefineFeatureCallFromBody(ast);
|
||||
if (!defineCall) return null;
|
||||
const arg = unwrapAsConstNode(defineCall.arguments[0]);
|
||||
if (!arg || arg.type !== "ObjectExpression") return null;
|
||||
|
||||
let name = null;
|
||||
let requiredCores = [];
|
||||
let requiresConsent = [];
|
||||
let useCases = {};
|
||||
|
||||
for (const prop of arg.properties) {
|
||||
if (prop.type !== "Property" || prop.key.type !== "Identifier") continue;
|
||||
if (
|
||||
prop.key.name === "name" &&
|
||||
prop.value.type === "Literal" &&
|
||||
typeof prop.value.value === "string"
|
||||
) {
|
||||
name = prop.value.value;
|
||||
} else if (
|
||||
prop.key.name === "requiredCores" &&
|
||||
prop.value.type === "ArrayExpression"
|
||||
) {
|
||||
requiredCores = extractStringLiterals(prop.value);
|
||||
} else if (
|
||||
prop.key.name === "requiresConsent" &&
|
||||
prop.value.type === "ArrayExpression"
|
||||
) {
|
||||
requiresConsent = extractStringLiterals(prop.value);
|
||||
} else if (
|
||||
prop.key.name === "useCases" &&
|
||||
prop.value.type === "ObjectExpression"
|
||||
) {
|
||||
useCases = extractUseCasesMap(prop.value);
|
||||
}
|
||||
}
|
||||
|
||||
if (name === null) return null;
|
||||
return { name, requiredCores, requiresConsent, useCases };
|
||||
}
|
||||
|
||||
function extractUseCasesMap(useCasesObjExpr) {
|
||||
const result = {};
|
||||
for (const entry of useCasesObjExpr.properties) {
|
||||
if (entry.type !== "Property" || entry.value.type !== "ObjectExpression")
|
||||
continue;
|
||||
const ucName =
|
||||
entry.key.type === "Identifier" ? entry.key.name : entry.key.value;
|
||||
result[ucName] = extractUseCaseEntryFromObj(entry.value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Helper aliases for the existing private functions — exposed under
|
||||
// different names to avoid touching existing code paths.
|
||||
function findDefineFeatureCallFromBody(ast) {
|
||||
for (const node of ast.body) {
|
||||
if (node.type !== "ExportNamedDeclaration" || !node.declaration) continue;
|
||||
if (node.declaration.type !== "VariableDeclaration") continue;
|
||||
for (const decl of node.declaration.declarations) {
|
||||
const init = decl.init;
|
||||
if (!init) continue;
|
||||
if (
|
||||
init.type === "CallExpression" &&
|
||||
init.callee.type === "Identifier" &&
|
||||
init.callee.name === "defineFeature"
|
||||
) {
|
||||
return init;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function unwrapAsConstNode(node) {
|
||||
if (node && node.type === "TSAsExpression") return node.expression;
|
||||
return node;
|
||||
}
|
||||
|
||||
function extractUseCaseEntryFromObj(objExpr) {
|
||||
const entry = {
|
||||
mutates: false,
|
||||
audits: [],
|
||||
publishes: [],
|
||||
consumes: [],
|
||||
analyticsEvents: [],
|
||||
rateLimit: [],
|
||||
};
|
||||
for (const prop of objExpr.properties) {
|
||||
if (prop.type !== "Property" || prop.key.type !== "Identifier") continue;
|
||||
const key = prop.key.name;
|
||||
if (key === "mutates" && prop.value.type === "Literal") {
|
||||
entry.mutates = prop.value.value === true;
|
||||
} else if (
|
||||
(key === "audits" ||
|
||||
key === "publishes" ||
|
||||
key === "consumes" ||
|
||||
key === "analyticsEvents") &&
|
||||
prop.value.type === "ArrayExpression"
|
||||
) {
|
||||
entry[key] = extractStringLiterals(prop.value);
|
||||
} else if (key === "rateLimit" && prop.value.type === "ArrayExpression") {
|
||||
entry[key] = extractRateLimitNames(prop.value);
|
||||
}
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
154
packages/core-eslint/rules/_manifest-ast.test.js
Normal file
154
packages/core-eslint/rules/_manifest-ast.test.js
Normal file
@@ -0,0 +1,154 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import { parseManifestUseCases, parseManifestFully } from "./_manifest-ast.js";
|
||||
|
||||
function writeManifest(content) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "manifest-ast-"));
|
||||
const fp = path.join(dir, "feature.manifest.ts");
|
||||
fs.writeFileSync(fp, content);
|
||||
return fp;
|
||||
}
|
||||
|
||||
describe("parseManifestUseCases", () => {
|
||||
it("returns an empty object for a manifest with no useCases", () => {
|
||||
const fp = writeManifest(`export const xManifest = defineFeature({
|
||||
name: "x",
|
||||
requiredCores: [],
|
||||
useCases: {},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`);
|
||||
expect(parseManifestUseCases(fp)).toEqual({});
|
||||
});
|
||||
|
||||
it("extracts per-use-case publishes/audits/consumes arrays", () => {
|
||||
const fp = writeManifest(`export const authManifest = defineFeature({
|
||||
name: "auth",
|
||||
requiredCores: [],
|
||||
useCases: {
|
||||
signIn: { mutates: false, audits: [], publishes: [], consumes: [] },
|
||||
signUp: { mutates: true, audits: ["user.created"], publishes: ["auth.signed-up"], consumes: [] },
|
||||
signOut: { mutates: true, audits: ["session.ended"], publishes: [], consumes: [] },
|
||||
},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`);
|
||||
expect(parseManifestUseCases(fp)).toEqual({
|
||||
signIn: {
|
||||
mutates: false,
|
||||
audits: [],
|
||||
publishes: [],
|
||||
consumes: [],
|
||||
analyticsEvents: [],
|
||||
rateLimit: [],
|
||||
},
|
||||
signUp: {
|
||||
mutates: true,
|
||||
audits: ["user.created"],
|
||||
publishes: ["auth.signed-up"],
|
||||
consumes: [],
|
||||
analyticsEvents: [],
|
||||
rateLimit: [],
|
||||
},
|
||||
signOut: {
|
||||
mutates: true,
|
||||
audits: ["session.ended"],
|
||||
publishes: [],
|
||||
consumes: [],
|
||||
analyticsEvents: [],
|
||||
rateLimit: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null when file does not exist", () => {
|
||||
expect(parseManifestUseCases("/nonexistent/manifest.ts")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the file has no defineFeature call", () => {
|
||||
const fp = writeManifest(`export const x = 1;`);
|
||||
expect(parseManifestUseCases(fp)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseManifestFully", () => {
|
||||
it("returns name + requiredCores + useCases for a complete manifest", () => {
|
||||
// Use the writeManifest helper that already exists in the test file
|
||||
const fp = writeManifest(`export const authManifest = defineFeature({
|
||||
name: "auth",
|
||||
requiredCores: ["audit", "events"],
|
||||
useCases: {
|
||||
signIn: { mutates: false, audits: [], publishes: [], consumes: [] },
|
||||
signUp: { mutates: true, audits: ["user.created"], publishes: [], consumes: [] },
|
||||
},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`);
|
||||
expect(parseManifestFully(fp)).toEqual({
|
||||
name: "auth",
|
||||
requiredCores: ["audit", "events"],
|
||||
requiresConsent: [],
|
||||
useCases: {
|
||||
signIn: {
|
||||
mutates: false,
|
||||
audits: [],
|
||||
publishes: [],
|
||||
consumes: [],
|
||||
analyticsEvents: [],
|
||||
rateLimit: [],
|
||||
},
|
||||
signUp: {
|
||||
mutates: true,
|
||||
audits: ["user.created"],
|
||||
publishes: [],
|
||||
consumes: [],
|
||||
analyticsEvents: [],
|
||||
rateLimit: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts requiresConsent categories from the manifest", () => {
|
||||
const fp = writeManifest(`export const consentManifest = defineFeature({
|
||||
name: "consent",
|
||||
requiredCores: [],
|
||||
requiresConsent: ["analytics", "marketing"],
|
||||
useCases: {},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`);
|
||||
expect(parseManifestFully(fp)).toEqual({
|
||||
name: "consent",
|
||||
requiredCores: [],
|
||||
requiresConsent: ["analytics", "marketing"],
|
||||
useCases: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null when the manifest has no name", () => {
|
||||
const fp = writeManifest(`export const x = 1;`);
|
||||
expect(parseManifestFully(fp)).toBeNull();
|
||||
});
|
||||
|
||||
it("is not fooled by 'name:' inside a JSDoc comment (regex would false-match)", () => {
|
||||
const fp = writeManifest(`/**
|
||||
* Sample comment with name: "fake" embedded in it.
|
||||
*/
|
||||
export const realManifest = defineFeature({
|
||||
name: "real",
|
||||
requiredCores: [],
|
||||
useCases: {},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`);
|
||||
expect(parseManifestFully(fp)).toEqual({
|
||||
name: "real",
|
||||
requiredCores: [],
|
||||
requiresConsent: [],
|
||||
useCases: {},
|
||||
});
|
||||
});
|
||||
});
|
||||
38
packages/core-eslint/rules/_manifest-source.js
Normal file
38
packages/core-eslint/rules/_manifest-source.js
Normal file
@@ -0,0 +1,38 @@
|
||||
import path from "node:path";
|
||||
import { parseManifestFully } from "./_manifest-ast.js";
|
||||
|
||||
/**
|
||||
* Reads a feature.manifest.ts and returns { name, requiredCores }.
|
||||
* Backed by the AST parser from _manifest-ast.js — no longer uses regex.
|
||||
*
|
||||
* Returns: { name: string, requiredCores: string[] } | null
|
||||
*/
|
||||
export function readManifestSource(manifestPath) {
|
||||
const full = parseManifestFully(manifestPath);
|
||||
if (!full) return null;
|
||||
return { name: full.name, requiredCores: full.requiredCores };
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical manifest path for a given feature package root.
|
||||
*/
|
||||
export function manifestPathForFeature(featureRoot) {
|
||||
return path.join(featureRoot, "src", "feature.manifest.ts");
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an absolute file path and the monorepo root, returns the feature
|
||||
* package root that contains the file (e.g. /repo/packages/auth). Returns
|
||||
* null when the file lives outside the packages/ tree.
|
||||
*
|
||||
* Assumes the conventional layout `packages/<feature>/src/...`.
|
||||
*/
|
||||
export function featureRootForFile(filepath, repoRoot) {
|
||||
const packagesDir = path.join(repoRoot, "packages");
|
||||
if (!filepath.startsWith(packagesDir + path.sep)) return null;
|
||||
const rel = filepath.slice(packagesDir.length + 1); // e.g. "auth/src/..."
|
||||
const slash = rel.indexOf(path.sep);
|
||||
if (slash === -1) return null;
|
||||
const featureName = rel.slice(0, slash);
|
||||
return path.join(packagesDir, featureName);
|
||||
}
|
||||
90
packages/core-eslint/rules/_manifest-source.test.js
Normal file
90
packages/core-eslint/rules/_manifest-source.test.js
Normal file
@@ -0,0 +1,90 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import {
|
||||
readManifestSource,
|
||||
manifestPathForFeature,
|
||||
featureRootForFile,
|
||||
} from "./_manifest-source.js";
|
||||
|
||||
function writeTempFile(filename, contents) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "manifest-source-"));
|
||||
const filepath = path.join(dir, filename);
|
||||
fs.writeFileSync(filepath, contents);
|
||||
return { dir, filepath };
|
||||
}
|
||||
|
||||
describe("_manifest-source", () => {
|
||||
describe("readManifestSource", () => {
|
||||
it("returns { name, requiredCores: [] } for a minimal manifest", () => {
|
||||
const { filepath } = writeTempFile(
|
||||
"feature.manifest.ts",
|
||||
`import { defineFeature } from "@repo/core-shared/conformance";
|
||||
export const xManifest = defineFeature({
|
||||
name: "test",
|
||||
requiredCores: [],
|
||||
useCases: {},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`,
|
||||
);
|
||||
expect(readManifestSource(filepath)).toEqual({
|
||||
name: "test",
|
||||
requiredCores: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts multi-element requiredCores", () => {
|
||||
const { filepath } = writeTempFile(
|
||||
"feature.manifest.ts",
|
||||
`export const xManifest = defineFeature({
|
||||
name: "auth",
|
||||
requiredCores: ["audit", "events"],
|
||||
useCases: {},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`,
|
||||
);
|
||||
expect(readManifestSource(filepath)).toEqual({
|
||||
name: "auth",
|
||||
requiredCores: ["audit", "events"],
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null when the file does not exist", () => {
|
||||
expect(
|
||||
readManifestSource("/nonexistent/path/feature.manifest.ts"),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the file is unreadable as a manifest (no name field)", () => {
|
||||
const { filepath } = writeTempFile(
|
||||
"feature.manifest.ts",
|
||||
`export const x = 1;`,
|
||||
);
|
||||
expect(readManifestSource(filepath)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("manifestPathForFeature", () => {
|
||||
it("returns the canonical manifest path for a feature root", () => {
|
||||
expect(manifestPathForFeature("/repo/packages/auth")).toBe(
|
||||
path.join("/repo/packages/auth", "src", "feature.manifest.ts"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("featureRootForFile", () => {
|
||||
it("returns the package root containing a use-case file", () => {
|
||||
const file =
|
||||
"/repo/packages/auth/src/application/use-cases/sign-in.use-case.ts";
|
||||
expect(featureRootForFile(file, "/repo")).toBe("/repo/packages/auth");
|
||||
});
|
||||
|
||||
it("returns null for files outside the packages tree", () => {
|
||||
const file = "/repo/apps/web-next/src/app/page.tsx";
|
||||
expect(featureRootForFile(file, "/repo")).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
18
packages/core-eslint/rules/_rule-context.js
Normal file
18
packages/core-eslint/rules/_rule-context.js
Normal file
@@ -0,0 +1,18 @@
|
||||
import { useCaseNameFromFile } from "./_usecase-name.js";
|
||||
import { featureRootForFile } from "./_manifest-source.js";
|
||||
|
||||
/**
|
||||
* Resolves the rule execution context from an ESLint context object.
|
||||
* Returns null when the file is not a use-case file or not inside a
|
||||
* recognised feature package — callers should return {} immediately.
|
||||
*/
|
||||
export function resolveRuleContext(context) {
|
||||
const opts = context.options[0] ?? {};
|
||||
const repoRoot = opts.repoRoot ?? context.cwd ?? process.cwd();
|
||||
const filename = context.filename;
|
||||
const useCaseName = useCaseNameFromFile(filename);
|
||||
if (!useCaseName) return null;
|
||||
const featureRoot = featureRootForFile(filename, repoRoot);
|
||||
if (!featureRoot) return null;
|
||||
return { useCaseName, featureRoot, repoRoot };
|
||||
}
|
||||
8
packages/core-eslint/rules/_rule-schema.js
Normal file
8
packages/core-eslint/rules/_rule-schema.js
Normal file
@@ -0,0 +1,8 @@
|
||||
/** Shared repoRoot option schema used by conformance rules that need to locate feature roots. */
|
||||
export const repoRootSchema = [
|
||||
{
|
||||
type: "object",
|
||||
properties: { repoRoot: { type: "string" } },
|
||||
additionalProperties: false,
|
||||
},
|
||||
];
|
||||
23
packages/core-eslint/rules/_usecase-name.js
Normal file
23
packages/core-eslint/rules/_usecase-name.js
Normal file
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Derive the manifest use-case key from a use-case file path.
|
||||
*
|
||||
* Convention: `packages/<feature>/src/application/use-cases/<kebab-slug>.use-case.ts`
|
||||
* → manifest.useCases.<camelCaseSlug>
|
||||
*
|
||||
* Returns null for non-use-case files.
|
||||
*/
|
||||
export function useCaseNameFromFile(filepath) {
|
||||
if (!filepath.endsWith(".use-case.ts")) return null;
|
||||
if (
|
||||
!filepath.includes("/application/use-cases/") &&
|
||||
!filepath.includes("\\application\\use-cases\\")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const base = filepath.split(/[\\/]/).pop();
|
||||
const slug = base.replace(/\.use-case\.ts$/, "");
|
||||
return slug
|
||||
.split("-")
|
||||
.map((part, i) => (i === 0 ? part : part[0].toUpperCase() + part.slice(1)))
|
||||
.join("");
|
||||
}
|
||||
37
packages/core-eslint/rules/_usecase-name.test.js
Normal file
37
packages/core-eslint/rules/_usecase-name.test.js
Normal file
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { useCaseNameFromFile } from "./_usecase-name.js";
|
||||
|
||||
describe("useCaseNameFromFile", () => {
|
||||
it("converts kebab-case slug to camelCase", () => {
|
||||
expect(
|
||||
useCaseNameFromFile(
|
||||
"/repo/packages/auth/src/application/use-cases/sign-in.use-case.ts",
|
||||
),
|
||||
).toBe("signIn");
|
||||
expect(
|
||||
useCaseNameFromFile(
|
||||
"/repo/packages/auth/src/application/use-cases/sign-up.use-case.ts",
|
||||
),
|
||||
).toBe("signUp");
|
||||
expect(
|
||||
useCaseNameFromFile(
|
||||
"/repo/packages/blog/src/application/use-cases/get-article-by-slug.use-case.ts",
|
||||
),
|
||||
).toBe("getArticleBySlug");
|
||||
});
|
||||
|
||||
it("handles single-word slugs", () => {
|
||||
expect(
|
||||
useCaseNameFromFile(
|
||||
"/repo/packages/x/src/application/use-cases/login.use-case.ts",
|
||||
),
|
||||
).toBe("login");
|
||||
});
|
||||
|
||||
it("returns null for non-use-case files", () => {
|
||||
expect(useCaseNameFromFile("/repo/packages/auth/src/index.ts")).toBeNull();
|
||||
expect(
|
||||
useCaseNameFromFile("/repo/packages/auth/src/feature.manifest.ts"),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
28
packages/core-eslint/rules/_workspace.js
Normal file
28
packages/core-eslint/rules/_workspace.js
Normal file
@@ -0,0 +1,28 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* Reads the `packages:` list from `pnpm-workspace.yaml` at the given repo
|
||||
* root. Returns an array of package glob strings (e.g. ["apps/*", "packages/*"]).
|
||||
* Returns [] when the file is missing or has no `packages:` key.
|
||||
*
|
||||
* Uses regex extraction over YAML parsing to avoid a `js-yaml` dependency;
|
||||
* the `packages:` block in pnpm-workspace.yaml has a stable, well-known
|
||||
* shape and this approach is sufficient.
|
||||
*/
|
||||
export function readWorkspacePackages(repoRoot) {
|
||||
const yamlPath = path.join(repoRoot, "pnpm-workspace.yaml");
|
||||
let src;
|
||||
try {
|
||||
src = fs.readFileSync(yamlPath, "utf8");
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const blockMatch = src.match(/^packages:\s*\n((?:\s+-\s+.+\n?)+)/m);
|
||||
if (!blockMatch) return [];
|
||||
return blockMatch[1]
|
||||
.split("\n")
|
||||
.map((line) => line.match(/^\s+-\s+"?([^"]+?)"?\s*$/))
|
||||
.filter((m) => m !== null)
|
||||
.map((m) => m[1]);
|
||||
}
|
||||
34
packages/core-eslint/rules/_workspace.test.js
Normal file
34
packages/core-eslint/rules/_workspace.test.js
Normal file
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import { readWorkspacePackages } from "./_workspace.js";
|
||||
|
||||
function writeWorkspaceYaml(contents) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "workspace-"));
|
||||
const filepath = path.join(dir, "pnpm-workspace.yaml");
|
||||
fs.writeFileSync(filepath, contents);
|
||||
return { dir, filepath };
|
||||
}
|
||||
|
||||
describe("_workspace", () => {
|
||||
it("returns the list of declared package globs", () => {
|
||||
const { dir } = writeWorkspaceYaml(
|
||||
`packages:
|
||||
- "apps/*"
|
||||
- "packages/*"
|
||||
`,
|
||||
);
|
||||
expect(readWorkspacePackages(dir)).toEqual(["apps/*", "packages/*"]);
|
||||
});
|
||||
|
||||
it("returns [] when pnpm-workspace.yaml is missing", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "workspace-"));
|
||||
expect(readWorkspacePackages(dir)).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns [] when packages key is absent", () => {
|
||||
const { dir } = writeWorkspaceYaml(`# empty\n`);
|
||||
expect(readWorkspacePackages(dir)).toEqual([]);
|
||||
});
|
||||
});
|
||||
47
packages/core-eslint/rules/atomic-tier-import-direction.js
Normal file
47
packages/core-eslint/rules/atomic-tier-import-direction.js
Normal file
@@ -0,0 +1,47 @@
|
||||
const TIERS = ["atoms", "molecules", "organisms", "templates", "pages"];
|
||||
|
||||
function tierOf(filepath) {
|
||||
for (let i = 0; i < TIERS.length; i++) {
|
||||
const tier = TIERS[i];
|
||||
if (filepath.includes(`/${tier}/`) || filepath.includes(`\\${tier}\\`)) {
|
||||
return { name: tier, index: i };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Atomic-design tier imports respect direction: atoms ← molecules ← organisms ← templates ← pages.",
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
wrongDirection:
|
||||
"{{fromTier}} cannot import from {{toTier}} ({{importPath}}). Tier direction: atoms ← molecules ← organisms ← templates ← pages.",
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const filename = context.filename;
|
||||
const from = tierOf(filename);
|
||||
if (!from) return {};
|
||||
return {
|
||||
ImportDeclaration(node) {
|
||||
const source = node.source.value;
|
||||
if (typeof source !== "string") return;
|
||||
const to = tierOf(source);
|
||||
if (!to) return;
|
||||
if (to.index > from.index) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "wrongDirection",
|
||||
data: { fromTier: from.name, toTier: to.name, importPath: source },
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import rule from "./atomic-tier-import-direction.js";
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: {
|
||||
parser: await import("@typescript-eslint/parser"),
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
parserOptions: { ecmaFeatures: { jsx: true } },
|
||||
},
|
||||
});
|
||||
|
||||
describe("atomic-tier-import-direction", () => {
|
||||
it("passes when an organism imports from atoms", () => {
|
||||
tester.run("atomic-tier-import-direction", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: "/repo/packages/core-ui/src/organisms/Card/Card.tsx",
|
||||
code: `import { Button } from "../../atoms/Button/Button";`,
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when an atom imports from organisms", () => {
|
||||
tester.run("atomic-tier-import-direction", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: "/repo/packages/core-ui/src/atoms/Button/Button.tsx",
|
||||
code: `import { Card } from "../../organisms/Card/Card";`,
|
||||
errors: [
|
||||
{
|
||||
messageId: "wrongDirection",
|
||||
data: {
|
||||
fromTier: "atoms",
|
||||
toTier: "organisms",
|
||||
importPath: "../../organisms/Card/Card",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op for files outside any tier folder", () => {
|
||||
tester.run("atomic-tier-import-direction", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename:
|
||||
"/repo/packages/auth/src/application/use-cases/sign-in.use-case.ts",
|
||||
code: `export const x = 1;`,
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("passes for same-tier imports", () => {
|
||||
tester.run("atomic-tier-import-direction", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename:
|
||||
"/repo/packages/core-ui/src/molecules/SearchBar/SearchBar.tsx",
|
||||
code: `import { FormField } from "../FormField/FormField";`,
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
59
packages/core-eslint/rules/component-must-have-story.js
Normal file
59
packages/core-eslint/rules/component-must-have-story.js
Normal file
@@ -0,0 +1,59 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* Identifies "component files" by location + extension:
|
||||
* - `.tsx` extension
|
||||
* - Inside `packages/core-ui/src/` OR `packages/<feature>/src/ui/`
|
||||
* - NOT a test, stories, spec, or barrel file
|
||||
*/
|
||||
function isComponentFile(filename) {
|
||||
if (!filename.endsWith(".tsx")) return false;
|
||||
const base = path.basename(filename);
|
||||
if (
|
||||
base === "index.tsx" ||
|
||||
base.endsWith(".test.tsx") ||
|
||||
base.endsWith(".stories.tsx") ||
|
||||
base.endsWith(".spec.tsx")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
filename.includes("/packages/core-ui/src/") ||
|
||||
/\/packages\/[^/]+\/src\/ui\//.test(filename)
|
||||
);
|
||||
}
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Every component file must have a sibling *.stories.tsx for Storybook coverage.",
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
missingStory:
|
||||
"Component {{filename}} has no sibling Storybook story at {{expected}}. Stories are the spec for visual conformance.",
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
return {
|
||||
Program(node) {
|
||||
const filename = context.filename;
|
||||
if (!isComponentFile(filename)) return;
|
||||
const expected = filename.replace(/\.tsx$/, ".stories.tsx");
|
||||
if (fs.existsSync(expected)) return;
|
||||
context.report({
|
||||
node,
|
||||
messageId: "missingStory",
|
||||
data: {
|
||||
filename: path.basename(filename),
|
||||
expected: path.basename(expected),
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
110
packages/core-eslint/rules/component-must-have-story.test.js
Normal file
110
packages/core-eslint/rules/component-must-have-story.test.js
Normal file
@@ -0,0 +1,110 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./component-must-have-story.js";
|
||||
|
||||
function makeFixture({ withStory, location = "core-ui" }) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "cmhs-"));
|
||||
const dir =
|
||||
location === "core-ui"
|
||||
? path.join(root, "packages", "core-ui", "src", "atoms", "Button")
|
||||
: path.join(root, "packages", "demo", "src", "ui", "atoms", "Button");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const component = path.join(dir, "Button.tsx");
|
||||
fs.writeFileSync(
|
||||
component,
|
||||
`export const Button = () => <button>x</button>;`,
|
||||
);
|
||||
if (withStory) {
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "Button.stories.tsx"),
|
||||
`export default { title: "Button" };`,
|
||||
);
|
||||
}
|
||||
return { component };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: {
|
||||
parser: await import("@typescript-eslint/parser"),
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
parserOptions: { ecmaFeatures: { jsx: true } },
|
||||
},
|
||||
});
|
||||
|
||||
describe("component-must-have-story", () => {
|
||||
it("passes for a core-ui component with a sibling .stories.tsx", () => {
|
||||
const { component } = makeFixture({ withStory: true });
|
||||
tester.run("component-must-have-story", rule, {
|
||||
valid: [
|
||||
{ filename: component, code: fs.readFileSync(component, "utf8") },
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires for a core-ui component without a sibling .stories.tsx", () => {
|
||||
const { component } = makeFixture({ withStory: false });
|
||||
tester.run("component-must-have-story", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: component,
|
||||
code: fs.readFileSync(component, "utf8"),
|
||||
errors: [{ messageId: "missingStory" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("passes for a feature ui component with a sibling .stories.tsx", () => {
|
||||
const { component } = makeFixture({ withStory: true, location: "feature" });
|
||||
tester.run("component-must-have-story", rule, {
|
||||
valid: [
|
||||
{ filename: component, code: fs.readFileSync(component, "utf8") },
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op for index.tsx", () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "cmhs-"));
|
||||
const dir = path.join(
|
||||
root,
|
||||
"packages",
|
||||
"core-ui",
|
||||
"src",
|
||||
"atoms",
|
||||
"Button",
|
||||
);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const file = path.join(dir, "index.tsx");
|
||||
fs.writeFileSync(file, `export * from "./Button";`);
|
||||
tester.run("component-must-have-story", rule, {
|
||||
valid: [{ filename: file, code: fs.readFileSync(file, "utf8") }],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op for files outside packages/core-ui/ and packages/*/src/ui/", () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "cmhs-"));
|
||||
const dir = path.join(
|
||||
root,
|
||||
"packages",
|
||||
"auth",
|
||||
"src",
|
||||
"application",
|
||||
"use-cases",
|
||||
);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const file = path.join(dir, "sign-in.use-case.tsx");
|
||||
fs.writeFileSync(file, `export const x = 1;`);
|
||||
tester.run("component-must-have-story", rule, {
|
||||
valid: [{ filename: file, code: fs.readFileSync(file, "utf8") }],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
53
packages/core-eslint/rules/component-must-have-test.js
Normal file
53
packages/core-eslint/rules/component-must-have-test.js
Normal file
@@ -0,0 +1,53 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
function isComponentFile(filename) {
|
||||
if (!filename.endsWith(".tsx")) return false;
|
||||
const base = path.basename(filename);
|
||||
if (
|
||||
base === "index.tsx" ||
|
||||
base.endsWith(".test.tsx") ||
|
||||
base.endsWith(".stories.tsx") ||
|
||||
base.endsWith(".spec.tsx")
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
filename.includes("/packages/core-ui/src/") ||
|
||||
/\/packages\/[^/]+\/src\/ui\//.test(filename)
|
||||
);
|
||||
}
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Every component file must have a sibling *.test.tsx for behavioural coverage.",
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
missingTest:
|
||||
"Component {{filename}} has no sibling test at {{expected}}. Write the red test first.",
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
return {
|
||||
Program(node) {
|
||||
const filename = context.filename;
|
||||
if (!isComponentFile(filename)) return;
|
||||
const expected = filename.replace(/\.tsx$/, ".test.tsx");
|
||||
if (fs.existsSync(expected)) return;
|
||||
context.report({
|
||||
node,
|
||||
messageId: "missingTest",
|
||||
data: {
|
||||
filename: path.basename(filename),
|
||||
expected: path.basename(expected),
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
59
packages/core-eslint/rules/component-must-have-test.test.js
Normal file
59
packages/core-eslint/rules/component-must-have-test.test.js
Normal file
@@ -0,0 +1,59 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./component-must-have-test.js";
|
||||
|
||||
function makeFixture({ withTest }) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "cmht-"));
|
||||
const dir = path.join(root, "packages", "core-ui", "src", "atoms", "Button");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const component = path.join(dir, "Button.tsx");
|
||||
fs.writeFileSync(
|
||||
component,
|
||||
`export const Button = () => <button>x</button>;`,
|
||||
);
|
||||
if (withTest) {
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "Button.test.tsx"),
|
||||
`import { it } from "vitest"; it("works", () => {});`,
|
||||
);
|
||||
}
|
||||
return { component };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: {
|
||||
parser: await import("@typescript-eslint/parser"),
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
parserOptions: { ecmaFeatures: { jsx: true } },
|
||||
},
|
||||
});
|
||||
|
||||
describe("component-must-have-test", () => {
|
||||
it("passes when sibling .test.tsx exists", () => {
|
||||
const { component } = makeFixture({ withTest: true });
|
||||
tester.run("component-must-have-test", rule, {
|
||||
valid: [
|
||||
{ filename: component, code: fs.readFileSync(component, "utf8") },
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when no sibling .test.tsx exists", () => {
|
||||
const { component } = makeFixture({ withTest: false });
|
||||
tester.run("component-must-have-test", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: component,
|
||||
code: fs.readFileSync(component, "utf8"),
|
||||
errors: [{ messageId: "missingTest" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
55
packages/core-eslint/rules/entity-must-have-test.js
Normal file
55
packages/core-eslint/rules/entity-must-have-test.js
Normal file
@@ -0,0 +1,55 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* Entity models (`entities/models/<x>.ts`) are pure domain logic — schemas,
|
||||
* invariants, derivations. They are the cheapest layer to test and the most
|
||||
* expensive to get wrong, so every model file must carry a sibling test.
|
||||
*
|
||||
* Scope is `entities/models/` only. Error classes (`entities/errors/`) are
|
||||
* conventionally covered by a consolidated `errors.test.ts`, and barrels
|
||||
* (`index.ts`) hold no logic — both are excluded.
|
||||
*/
|
||||
function isEntityModelFile(filename) {
|
||||
const normalized = filename.replace(/\\/g, "/");
|
||||
if (!normalized.includes("/entities/models/")) return false;
|
||||
if (!normalized.endsWith(".ts")) return false;
|
||||
if (normalized.endsWith(".test.ts")) return false;
|
||||
if (normalized.endsWith(".d.ts")) return false;
|
||||
if (normalized.endsWith("/index.ts")) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Every entity model file (entities/models/<x>.ts) must have a sibling <x>.test.ts.",
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
missingTest:
|
||||
"Entity model {{filename}} has no sibling test at {{expected}}. Entity models are pure domain logic — cover them with a unit test.",
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
return {
|
||||
Program(node) {
|
||||
const filename = context.filename;
|
||||
if (!isEntityModelFile(filename)) return;
|
||||
const expected = filename.replace(/\.ts$/, ".test.ts");
|
||||
if (fs.existsSync(expected)) return;
|
||||
context.report({
|
||||
node,
|
||||
messageId: "missingTest",
|
||||
data: {
|
||||
filename: path.basename(filename),
|
||||
expected: path.basename(expected),
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
74
packages/core-eslint/rules/entity-must-have-test.test.js
Normal file
74
packages/core-eslint/rules/entity-must-have-test.test.js
Normal file
@@ -0,0 +1,74 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./entity-must-have-test.js";
|
||||
|
||||
function makeModelsDir() {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "emht-"));
|
||||
const modelsDir = path.join(dir, "src", "entities", "models");
|
||||
fs.mkdirSync(modelsDir, { recursive: true });
|
||||
return modelsDir;
|
||||
}
|
||||
|
||||
function makeEntityFixture({ withTest }) {
|
||||
const modelsDir = makeModelsDir();
|
||||
const entity = path.join(modelsDir, "cookie.ts");
|
||||
fs.writeFileSync(entity, `export const cookie = {};`);
|
||||
if (withTest) {
|
||||
fs.writeFileSync(
|
||||
path.join(modelsDir, "cookie.test.ts"),
|
||||
`import { it } from "vitest"; it("works", () => {});`,
|
||||
);
|
||||
}
|
||||
return { entity };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: { ecmaVersion: "latest", sourceType: "module" },
|
||||
});
|
||||
|
||||
describe("entity-must-have-test", () => {
|
||||
it("passes when a sibling .test.ts exists", () => {
|
||||
const { entity } = makeEntityFixture({ withTest: true });
|
||||
tester.run("entity-must-have-test", rule, {
|
||||
valid: [{ filename: entity, code: fs.readFileSync(entity, "utf8") }],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when no sibling test file exists", () => {
|
||||
const { entity } = makeEntityFixture({ withTest: false });
|
||||
tester.run("entity-must-have-test", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: entity,
|
||||
code: fs.readFileSync(entity, "utf8"),
|
||||
errors: [{ messageId: "missingTest" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores files outside entities/models", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "emht-"));
|
||||
const other = path.join(dir, "helper.ts");
|
||||
fs.writeFileSync(other, `export const x = 1;`);
|
||||
tester.run("entity-must-have-test", rule, {
|
||||
valid: [{ filename: other, code: "export const x = 1;" }],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores the index.ts barrel inside entities/models", () => {
|
||||
const modelsDir = makeModelsDir();
|
||||
const index = path.join(modelsDir, "index.ts");
|
||||
fs.writeFileSync(index, `export {};`);
|
||||
tester.run("entity-must-have-test", rule, {
|
||||
valid: [{ filename: index, code: "export {};" }],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
55
packages/core-eslint/rules/feature-must-have-manifest.js
Normal file
55
packages/core-eslint/rules/feature-must-have-manifest.js
Normal file
@@ -0,0 +1,55 @@
|
||||
import fs from "node:fs";
|
||||
import {
|
||||
manifestPathForFeature,
|
||||
featureRootForFile,
|
||||
} from "./_manifest-source.js";
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Every feature with use-case files must declare a feature.manifest.ts at its src/ root.",
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
repoRoot: { type: "string" },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
messages: {
|
||||
missingManifest:
|
||||
"Feature {{feature}} has use cases but no feature.manifest.ts. Run `pnpm turbo gen feature {{feature}}` or scaffold the manifest manually at {{expected}}.",
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const opts = context.options[0] ?? {};
|
||||
const repoRoot = opts.repoRoot ?? context.cwd ?? process.cwd();
|
||||
return {
|
||||
Program(node) {
|
||||
const filename = context.filename;
|
||||
const featureRoot = featureRootForFile(filename, repoRoot);
|
||||
if (!featureRoot) return;
|
||||
// Only check use-case files
|
||||
if (
|
||||
!filename.includes("/application/use-cases/") ||
|
||||
!filename.endsWith(".use-case.ts")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const manifestPath = manifestPathForFeature(featureRoot);
|
||||
if (fs.existsSync(manifestPath)) return;
|
||||
const featureName = featureRoot.split("/").pop();
|
||||
context.report({
|
||||
node,
|
||||
messageId: "missingManifest",
|
||||
data: { feature: featureName, expected: manifestPath },
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./feature-must-have-manifest.js";
|
||||
|
||||
function makeFeatureFixture({ withManifest }) {
|
||||
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), "fmm-"));
|
||||
const featureDir = path.join(repoRoot, "packages", "demo");
|
||||
fs.mkdirSync(path.join(featureDir, "src", "application", "use-cases"), {
|
||||
recursive: true,
|
||||
});
|
||||
if (withManifest) {
|
||||
fs.writeFileSync(
|
||||
path.join(featureDir, "src", "feature.manifest.ts"),
|
||||
`export const demoManifest = defineFeature({ name: "demo", requiredCores: [], useCases: {}, realtimeChannels: [], jobs: [] } as const);`,
|
||||
);
|
||||
}
|
||||
const useCaseFile = path.join(
|
||||
featureDir,
|
||||
"src",
|
||||
"application",
|
||||
"use-cases",
|
||||
"do-thing.use-case.ts",
|
||||
);
|
||||
fs.writeFileSync(
|
||||
useCaseFile,
|
||||
`export const doThingUseCase = () => async () => {};`,
|
||||
);
|
||||
return { repoRoot, useCaseFile };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: { ecmaVersion: "latest", sourceType: "module" },
|
||||
});
|
||||
|
||||
describe("feature-must-have-manifest", () => {
|
||||
it("passes when the feature has a manifest", () => {
|
||||
const { repoRoot, useCaseFile } = makeFeatureFixture({
|
||||
withManifest: true,
|
||||
});
|
||||
tester.run("feature-must-have-manifest", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when the feature has no manifest", () => {
|
||||
const { repoRoot, useCaseFile } = makeFeatureFixture({
|
||||
withManifest: false,
|
||||
});
|
||||
tester.run("feature-must-have-manifest", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
errors: [{ messageId: "missingManifest" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Feature test files import from `src/` through the `@/` alias, never via
|
||||
* `../` parent traversal (CLAUDE.md "Key Conventions"). A `../` import in a
|
||||
* test file is always reaching across `src/` directories — `@/` keeps those
|
||||
* imports stable under file moves and makes the test's dependencies legible.
|
||||
*
|
||||
* Scoped to feature packages (`packages/<name>/src/`, excluding `core-*`):
|
||||
* the convention is part of the feature template's contract. Core packages
|
||||
* are generated and governed by their own templates, and tooling packages
|
||||
* (turbo/generators, scripts) legitimately use relative paths.
|
||||
*/
|
||||
function isFeatureSrcTestFile(filename) {
|
||||
const normalized = filename.replace(/\\/g, "/");
|
||||
if (!normalized.endsWith(".test.ts") && !normalized.endsWith(".test.tsx")) {
|
||||
return false;
|
||||
}
|
||||
return /\/packages\/(?!core-)[^/]+\/src\//.test(normalized);
|
||||
}
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Feature test files must import src modules via the @/ alias, not ../ parent paths.",
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
relativeParentImport:
|
||||
'Test file imports "{{source}}" with a ../ parent path. Use the "@/" alias for src imports (e.g. "@/application/...").',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
if (!isFeatureSrcTestFile(context.filename)) return {};
|
||||
return {
|
||||
ImportDeclaration(node) {
|
||||
const source = node.source.value;
|
||||
if (typeof source === "string" && source.startsWith("../")) {
|
||||
context.report({
|
||||
node: node.source,
|
||||
messageId: "relativeParentImport",
|
||||
data: { source },
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import rule from "./no-relative-parent-import-in-tests.js";
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: { ecmaVersion: "latest", sourceType: "module" },
|
||||
});
|
||||
|
||||
const featureTest = "/repo/packages/auth/src/di/container.test.ts";
|
||||
const featureSrc = "/repo/packages/auth/src/di/container.ts";
|
||||
const coreTest = "/repo/packages/core-audit/src/di/bind-audit.test.ts";
|
||||
|
||||
describe("no-relative-parent-import-in-tests", () => {
|
||||
it("passes when a feature test uses the @/ alias", () => {
|
||||
tester.run("no-relative-parent-import-in-tests", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: featureTest,
|
||||
code: `import { x } from "@/infrastructure/x";`,
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("passes for same-directory ./ imports", () => {
|
||||
tester.run("no-relative-parent-import-in-tests", rule, {
|
||||
valid: [
|
||||
{ filename: featureTest, code: `import { x } from "./container";` },
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when a feature test imports via ../", () => {
|
||||
tester.run("no-relative-parent-import-in-tests", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: featureTest,
|
||||
code: `import { x } from "../infrastructure/x";`,
|
||||
errors: [
|
||||
{
|
||||
messageId: "relativeParentImport",
|
||||
data: { source: "../infrastructure/x" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores ../ imports in non-test source files", () => {
|
||||
tester.run("no-relative-parent-import-in-tests", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: featureSrc,
|
||||
code: `import { x } from "../infrastructure/x";`,
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores core-package test files (governed by their own templates)", () => {
|
||||
tester.run("no-relative-parent-import-in-tests", rule, {
|
||||
valid: [
|
||||
{ filename: coreTest, code: `import { x } from "../noop-audit-log";` },
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
51
packages/core-eslint/rules/no-undeclared-analytics-event.js
Normal file
51
packages/core-eslint/rules/no-undeclared-analytics-event.js
Normal file
@@ -0,0 +1,51 @@
|
||||
import { parseManifestUseCases } from "./_manifest-ast.js";
|
||||
import { manifestPathForFeature } from "./_manifest-source.js";
|
||||
import { repoRootSchema } from "./_rule-schema.js";
|
||||
import { resolveRuleContext } from "./_rule-context.js";
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
'analytics.track("X") inside a use-case factory must declare X in manifest.useCases[name].analyticsEvents.',
|
||||
},
|
||||
schema: repoRootSchema,
|
||||
messages: {
|
||||
undeclared:
|
||||
'{{useCase}} calls analytics.track("{{event}}") but {{event}} is not declared in manifest.useCases.{{useCase}}.analyticsEvents. Add it to the manifest or remove the call.',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const rc = resolveRuleContext(context);
|
||||
if (!rc) return {};
|
||||
const { useCaseName, featureRoot } = rc;
|
||||
const manifest = parseManifestUseCases(manifestPathForFeature(featureRoot));
|
||||
if (!manifest || !manifest[useCaseName]) return {};
|
||||
const declared = new Set(manifest[useCaseName].analyticsEvents ?? []);
|
||||
return {
|
||||
CallExpression(node) {
|
||||
if (
|
||||
node.callee.type === "MemberExpression" &&
|
||||
node.callee.object.type === "Identifier" &&
|
||||
node.callee.object.name === "analytics" &&
|
||||
node.callee.property.type === "Identifier" &&
|
||||
node.callee.property.name === "track" &&
|
||||
node.arguments.length > 0 &&
|
||||
node.arguments[0].type === "Literal" &&
|
||||
typeof node.arguments[0].value === "string"
|
||||
) {
|
||||
const event = node.arguments[0].value;
|
||||
if (!declared.has(event)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "undeclared",
|
||||
data: { event, useCase: useCaseName },
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
155
packages/core-eslint/rules/no-undeclared-analytics-event.test.js
Normal file
155
packages/core-eslint/rules/no-undeclared-analytics-event.test.js
Normal file
@@ -0,0 +1,155 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./no-undeclared-analytics-event.js";
|
||||
|
||||
function makeFixture({ manifestUseCases, useCaseBody }) {
|
||||
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nuae-"));
|
||||
const featureDir = path.join(repoRoot, "packages", "demo");
|
||||
fs.mkdirSync(path.join(featureDir, "src", "application", "use-cases"), {
|
||||
recursive: true,
|
||||
});
|
||||
const useCasesObj = Object.entries(manifestUseCases)
|
||||
.map(
|
||||
([name, uc]) =>
|
||||
` ${name}: { mutates: ${uc.mutates}, audits: [], publishes: [], consumes: [], analyticsEvents: [${uc.analyticsEvents.map((e) => `"${e}"`).join(", ")}] },`,
|
||||
)
|
||||
.join("\n");
|
||||
fs.writeFileSync(
|
||||
path.join(featureDir, "src", "feature.manifest.ts"),
|
||||
`export const demoManifest = defineFeature({
|
||||
name: "demo",
|
||||
requiredCores: [],
|
||||
useCases: {
|
||||
${useCasesObj}
|
||||
},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`,
|
||||
);
|
||||
const useCaseFile = path.join(
|
||||
featureDir,
|
||||
"src",
|
||||
"application",
|
||||
"use-cases",
|
||||
"sign-up.use-case.ts",
|
||||
);
|
||||
fs.writeFileSync(useCaseFile, useCaseBody);
|
||||
return { repoRoot, useCaseFile };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: {
|
||||
parser: await import("@typescript-eslint/parser"),
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
},
|
||||
});
|
||||
|
||||
describe("no-undeclared-analytics-event", () => {
|
||||
it("passes when analytics.track slug matches manifest analyticsEvents[]", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: {
|
||||
signUp: { mutates: true, analyticsEvents: ["user.signed-up"] },
|
||||
},
|
||||
useCaseBody: `export const signUpUseCase = (analytics) => async () => { analytics.track("user.signed-up", {}); };`,
|
||||
});
|
||||
tester.run("no-undeclared-analytics-event", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when analytics.track slug is not in manifest", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: { signUp: { mutates: true, analyticsEvents: [] } },
|
||||
useCaseBody: `export const signUpUseCase = (analytics) => async () => { analytics.track("user.signed-up", {}); };`,
|
||||
});
|
||||
tester.run("no-undeclared-analytics-event", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
errors: [
|
||||
{
|
||||
messageId: "undeclared",
|
||||
data: { event: "user.signed-up", useCase: "signUp" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op when analytics.track is called with a non-literal argument", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: { signUp: { mutates: true, analyticsEvents: [] } },
|
||||
useCaseBody: `export const signUpUseCase = (analytics, slug) => async () => { analytics.track(slug, {}); };`,
|
||||
});
|
||||
tester.run("no-undeclared-analytics-event", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op for files that are not use-case files", () => {
|
||||
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nuae-"));
|
||||
const featureDir = path.join(repoRoot, "packages", "demo");
|
||||
fs.mkdirSync(path.join(featureDir, "src", "application"), {
|
||||
recursive: true,
|
||||
});
|
||||
const controllerFile = path.join(
|
||||
featureDir,
|
||||
"src",
|
||||
"application",
|
||||
"sign-up.controller.ts",
|
||||
);
|
||||
fs.writeFileSync(
|
||||
controllerFile,
|
||||
`export const signUpController = (analytics) => async () => { analytics.track("user.signed-up", {}); };`,
|
||||
);
|
||||
tester.run("no-undeclared-analytics-event", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: controllerFile,
|
||||
code: fs.readFileSync(controllerFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op when manifest has no entry for the use case", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: {},
|
||||
useCaseBody: `export const signUpUseCase = (analytics) => async () => { analytics.track("user.signed-up", {}); };`,
|
||||
});
|
||||
tester.run("no-undeclared-analytics-event", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
62
packages/core-eslint/rules/no-undeclared-audit.js
Normal file
62
packages/core-eslint/rules/no-undeclared-audit.js
Normal file
@@ -0,0 +1,62 @@
|
||||
import { parseManifestUseCases } from "./_manifest-ast.js";
|
||||
import { manifestPathForFeature } from "./_manifest-source.js";
|
||||
import { repoRootSchema } from "./_rule-schema.js";
|
||||
import { resolveRuleContext } from "./_rule-context.js";
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
'auditLog.record({ type: "X" }) inside a use-case factory must declare X in manifest.useCases[name].audits.',
|
||||
},
|
||||
schema: repoRootSchema,
|
||||
messages: {
|
||||
undeclared:
|
||||
'{{useCase}} calls auditLog.record with type "{{event}}" but {{event}} is not declared in manifest.useCases.{{useCase}}.audits. Add it to the manifest or remove the call.',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const rc = resolveRuleContext(context);
|
||||
if (!rc) return {};
|
||||
const { useCaseName, featureRoot } = rc;
|
||||
const manifest = parseManifestUseCases(manifestPathForFeature(featureRoot));
|
||||
if (!manifest || !manifest[useCaseName]) return {};
|
||||
const declared = new Set(manifest[useCaseName].audits);
|
||||
return {
|
||||
CallExpression(node) {
|
||||
if (
|
||||
node.callee.type === "MemberExpression" &&
|
||||
node.callee.object.type === "Identifier" &&
|
||||
node.callee.object.name === "auditLog" &&
|
||||
node.callee.property.type === "Identifier" &&
|
||||
node.callee.property.name === "record" &&
|
||||
node.arguments.length > 0 &&
|
||||
node.arguments[0].type === "ObjectExpression"
|
||||
) {
|
||||
const typeProp = node.arguments[0].properties.find(
|
||||
(p) =>
|
||||
p.type === "Property" &&
|
||||
p.key.type === "Identifier" &&
|
||||
p.key.name === "type",
|
||||
);
|
||||
if (
|
||||
typeProp &&
|
||||
typeProp.value.type === "Literal" &&
|
||||
typeof typeProp.value.value === "string"
|
||||
) {
|
||||
const event = typeProp.value.value;
|
||||
if (!declared.has(event)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "undeclared",
|
||||
data: { event, useCase: useCaseName },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
108
packages/core-eslint/rules/no-undeclared-audit.test.js
Normal file
108
packages/core-eslint/rules/no-undeclared-audit.test.js
Normal file
@@ -0,0 +1,108 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./no-undeclared-audit.js";
|
||||
|
||||
function makeFixture({ manifestUseCases, useCaseBody }) {
|
||||
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nua-"));
|
||||
const featureDir = path.join(repoRoot, "packages", "demo");
|
||||
fs.mkdirSync(path.join(featureDir, "src", "application", "use-cases"), {
|
||||
recursive: true,
|
||||
});
|
||||
const useCasesObj = Object.entries(manifestUseCases)
|
||||
.map(
|
||||
([name, uc]) =>
|
||||
` ${name}: { mutates: ${uc.mutates}, audits: [${uc.audits.map((a) => `"${a}"`).join(", ")}], publishes: [], consumes: [] },`,
|
||||
)
|
||||
.join("\n");
|
||||
fs.writeFileSync(
|
||||
path.join(featureDir, "src", "feature.manifest.ts"),
|
||||
`export const demoManifest = defineFeature({
|
||||
name: "demo",
|
||||
requiredCores: [],
|
||||
useCases: {
|
||||
${useCasesObj}
|
||||
},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`,
|
||||
);
|
||||
const useCaseFile = path.join(
|
||||
featureDir,
|
||||
"src",
|
||||
"application",
|
||||
"use-cases",
|
||||
"sign-up.use-case.ts",
|
||||
);
|
||||
fs.writeFileSync(useCaseFile, useCaseBody);
|
||||
return { repoRoot, useCaseFile };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: {
|
||||
parser: await import("@typescript-eslint/parser"),
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
},
|
||||
});
|
||||
|
||||
describe("no-undeclared-audit", () => {
|
||||
it("passes when auditLog.record type matches manifest audits[]", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: { signUp: { mutates: true, audits: ["user.created"] } },
|
||||
useCaseBody: `export const signUpUseCase = (auditLog) => async () => { auditLog.record({ type: "user.created", subject: "x", actor: "y" }); };`,
|
||||
});
|
||||
tester.run("no-undeclared-audit", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when auditLog.record type is not in manifest", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: { signUp: { mutates: true, audits: [] } },
|
||||
useCaseBody: `export const signUpUseCase = (auditLog) => async () => { auditLog.record({ type: "user.created", subject: "x" }); };`,
|
||||
});
|
||||
tester.run("no-undeclared-audit", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
errors: [
|
||||
{
|
||||
messageId: "undeclared",
|
||||
data: { event: "user.created", useCase: "signUp" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op when auditLog.record is called with a non-literal type", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: { signUp: { mutates: true, audits: [] } },
|
||||
useCaseBody: `export const signUpUseCase = (auditLog, type) => async () => { auditLog.record({ type, subject: "x" }); };`,
|
||||
});
|
||||
tester.run("no-undeclared-audit", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
68
packages/core-eslint/rules/no-undeclared-consent-check.js
Normal file
68
packages/core-eslint/rules/no-undeclared-consent-check.js
Normal file
@@ -0,0 +1,68 @@
|
||||
import { parseManifestFully } from "./_manifest-ast.js";
|
||||
import { manifestPathForFeature } from "./_manifest-source.js";
|
||||
import { repoRootSchema } from "./_rule-schema.js";
|
||||
import { resolveRuleContext } from "./_rule-context.js";
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
docs: {
|
||||
description:
|
||||
'consent.isGranted("X") inside a use-case file must match a category declared in manifest.requiresConsent.',
|
||||
},
|
||||
schema: repoRootSchema,
|
||||
messages: {
|
||||
undeclared:
|
||||
'{{useCase}} calls consent.isGranted("{{category}}") but "{{category}}" is not declared in manifest.requiresConsent. Add it to the manifest or remove the call.',
|
||||
unusedDeclaration:
|
||||
"{{useCase}} manifest declares requiresConsent but no consent.isGranted() call found in this file. Add consent checks or clear the manifest declaration.",
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const rc = resolveRuleContext(context);
|
||||
if (!rc) return {};
|
||||
const { useCaseName, featureRoot } = rc;
|
||||
const manifest = parseManifestFully(manifestPathForFeature(featureRoot));
|
||||
if (!manifest) return {};
|
||||
const requiresConsent = manifest.requiresConsent ?? [];
|
||||
if (requiresConsent.length === 0) return {};
|
||||
|
||||
const declared = new Set(requiresConsent);
|
||||
let hasConsentCall = false;
|
||||
|
||||
return {
|
||||
CallExpression(node) {
|
||||
if (
|
||||
node.callee.type === "MemberExpression" &&
|
||||
node.callee.object.type === "Identifier" &&
|
||||
node.callee.object.name === "consent" &&
|
||||
node.callee.property.type === "Identifier" &&
|
||||
node.callee.property.name === "isGranted" &&
|
||||
node.arguments.length > 0 &&
|
||||
node.arguments[0].type === "Literal" &&
|
||||
typeof node.arguments[0].value === "string"
|
||||
) {
|
||||
hasConsentCall = true;
|
||||
const category = node.arguments[0].value;
|
||||
if (!declared.has(category)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "undeclared",
|
||||
data: { category, useCase: useCaseName },
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
"Program:exit"(node) {
|
||||
if (!hasConsentCall) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unusedDeclaration",
|
||||
data: { useCase: useCaseName },
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
132
packages/core-eslint/rules/no-undeclared-consent-check.test.js
Normal file
132
packages/core-eslint/rules/no-undeclared-consent-check.test.js
Normal file
@@ -0,0 +1,132 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./no-undeclared-consent-check.js";
|
||||
|
||||
function makeFixture({ requiresConsent, useCaseBody }) {
|
||||
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nucc-"));
|
||||
const featureDir = path.join(repoRoot, "packages", "demo");
|
||||
fs.mkdirSync(path.join(featureDir, "src", "application", "use-cases"), {
|
||||
recursive: true,
|
||||
});
|
||||
const consentField =
|
||||
requiresConsent.length > 0
|
||||
? ` requiresConsent: [${requiresConsent.map((c) => `"${c}"`).join(", ")}],\n`
|
||||
: "";
|
||||
fs.writeFileSync(
|
||||
path.join(featureDir, "src", "feature.manifest.ts"),
|
||||
`export const demoManifest = defineFeature({
|
||||
name: "demo",
|
||||
requiredCores: [],
|
||||
${consentField} useCases: {
|
||||
checkData: { mutates: false, audits: [], publishes: [], consumes: [] },
|
||||
},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`,
|
||||
);
|
||||
const useCaseFile = path.join(
|
||||
featureDir,
|
||||
"src",
|
||||
"application",
|
||||
"use-cases",
|
||||
"check-data.use-case.ts",
|
||||
);
|
||||
fs.writeFileSync(useCaseFile, useCaseBody);
|
||||
return { repoRoot, useCaseFile };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: {
|
||||
parser: await import("@typescript-eslint/parser"),
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
},
|
||||
});
|
||||
|
||||
describe("no-undeclared-consent-check", () => {
|
||||
it("passes when consent.isGranted category matches manifest requiresConsent", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
requiresConsent: ["analytics"],
|
||||
useCaseBody: `export const checkDataUseCase = (consent) => async () => { if (!consent.isGranted("analytics")) throw new Error(); };`,
|
||||
});
|
||||
tester.run("no-undeclared-consent-check", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when category is undeclared or manifest declaration is unused", () => {
|
||||
const { repoRoot: rootA, useCaseFile: fileA } = makeFixture({
|
||||
requiresConsent: ["analytics"],
|
||||
useCaseBody: `export const checkDataUseCase = (consent) => async () => { if (!consent.isGranted("marketing")) throw new Error(); };`,
|
||||
});
|
||||
const { repoRoot: rootB, useCaseFile: fileB } = makeFixture({
|
||||
requiresConsent: ["analytics"],
|
||||
useCaseBody: `export const checkDataUseCase = () => async () => { return { ok: true }; };`,
|
||||
});
|
||||
tester.run("no-undeclared-consent-check", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: fileA,
|
||||
code: fs.readFileSync(fileA, "utf8"),
|
||||
options: [{ repoRoot: rootA }],
|
||||
errors: [
|
||||
{
|
||||
messageId: "undeclared",
|
||||
data: { category: "marketing", useCase: "checkData" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
filename: fileB,
|
||||
code: fs.readFileSync(fileB, "utf8"),
|
||||
options: [{ repoRoot: rootB }],
|
||||
errors: [
|
||||
{ messageId: "unusedDeclaration", data: { useCase: "checkData" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op for non-use-case files", () => {
|
||||
const { repoRoot } = makeFixture({
|
||||
requiresConsent: ["analytics"],
|
||||
useCaseBody: `export const checkDataUseCase = (consent) => async () => { consent.isGranted("unknown"); };`,
|
||||
});
|
||||
const serviceFile = path.join(
|
||||
repoRoot,
|
||||
"packages",
|
||||
"demo",
|
||||
"src",
|
||||
"application",
|
||||
"services",
|
||||
"data.service.ts",
|
||||
);
|
||||
fs.mkdirSync(path.dirname(serviceFile), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
serviceFile,
|
||||
`export function doWork(consent) { consent.isGranted("unknown"); }`,
|
||||
);
|
||||
tester.run("no-undeclared-consent-check", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: serviceFile,
|
||||
code: fs.readFileSync(serviceFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
87
packages/core-eslint/rules/no-undeclared-event-publish.js
Normal file
87
packages/core-eslint/rules/no-undeclared-event-publish.js
Normal file
@@ -0,0 +1,87 @@
|
||||
import { parseManifestUseCases } from "./_manifest-ast.js";
|
||||
import { manifestPathForFeature } from "./_manifest-source.js";
|
||||
import { repoRootSchema } from "./_rule-schema.js";
|
||||
import { resolveRuleContext } from "./_rule-context.js";
|
||||
import { eventNameFromFile, resolveRelativeImport } from "./_event-ast.js";
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"bus.publish(event) inside a use-case factory must declare the event in manifest.useCases[name].publishes. Resolves both a string-literal event name and an imported event descriptor (defineEvent(...) or an inline { name } object).",
|
||||
},
|
||||
schema: repoRootSchema,
|
||||
messages: {
|
||||
undeclared:
|
||||
'{{useCase}} publishes "{{event}}" via bus.publish but {{event}} is not declared in manifest.useCases.{{useCase}}.publishes. Add it to the manifest or remove the call.',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const rc = resolveRuleContext(context);
|
||||
if (!rc) return {};
|
||||
const { useCaseName, featureRoot } = rc;
|
||||
const manifest = parseManifestUseCases(manifestPathForFeature(featureRoot));
|
||||
if (!manifest || !manifest[useCaseName]) return {};
|
||||
const declared = new Set(manifest[useCaseName].publishes);
|
||||
|
||||
// Local import name -> import source string. Populated as `ImportDeclaration`
|
||||
// nodes are visited; imports always precede the use-case body, so the map
|
||||
// is complete by the time a `bus.publish` call is reached.
|
||||
const importSources = new Map();
|
||||
|
||||
/**
|
||||
* Resolve a `bus.publish()` first argument to its event name. Returns null
|
||||
* when the argument can't be statically analysed — an unresolvable case is
|
||||
* skipped rather than reported, so the rule never false-positives.
|
||||
*/
|
||||
function eventNameFor(arg) {
|
||||
if (arg.type === "Literal" && typeof arg.value === "string") {
|
||||
return arg.value;
|
||||
}
|
||||
if (arg.type === "Identifier") {
|
||||
const source = importSources.get(arg.name);
|
||||
if (!source) return null;
|
||||
const file = resolveRelativeImport(source, context.filename);
|
||||
if (!file) return null;
|
||||
return eventNameFromFile(file, arg.name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
ImportDeclaration(node) {
|
||||
const source = node.source.value;
|
||||
for (const spec of node.specifiers) {
|
||||
if (
|
||||
spec.type === "ImportSpecifier" ||
|
||||
spec.type === "ImportDefaultSpecifier"
|
||||
) {
|
||||
importSources.set(spec.local.name, source);
|
||||
}
|
||||
}
|
||||
},
|
||||
CallExpression(node) {
|
||||
if (
|
||||
node.callee.type === "MemberExpression" &&
|
||||
node.callee.object.type === "Identifier" &&
|
||||
node.callee.object.name === "bus" &&
|
||||
node.callee.property.type === "Identifier" &&
|
||||
node.callee.property.name === "publish" &&
|
||||
node.arguments.length > 0
|
||||
) {
|
||||
const event = eventNameFor(node.arguments[0]);
|
||||
if (event === null) return;
|
||||
if (!declared.has(event)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "undeclared",
|
||||
data: { event, useCase: useCaseName },
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
206
packages/core-eslint/rules/no-undeclared-event-publish.test.js
Normal file
206
packages/core-eslint/rules/no-undeclared-event-publish.test.js
Normal file
@@ -0,0 +1,206 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./no-undeclared-event-publish.js";
|
||||
|
||||
function makeFixture({ manifestUseCases, useCaseBody, eventFile }) {
|
||||
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nuep-"));
|
||||
const featureDir = path.join(repoRoot, "packages", "demo");
|
||||
fs.mkdirSync(path.join(featureDir, "src", "application", "use-cases"), {
|
||||
recursive: true,
|
||||
});
|
||||
const useCasesObj = Object.entries(manifestUseCases)
|
||||
.map(
|
||||
([name, uc]) =>
|
||||
` ${name}: { mutates: ${uc.mutates}, audits: [${uc.audits.map((a) => `"${a}"`).join(", ")}], publishes: [${uc.publishes.map((p) => `"${p}"`).join(", ")}], consumes: [] },`,
|
||||
)
|
||||
.join("\n");
|
||||
fs.writeFileSync(
|
||||
path.join(featureDir, "src", "feature.manifest.ts"),
|
||||
`export const demoManifest = defineFeature({
|
||||
name: "demo",
|
||||
requiredCores: [],
|
||||
useCases: {
|
||||
${useCasesObj}
|
||||
},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`,
|
||||
);
|
||||
if (eventFile) {
|
||||
const eventsDir = path.join(featureDir, "src", "events");
|
||||
fs.mkdirSync(eventsDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(eventsDir, eventFile.filename),
|
||||
eventFile.contents,
|
||||
);
|
||||
}
|
||||
const useCaseFile = path.join(
|
||||
featureDir,
|
||||
"src",
|
||||
"application",
|
||||
"use-cases",
|
||||
"sign-up.use-case.ts",
|
||||
);
|
||||
fs.writeFileSync(useCaseFile, useCaseBody);
|
||||
return { repoRoot, useCaseFile };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: {
|
||||
parser: await import("@typescript-eslint/parser"),
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
},
|
||||
});
|
||||
|
||||
describe("no-undeclared-event-publish", () => {
|
||||
it("passes when bus.publish event name matches manifest publishes[]", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: {
|
||||
signUp: { mutates: true, audits: [], publishes: ["demo.signed-up"] },
|
||||
},
|
||||
useCaseBody: `export const signUpUseCase = (bus) => async () => { bus.publish("demo.signed-up", {}); };`,
|
||||
});
|
||||
tester.run("no-undeclared-event-publish", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when bus.publish event name is not in manifest", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: {
|
||||
signUp: { mutates: true, audits: [], publishes: [] },
|
||||
},
|
||||
useCaseBody: `export const signUpUseCase = (bus) => async () => { bus.publish("demo.signed-up", {}); };`,
|
||||
});
|
||||
tester.run("no-undeclared-event-publish", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
errors: [
|
||||
{
|
||||
messageId: "undeclared",
|
||||
data: { event: "demo.signed-up", useCase: "signUp" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op when bus.publish is called with an unresolvable identifier", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: {
|
||||
signUp: { mutates: true, audits: [], publishes: [] },
|
||||
},
|
||||
useCaseBody: `export const signUpUseCase = (bus, name) => async () => { bus.publish(name, {}); };`,
|
||||
});
|
||||
tester.run("no-undeclared-event-publish", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("passes when an imported inline event descriptor is declared", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: {
|
||||
signUp: { mutates: true, audits: [], publishes: ["demo.signed-up"] },
|
||||
},
|
||||
eventFile: {
|
||||
filename: "signed-up.event.ts",
|
||||
contents: `export const signedUpEvent = { name: "demo.signed-up" as const, schema: {} };`,
|
||||
},
|
||||
useCaseBody: `import { signedUpEvent } from "../../events/signed-up.event";
|
||||
export const signUpUseCase = (bus) => async () => { bus.publish(signedUpEvent, {}); };`,
|
||||
});
|
||||
tester.run("no-undeclared-event-publish", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when an imported inline event descriptor is not declared", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: {
|
||||
signUp: { mutates: true, audits: [], publishes: [] },
|
||||
},
|
||||
eventFile: {
|
||||
filename: "signed-up.event.ts",
|
||||
contents: `export const signedUpEvent = { name: "demo.signed-up" as const, schema: {} };`,
|
||||
},
|
||||
useCaseBody: `import { signedUpEvent } from "../../events/signed-up.event";
|
||||
export const signUpUseCase = (bus) => async () => { bus.publish(signedUpEvent, {}); };`,
|
||||
});
|
||||
tester.run("no-undeclared-event-publish", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
errors: [
|
||||
{
|
||||
messageId: "undeclared",
|
||||
data: { event: "demo.signed-up", useCase: "signUp" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when an imported defineEvent() descriptor is not declared", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestUseCases: {
|
||||
signUp: { mutates: true, audits: [], publishes: [] },
|
||||
},
|
||||
eventFile: {
|
||||
filename: "signed-up.event.ts",
|
||||
contents: `export const signedUpEvent = defineEvent("demo.signed-up", {});`,
|
||||
},
|
||||
useCaseBody: `import { signedUpEvent } from "../../events/signed-up.event";
|
||||
export const signUpUseCase = (bus) => async () => { bus.publish(signedUpEvent, {}); };`,
|
||||
});
|
||||
tester.run("no-undeclared-event-publish", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
errors: [
|
||||
{
|
||||
messageId: "undeclared",
|
||||
data: { event: "demo.signed-up", useCase: "signUp" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
67
packages/core-eslint/rules/no-undeclared-rate-limit.js
Normal file
67
packages/core-eslint/rules/no-undeclared-rate-limit.js
Normal file
@@ -0,0 +1,67 @@
|
||||
import { parseManifestUseCases } from "./_manifest-ast.js";
|
||||
import { manifestPathForFeature } from "./_manifest-source.js";
|
||||
import { repoRootSchema } from "./_rule-schema.js";
|
||||
import { resolveRuleContext } from "./_rule-context.js";
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "suggestion",
|
||||
docs: {
|
||||
description:
|
||||
'rateLimit.consume("X", _) inside a use-case file must match a budget declared in manifest.useCases[name].rateLimit.',
|
||||
},
|
||||
schema: repoRootSchema,
|
||||
messages: {
|
||||
undeclared:
|
||||
'{{useCase}} calls rateLimit.consume("{{budget}}") but "{{budget}}" is not declared in manifest.useCases.{{useCase}}.rateLimit. Add it to the manifest or remove the call.',
|
||||
unusedDeclaration:
|
||||
'{{useCase}} declares rateLimit budget "{{budget}}" in the manifest but rateLimit.consume("{{budget}}") is never called in this file. Add the consume call or remove the manifest declaration.',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const rc = resolveRuleContext(context);
|
||||
if (!rc) return {};
|
||||
const { useCaseName, featureRoot } = rc;
|
||||
const manifest = parseManifestUseCases(manifestPathForFeature(featureRoot));
|
||||
if (!manifest || !manifest[useCaseName]) return {};
|
||||
const declared = new Set(manifest[useCaseName].rateLimit ?? []);
|
||||
const consumed = new Set();
|
||||
|
||||
return {
|
||||
CallExpression(node) {
|
||||
if (
|
||||
node.callee.type === "MemberExpression" &&
|
||||
node.callee.object.type === "Identifier" &&
|
||||
node.callee.object.name === "rateLimit" &&
|
||||
node.callee.property.type === "Identifier" &&
|
||||
node.callee.property.name === "consume" &&
|
||||
node.arguments.length > 0 &&
|
||||
node.arguments[0].type === "Literal" &&
|
||||
typeof node.arguments[0].value === "string"
|
||||
) {
|
||||
const budget = node.arguments[0].value;
|
||||
consumed.add(budget);
|
||||
if (!declared.has(budget)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "undeclared",
|
||||
data: { budget, useCase: useCaseName },
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
"Program:exit"(node) {
|
||||
for (const budget of declared) {
|
||||
if (!consumed.has(budget)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "unusedDeclaration",
|
||||
data: { budget, useCase: useCaseName },
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
187
packages/core-eslint/rules/no-undeclared-rate-limit.test.js
Normal file
187
packages/core-eslint/rules/no-undeclared-rate-limit.test.js
Normal file
@@ -0,0 +1,187 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./no-undeclared-rate-limit.js";
|
||||
|
||||
function makeFixture({ manifestRateLimit, useCaseBody }) {
|
||||
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nurl-"));
|
||||
const featureDir = path.join(repoRoot, "packages", "demo");
|
||||
fs.mkdirSync(path.join(featureDir, "src", "application", "use-cases"), {
|
||||
recursive: true,
|
||||
});
|
||||
const rateLimitField =
|
||||
manifestRateLimit.length > 0
|
||||
? `, rateLimit: [${manifestRateLimit.map((b) => `"${b}"`).join(", ")}]`
|
||||
: "";
|
||||
fs.writeFileSync(
|
||||
path.join(featureDir, "src", "feature.manifest.ts"),
|
||||
`export const demoManifest = defineFeature({
|
||||
name: "demo",
|
||||
requiredCores: [],
|
||||
useCases: {
|
||||
signUp: { mutates: true, audits: [], publishes: [], consumes: []${rateLimitField} },
|
||||
},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`,
|
||||
);
|
||||
const useCaseFile = path.join(
|
||||
featureDir,
|
||||
"src",
|
||||
"application",
|
||||
"use-cases",
|
||||
"sign-up.use-case.ts",
|
||||
);
|
||||
fs.writeFileSync(useCaseFile, useCaseBody);
|
||||
return { repoRoot, useCaseFile };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: {
|
||||
parser: await import("@typescript-eslint/parser"),
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
},
|
||||
});
|
||||
|
||||
describe("no-undeclared-rate-limit", () => {
|
||||
it("passes when rateLimit.consume budget matches manifest rateLimit[]", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestRateLimit: ["signUp.ip"],
|
||||
useCaseBody: `export const signUpUseCase = (rateLimit) => async (input) => { await rateLimit.consume("signUp.ip", input.ip); };`,
|
||||
});
|
||||
tester.run("no-undeclared-rate-limit", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when rateLimit.consume budget is not declared in manifest", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestRateLimit: [],
|
||||
useCaseBody: `export const signUpUseCase = (rateLimit) => async (input) => { await rateLimit.consume("signUp.ip", input.ip); };`,
|
||||
});
|
||||
tester.run("no-undeclared-rate-limit", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
errors: [
|
||||
{
|
||||
messageId: "undeclared",
|
||||
data: { budget: "signUp.ip", useCase: "signUp" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when a declared budget is never consumed in the use-case body", () => {
|
||||
const { repoRoot, useCaseFile } = makeFixture({
|
||||
manifestRateLimit: ["signUp.ip"],
|
||||
useCaseBody: `export const signUpUseCase = () => async () => { return { ok: true }; };`,
|
||||
});
|
||||
tester.run("no-undeclared-rate-limit", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
errors: [
|
||||
{
|
||||
messageId: "unusedDeclaration",
|
||||
data: { budget: "signUp.ip", useCase: "signUp" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("passes when rateLimit.consume budget matches a RateLimitBudget object in manifest rateLimit[]", () => {
|
||||
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nurl-obj-"));
|
||||
const featureDir = path.join(repoRoot, "packages", "demo");
|
||||
fs.mkdirSync(path.join(featureDir, "src", "application", "use-cases"), {
|
||||
recursive: true,
|
||||
});
|
||||
fs.writeFileSync(
|
||||
path.join(featureDir, "src", "feature.manifest.ts"),
|
||||
`export const demoManifest = defineFeature({
|
||||
name: "demo",
|
||||
requiredCores: [],
|
||||
useCases: {
|
||||
signUp: { mutates: true, audits: [], publishes: [], consumes: [], rateLimit: [{ name: "ip", window: "1m", budget: 5 }, { name: "account", window: "1h", budget: 10 }] },
|
||||
},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`,
|
||||
);
|
||||
const useCaseFile = path.join(
|
||||
featureDir,
|
||||
"src",
|
||||
"application",
|
||||
"use-cases",
|
||||
"sign-up.use-case.ts",
|
||||
);
|
||||
fs.writeFileSync(
|
||||
useCaseFile,
|
||||
`export const signUpUseCase = (rateLimit) => async (input) => {
|
||||
await rateLimit.consume("ip", input.clientIp);
|
||||
await rateLimit.consume("account", input.username);
|
||||
};`,
|
||||
);
|
||||
tester.run("no-undeclared-rate-limit", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: useCaseFile,
|
||||
code: fs.readFileSync(useCaseFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op for non-use-case files", () => {
|
||||
const { repoRoot } = makeFixture({
|
||||
manifestRateLimit: ["signUp.ip"],
|
||||
useCaseBody: `export const signUpUseCase = (rateLimit) => async (input) => { await rateLimit.consume("signUp.ip", input.ip); };`,
|
||||
});
|
||||
const serviceFile = path.join(
|
||||
repoRoot,
|
||||
"packages",
|
||||
"demo",
|
||||
"src",
|
||||
"application",
|
||||
"services",
|
||||
"sign-up.service.ts",
|
||||
);
|
||||
fs.mkdirSync(path.dirname(serviceFile), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
serviceFile,
|
||||
`export function doWork(rateLimit) { rateLimit.consume("undeclared", "x"); }`,
|
||||
);
|
||||
tester.run("no-undeclared-rate-limit", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: serviceFile,
|
||||
code: fs.readFileSync(serviceFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
const REQUIRED_FIELDS = ["category", "purpose", "exportable", "restrictable"];
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"custom.pii blocks in Payload config files must declare all required sub-fields: category, purpose, exportable, restrictable.",
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
missingField:
|
||||
"custom.pii block is missing required field '{{field}}'. Incomplete PII declarations can produce incorrect audit reports.",
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
return {
|
||||
Property(node) {
|
||||
if (
|
||||
node.key.type !== "Identifier" ||
|
||||
node.key.name !== "custom" ||
|
||||
node.value.type !== "ObjectExpression"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const piiProp = node.value.properties.find(
|
||||
(p) =>
|
||||
p.type === "Property" &&
|
||||
p.key.type === "Identifier" &&
|
||||
p.key.name === "pii",
|
||||
);
|
||||
|
||||
if (!piiProp || piiProp.value.type !== "ObjectExpression") {
|
||||
return;
|
||||
}
|
||||
|
||||
const presentFields = new Set(
|
||||
piiProp.value.properties
|
||||
.filter((p) => p.type === "Property" && p.key.type === "Identifier")
|
||||
.map((p) => p.key.name),
|
||||
);
|
||||
|
||||
for (const field of REQUIRED_FIELDS) {
|
||||
if (!presentFields.has(field)) {
|
||||
context.report({
|
||||
node: piiProp,
|
||||
messageId: "missingField",
|
||||
data: { field },
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,163 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import rule from "./pii-declaration-must-be-complete.js";
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: {
|
||||
parser: await import("@typescript-eslint/parser"),
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
},
|
||||
});
|
||||
|
||||
describe("pii-declaration-must-be-complete", () => {
|
||||
it("passes when custom.pii has all required fields", () => {
|
||||
tester.run("pii-declaration-must-be-complete", rule, {
|
||||
valid: [
|
||||
{
|
||||
code: `
|
||||
const field = {
|
||||
slug: "email",
|
||||
type: "email",
|
||||
custom: {
|
||||
pii: {
|
||||
category: "contact",
|
||||
purpose: "authentication",
|
||||
exportable: false,
|
||||
restrictable: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
`,
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when category is missing", () => {
|
||||
tester.run("pii-declaration-must-be-complete", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `
|
||||
const field = {
|
||||
custom: {
|
||||
pii: {
|
||||
purpose: "authentication",
|
||||
exportable: false,
|
||||
restrictable: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
`,
|
||||
errors: [{ messageId: "missingField", data: { field: "category" } }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when purpose is missing", () => {
|
||||
tester.run("pii-declaration-must-be-complete", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `
|
||||
const field = {
|
||||
custom: {
|
||||
pii: {
|
||||
category: "contact",
|
||||
exportable: false,
|
||||
restrictable: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
`,
|
||||
errors: [{ messageId: "missingField", data: { field: "purpose" } }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when exportable is missing", () => {
|
||||
tester.run("pii-declaration-must-be-complete", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `
|
||||
const field = {
|
||||
custom: {
|
||||
pii: {
|
||||
category: "contact",
|
||||
purpose: "authentication",
|
||||
restrictable: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
`,
|
||||
errors: [
|
||||
{ messageId: "missingField", data: { field: "exportable" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when restrictable is missing", () => {
|
||||
tester.run("pii-declaration-must-be-complete", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
code: `
|
||||
const field = {
|
||||
custom: {
|
||||
pii: {
|
||||
category: "contact",
|
||||
purpose: "authentication",
|
||||
exportable: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
`,
|
||||
errors: [
|
||||
{ messageId: "missingField", data: { field: "restrictable" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op when custom has no pii property", () => {
|
||||
tester.run("pii-declaration-must-be-complete", rule, {
|
||||
valid: [
|
||||
{
|
||||
code: `
|
||||
const field = {
|
||||
custom: {
|
||||
someOtherProperty: "value",
|
||||
},
|
||||
};
|
||||
`,
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op when custom.pii is not an object", () => {
|
||||
tester.run("pii-declaration-must-be-complete", rule, {
|
||||
valid: [
|
||||
{
|
||||
code: `
|
||||
const field = {
|
||||
custom: {
|
||||
pii: true,
|
||||
},
|
||||
};
|
||||
`,
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
71
packages/core-eslint/rules/required-cores-installed.js
Normal file
71
packages/core-eslint/rules/required-cores-installed.js
Normal file
@@ -0,0 +1,71 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { readManifestSource } from "./_manifest-source.js";
|
||||
import { readWorkspacePackages } from "./_workspace.js";
|
||||
|
||||
/**
|
||||
* Check whether `packages/core-<name>` exists under any of the workspace
|
||||
* globs. The glob set is small and predictable (e.g. ["apps/*", "packages/*"]);
|
||||
* we simulate matching by checking each glob's directory portion + verifying
|
||||
* `core-<name>` exists in that directory.
|
||||
*/
|
||||
function coreExistsInWorkspace(coreName, repoRoot, packageGlobs) {
|
||||
for (const glob of packageGlobs) {
|
||||
const slashStar = glob.endsWith("/*") ? glob.slice(0, -2) : null;
|
||||
if (!slashStar) continue;
|
||||
const candidate = path.join(repoRoot, slashStar, `core-${coreName}`);
|
||||
if (fs.existsSync(candidate)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Cores declared in a feature.manifest.ts's requiredCores must exist as core-<name> packages within a workspace glob.",
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
repoRoot: { type: "string" },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
messages: {
|
||||
coreNotInstalled:
|
||||
'Manifest declares requiredCores: [..., "{{core}}", ...] but `core-{{core}}` is not present in any workspace glob. Run `pnpm turbo gen core-package {{core}}` or drop the entry.',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const opts = context.options[0] ?? {};
|
||||
const repoRoot = opts.repoRoot ?? context.cwd ?? process.cwd();
|
||||
return {
|
||||
Program(node) {
|
||||
const filename = context.filename;
|
||||
if (
|
||||
!filename.endsWith("/feature.manifest.ts") &&
|
||||
!filename.endsWith("\\feature.manifest.ts")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const manifest = readManifestSource(filename);
|
||||
if (!manifest) return;
|
||||
const globs = readWorkspacePackages(repoRoot);
|
||||
for (const core of manifest.requiredCores) {
|
||||
if (!coreExistsInWorkspace(core, repoRoot, globs)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: "coreNotInstalled",
|
||||
data: { core },
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
112
packages/core-eslint/rules/required-cores-installed.test.js
Normal file
112
packages/core-eslint/rules/required-cores-installed.test.js
Normal file
@@ -0,0 +1,112 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./required-cores-installed.js";
|
||||
|
||||
function makeFixture({ workspacePackages, manifestCores }) {
|
||||
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), "rci-"));
|
||||
fs.writeFileSync(
|
||||
path.join(repoRoot, "pnpm-workspace.yaml"),
|
||||
`packages:\n${workspacePackages.map((p) => ` - "${p}"`).join("\n")}\n`,
|
||||
);
|
||||
const manifestDir = path.join(repoRoot, "packages", "demo", "src");
|
||||
fs.mkdirSync(manifestDir, { recursive: true });
|
||||
// We also need each declared core to exist as a package directory for the glob to resolve.
|
||||
for (const core of manifestCores) {
|
||||
fs.mkdirSync(path.join(repoRoot, "packages", `core-${core}`), {
|
||||
recursive: true,
|
||||
});
|
||||
}
|
||||
const manifest = path.join(manifestDir, "feature.manifest.ts");
|
||||
fs.writeFileSync(
|
||||
manifest,
|
||||
`export const demoManifest = defineFeature({
|
||||
name: "demo",
|
||||
requiredCores: [${manifestCores.map((c) => `"${c}"`).join(", ")}],
|
||||
useCases: {},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`,
|
||||
);
|
||||
return { repoRoot, manifest };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: { ecmaVersion: "latest", sourceType: "module" },
|
||||
});
|
||||
|
||||
describe("required-cores-installed", () => {
|
||||
it("passes when all declared cores are present as core-<x> packages under a workspace glob", () => {
|
||||
const { repoRoot, manifest } = makeFixture({
|
||||
workspacePackages: ["packages/*"],
|
||||
manifestCores: ["audit", "events"],
|
||||
});
|
||||
tester.run("required-cores-installed", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: manifest,
|
||||
code: fs.readFileSync(manifest, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires for any declared core that has no matching package", () => {
|
||||
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), "rci-"));
|
||||
fs.writeFileSync(
|
||||
path.join(repoRoot, "pnpm-workspace.yaml"),
|
||||
`packages:\n - "packages/*"\n`,
|
||||
);
|
||||
const manifestDir = path.join(repoRoot, "packages", "demo", "src");
|
||||
fs.mkdirSync(manifestDir, { recursive: true });
|
||||
// NB: do NOT create packages/core-realtime — that's the missing one.
|
||||
fs.mkdirSync(path.join(repoRoot, "packages", "core-audit"), {
|
||||
recursive: true,
|
||||
});
|
||||
const manifest = path.join(manifestDir, "feature.manifest.ts");
|
||||
fs.writeFileSync(
|
||||
manifest,
|
||||
`export const demoManifest = defineFeature({
|
||||
name: "demo",
|
||||
requiredCores: ["audit", "realtime"],
|
||||
useCases: {},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`,
|
||||
);
|
||||
|
||||
tester.run("required-cores-installed", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: manifest,
|
||||
code: fs.readFileSync(manifest, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
errors: [
|
||||
{ messageId: "coreNotInstalled", data: { core: "realtime" } },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op for files that are not feature.manifest.ts", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "rci-"));
|
||||
const other = path.join(dir, "not-a-manifest.ts");
|
||||
fs.writeFileSync(other, `export const x = 1;`);
|
||||
tester.run("required-cores-installed", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: other,
|
||||
code: fs.readFileSync(other, "utf8"),
|
||||
options: [{ repoRoot: dir }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
96
packages/core-eslint/rules/usecase-must-be-wired.js
Normal file
96
packages/core-eslint/rules/usecase-must-be-wired.js
Normal file
@@ -0,0 +1,96 @@
|
||||
import path from "node:path";
|
||||
import { parseManifestUseCases } from "./_manifest-ast.js";
|
||||
import {
|
||||
manifestPathForFeature,
|
||||
featureRootForFile,
|
||||
} from "./_manifest-source.js";
|
||||
|
||||
/**
|
||||
* Every manifest-declared use case must be bound through `wireUseCase(...)` in
|
||||
* the feature's `bind-production.ts` and `bind-dev-seed.ts`. `wireUseCase` is
|
||||
* the canonical helper that wraps factories with `withSpan` + `withCapture`
|
||||
* (+ `withAudit` for mutating use cases) and attaches the corresponding
|
||||
* brands. Skipping it produces an unbranded binding that `assertFeatureConformance`
|
||||
* will reject at boot — this rule shifts that check from ~3s (boot) to <1s
|
||||
* (lint), so drift is caught while typing.
|
||||
*
|
||||
* Lint-time complement to:
|
||||
* - the TypeScript brand check (`ProductionUseCase<I,O>` slot type) — compile time
|
||||
* - the boot-time assertion (`assertFeatureConformance`) — runtime
|
||||
* - the smoke test (`bind-production.smoke.test.ts`) — CI
|
||||
*/
|
||||
const BINDER_BASENAMES = new Set(["bind-production.ts", "bind-dev-seed.ts"]);
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Every manifest use case must be bound through wireUseCase(...) in the feature's bind-production.ts / bind-dev-seed.ts.",
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: "object",
|
||||
properties: { repoRoot: { type: "string" } },
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
messages: {
|
||||
missing:
|
||||
'Use case "{{useCase}}" is declared in {{feature}}.manifest.ts but not wired through wireUseCase({ name: "{{useCase}}", ... }) in this binder. Add the wireUseCase call or remove the manifest entry.',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const opts = context.options[0] ?? {};
|
||||
const repoRoot = opts.repoRoot ?? context.cwd ?? process.cwd();
|
||||
const filename = context.filename;
|
||||
if (!BINDER_BASENAMES.has(path.basename(filename))) return {};
|
||||
|
||||
const featureRoot = featureRootForFile(filename, repoRoot);
|
||||
if (!featureRoot) return {};
|
||||
const manifest = parseManifestUseCases(manifestPathForFeature(featureRoot));
|
||||
if (!manifest) return {};
|
||||
const declaredNames = Object.keys(manifest);
|
||||
if (declaredNames.length === 0) return {};
|
||||
const featureName = path.basename(featureRoot);
|
||||
|
||||
const wired = new Set();
|
||||
return {
|
||||
CallExpression(node) {
|
||||
if (
|
||||
node.callee.type !== "Identifier" ||
|
||||
node.callee.name !== "wireUseCase"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const arg = node.arguments[0];
|
||||
if (!arg || arg.type !== "ObjectExpression") return;
|
||||
const nameProp = arg.properties.find(
|
||||
(p) =>
|
||||
p.type === "Property" &&
|
||||
p.key.type === "Identifier" &&
|
||||
p.key.name === "name",
|
||||
);
|
||||
if (
|
||||
nameProp &&
|
||||
nameProp.value.type === "Literal" &&
|
||||
typeof nameProp.value.value === "string"
|
||||
) {
|
||||
wired.add(nameProp.value.value);
|
||||
}
|
||||
},
|
||||
"Program:exit"(programNode) {
|
||||
for (const useCase of declaredNames) {
|
||||
if (!wired.has(useCase)) {
|
||||
context.report({
|
||||
node: programNode,
|
||||
messageId: "missing",
|
||||
data: { useCase, feature: featureName },
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
172
packages/core-eslint/rules/usecase-must-be-wired.test.js
Normal file
172
packages/core-eslint/rules/usecase-must-be-wired.test.js
Normal file
@@ -0,0 +1,172 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./usecase-must-be-wired.js";
|
||||
|
||||
function makeFixture({
|
||||
manifestUseCases,
|
||||
binderBody,
|
||||
binderName = "bind-production.ts",
|
||||
}) {
|
||||
const repoRoot = fs.mkdtempSync(path.join(os.tmpdir(), "umbw-"));
|
||||
const featureDir = path.join(repoRoot, "packages", "demo");
|
||||
fs.mkdirSync(path.join(featureDir, "src", "di"), { recursive: true });
|
||||
const useCasesObj = Object.entries(manifestUseCases)
|
||||
.map(
|
||||
([name, uc]) =>
|
||||
` ${name}: { mutates: ${uc.mutates}, audits: [${uc.audits.map((a) => `"${a}"`).join(", ")}], publishes: [], consumes: [] },`,
|
||||
)
|
||||
.join("\n");
|
||||
fs.writeFileSync(
|
||||
path.join(featureDir, "src", "feature.manifest.ts"),
|
||||
`export const demoManifest = defineFeature({
|
||||
name: "demo",
|
||||
requiredCores: [],
|
||||
useCases: {
|
||||
${useCasesObj}
|
||||
},
|
||||
realtimeChannels: [],
|
||||
jobs: [],
|
||||
} as const);`,
|
||||
);
|
||||
const binderFile = path.join(featureDir, "src", "di", binderName);
|
||||
fs.writeFileSync(binderFile, binderBody);
|
||||
return { repoRoot, binderFile };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: {
|
||||
parser: await import("@typescript-eslint/parser"),
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
},
|
||||
});
|
||||
|
||||
describe("usecase-must-be-wired", () => {
|
||||
it("passes when every manifest use case has a wireUseCase call", () => {
|
||||
const { repoRoot, binderFile } = makeFixture({
|
||||
manifestUseCases: {
|
||||
signIn: { mutates: false, audits: [] },
|
||||
signUp: { mutates: true, audits: ["user.created"] },
|
||||
},
|
||||
binderBody: `
|
||||
export function bindProductionDemo(ctx) {
|
||||
wireUseCase({ name: "signIn", factory: signInUseCase });
|
||||
wireUseCase({ name: "signUp", factory: signUpUseCase });
|
||||
}
|
||||
`,
|
||||
});
|
||||
tester.run("usecase-must-be-wired", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: binderFile,
|
||||
code: fs.readFileSync(binderFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when a manifest use case is missing a wireUseCase call", () => {
|
||||
const { repoRoot, binderFile } = makeFixture({
|
||||
manifestUseCases: {
|
||||
signIn: { mutates: false, audits: [] },
|
||||
signUp: { mutates: true, audits: [] },
|
||||
},
|
||||
binderBody: `
|
||||
export function bindProductionDemo(ctx) {
|
||||
wireUseCase({ name: "signIn", factory: signInUseCase });
|
||||
}
|
||||
`,
|
||||
});
|
||||
tester.run("usecase-must-be-wired", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: binderFile,
|
||||
code: fs.readFileSync(binderFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
errors: [
|
||||
{
|
||||
messageId: "missing",
|
||||
data: { useCase: "signUp", feature: "demo" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("also applies to bind-dev-seed.ts", () => {
|
||||
const { repoRoot, binderFile } = makeFixture({
|
||||
binderName: "bind-dev-seed.ts",
|
||||
manifestUseCases: { signIn: { mutates: false, audits: [] } },
|
||||
binderBody: `
|
||||
export async function bindDevSeedDemo(ctx) {
|
||||
// forgot to call wireUseCase
|
||||
}
|
||||
`,
|
||||
});
|
||||
tester.run("usecase-must-be-wired", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: binderFile,
|
||||
code: fs.readFileSync(binderFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
errors: [
|
||||
{
|
||||
messageId: "missing",
|
||||
data: { useCase: "signIn", feature: "demo" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op on files outside src/di/bind-*.ts", () => {
|
||||
const { repoRoot } = makeFixture({
|
||||
manifestUseCases: { signIn: { mutates: false, audits: [] } },
|
||||
binderBody: `// not a binder`,
|
||||
});
|
||||
const otherFile = path.join(
|
||||
repoRoot,
|
||||
"packages",
|
||||
"demo",
|
||||
"src",
|
||||
"other.ts",
|
||||
);
|
||||
fs.writeFileSync(otherFile, `export const x = 1;`);
|
||||
tester.run("usecase-must-be-wired", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: otherFile,
|
||||
code: fs.readFileSync(otherFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("is a no-op when the feature manifest declares no use cases", () => {
|
||||
const { repoRoot, binderFile } = makeFixture({
|
||||
manifestUseCases: {},
|
||||
binderBody: `export function bindProductionDemo(ctx) {}`,
|
||||
});
|
||||
tester.run("usecase-must-be-wired", rule, {
|
||||
valid: [
|
||||
{
|
||||
filename: binderFile,
|
||||
code: fs.readFileSync(binderFile, "utf8"),
|
||||
options: [{ repoRoot }],
|
||||
},
|
||||
],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
38
packages/core-eslint/rules/usecase-must-have-test-file.js
Normal file
38
packages/core-eslint/rules/usecase-must-have-test-file.js
Normal file
@@ -0,0 +1,38 @@
|
||||
import fs from "node:fs";
|
||||
|
||||
/** @type {import("eslint").Rule.RuleModule} */
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description:
|
||||
"Every *.use-case.ts file must have a sibling *.use-case.test.ts (TDD discipline).",
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
missingTestFile:
|
||||
"Use case {{filename}} has no sibling test file at {{expected}}. Write the red test first.",
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
return {
|
||||
Program(node) {
|
||||
const filename = context.filename;
|
||||
if (!filename.endsWith(".use-case.ts")) return;
|
||||
const expected = filename.replace(
|
||||
/\.use-case\.ts$/,
|
||||
".use-case.test.ts",
|
||||
);
|
||||
if (fs.existsSync(expected)) return;
|
||||
context.report({
|
||||
node,
|
||||
messageId: "missingTestFile",
|
||||
data: {
|
||||
filename: filename.split("/").pop(),
|
||||
expected: expected.split("/").pop(),
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, it } from "vitest";
|
||||
import { RuleTester } from "eslint";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import fs from "node:fs";
|
||||
import rule from "./usecase-must-have-test-file.js";
|
||||
|
||||
function makeUseCaseFixture({ withTest }) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "umht-"));
|
||||
const useCase = path.join(dir, "sign-in.use-case.ts");
|
||||
fs.writeFileSync(
|
||||
useCase,
|
||||
`export const signInUseCase = () => async () => {};`,
|
||||
);
|
||||
if (withTest) {
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "sign-in.use-case.test.ts"),
|
||||
`import { it } from "vitest"; it("works", () => {});`,
|
||||
);
|
||||
}
|
||||
return { useCase };
|
||||
}
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: { ecmaVersion: "latest", sourceType: "module" },
|
||||
});
|
||||
|
||||
describe("usecase-must-have-test-file", () => {
|
||||
it("passes when a sibling .test.ts exists", () => {
|
||||
const { useCase } = makeUseCaseFixture({ withTest: true });
|
||||
tester.run("usecase-must-have-test-file", rule, {
|
||||
valid: [{ filename: useCase, code: fs.readFileSync(useCase, "utf8") }],
|
||||
invalid: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("fires when no sibling test file exists", () => {
|
||||
const { useCase } = makeUseCaseFixture({ withTest: false });
|
||||
tester.run("usecase-must-have-test-file", rule, {
|
||||
valid: [],
|
||||
invalid: [
|
||||
{
|
||||
filename: useCase,
|
||||
code: fs.readFileSync(useCase, "utf8"),
|
||||
errors: [{ messageId: "missingTestFile" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user