Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | 2x 2x 2x 2x 2x 2x 2x 96x 96x 93x 93x 3x 3x 6x 3x 3x 2x 96x 96x 96x 96x 276x 93x 2x 18x 19x 2x 32x 32x 31x 2x 33x 33x 14x 7x 2x 33x 33x 33x 33x 32x 62x 62x 124x 62x 26x 32x 32x 33x 33x 33x 33x 33x 33x 30x 26x 4x 22x 19x 16x 3x 13x 11x 8x 33x 42x 42x 42x 18x 33x 16x 8x 8x 6x 3x 33x 33x 33x 33x 33x 18x 1x 1x 1x 33x 33x 16x 16x 16x 32x 1x 1x 31x 31x 31x 32x 32x 7x 33x | import { statSync, readFileSync } from "node:fs";
import { posix } from "node:path";
import type { Rule, Scope } from "eslint";
export interface LayerBoundariesOptions {
cores: string[];
kit: string[];
}
type Options = [LayerBoundariesOptions];
type Origins = Map<string, string>;
type Owner = { layer: string } | "kit" | "shell";
interface TemplateElement {
rawName: string;
loc: Rule.Node["loc"];
}
interface TemplateContainer {
references: { id: { name: string; loc: Rule.Node["loc"] } }[];
}
interface TemplateVisitor {
defineTemplateBodyVisitor?: (
templateVisitor: Record<string, (node: never) => void>,
scriptVisitor: Rule.RuleListener,
) => Rule.RuleListener;
}
const LAYERS = "/layers/";
const DECLARATION = /const (\w+): (?:LazyComponent<)?typeof import\((["'])([^"']+)\2\)/g;
const MAPS = {
app: ["types/imports.d.ts"],
server: ["types/nitro-imports.d.ts"],
shared: ["types/shared-imports.d.ts"],
components: ["components.d.ts"],
} as const satisfies Record<string, readonly string[]>;
const ALIASES: Record<string, string> = { "~/": "app/", "@/": "app/", "~~/": "", "@@/": "" };
const EXTERNAL = ["node_modules/", ".nuxt/"];
// ESLint's language server lives across `nuxi prepare` runs, so a cached map is reread on change.
const cache = new Map<string, { mtimeMs: number; origins: Origins }>();
const readOrigins = (file: string): Origins | undefined => {
const mtimeMs = statSync(file, { throwIfNoEntry: false })?.mtimeMs;
if (mtimeMs === undefined) return undefined;
const cached = cache.get(file);
if (cached?.mtimeMs === mtimeMs) return cached.origins;
const origins: Origins = new Map();
for (const [, name, , path] of readFileSync(file, "utf8").matchAll(DECLARATION)) {
Eif (name && path) origins.set(name, posix.resolve(posix.dirname(file), path));
}
cache.set(file, { mtimeMs, origins });
return origins;
};
const readMaps = (nuxtDir: string, files: readonly string[]): Origins | undefined => {
const merged: Origins = new Map();
for (const file of files) {
const origins = readOrigins(posix.join(nuxtDir, file));
if (!origins) return undefined;
for (const [name, path] of origins) merged.set(name, path);
}
return merged;
};
const toPascal = (tag: string): string =>
tag
.split("-")
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join("");
const scriptKind = (path: string): keyof typeof MAPS => {
Iif (path.includes("server/")) return "server";
if (path.includes("shared/")) return "shared";
return "app";
};
const appRootOf = (filename: string, kit: string[]): string | undefined => {
const at = filename.indexOf(LAYERS);
if (at !== -1) return filename.slice(0, at);
const inKit = kit.map((path) => filename.indexOf(`/${path}`)).find((index) => index !== -1);
return inKit === undefined ? undefined : filename.slice(0, inKit);
};
const layerBoundaries: Rule.RuleModule = {
meta: {
type: "problem",
docs: {
description:
"Keep Nuxt layers apart, auto-imports included: the kit uses only itself, a core uses only itself and the kit, a feature also uses the cores, and only a feature's pages render another feature's components.",
},
schema: [
{
type: "object",
properties: {
cores: { type: "array", items: { type: "string" } },
kit: { type: "array", items: { type: "string" } },
},
required: ["cores", "kit"],
additionalProperties: false,
},
],
messages: {
featureToFeature:
"Move what this needs from the `{{target}}` feature into a core layer ({{cores}}) or the kit ({{kit}}): a feature never uses another feature.",
coreToFeature:
"Move what this needs from the `{{target}}` feature into a core layer: a core never uses a feature.",
coreToCore:
"Move what this needs from the `{{target}}` layer into this one or into the kit ({{kit}}): a core uses only itself and the kit.",
layerToShell:
"Move what this needs from the shell into the kit ({{kit}}): a layer never uses the rest of `app/` or `server/`.",
kitToOutside:
"Move what this needs into the kit ({{kit}}), or pass it in from the caller: the kit uses only itself.",
unprepared:
"Run `nuxi prepare` in this app: without `.nuxt/` this rule can't tell which layer an auto-import comes from.",
},
},
create: (context) => {
const [{ cores, kit }] = context.options as Options;
const filename = context.filename.replaceAll("\\", "/");
const appRoot = appRootOf(filename, kit);
if (appRoot === undefined) return {};
// eslint-disable-next-line sonarjs/function-return-type -- Owner names the kit and shell as strings and a layer as an object
const ownerOf = (path: string): Owner | undefined => {
Iif (!path.startsWith(`${appRoot}/`)) return undefined;
const relative = path.slice(appRoot.length + 1);
Iif (EXTERNAL.some((prefix) => relative.startsWith(prefix))) return undefined;
if (relative.startsWith("layers/")) return { layer: relative.split("/")[1] ?? "" };
return kit.some((prefix) => relative.startsWith(prefix)) ? "kit" : "shell";
};
const self = ownerOf(filename);
const layer = typeof self === "object" ? self.layer : undefined;
const fromCore = cores.includes(layer ?? "");
const relative = filename.slice(appRoot.length + 1);
const featurePage =
!!layer && !fromCore && relative.startsWith(`layers/${layer}/app/pages/`);
const fromDir = posix.dirname(filename);
const data = { cores: cores.join(", "), kit: kit.join(", ") };
const messageFor = (
target: Owner,
asComponent: boolean,
): { messageId: string; target: string } | undefined => {
if (target === "kit") return undefined;
if (self === "kit") {
return {
messageId: "kitToOutside",
target: target === "shell" ? "shell" : target.layer,
};
}
if (target === "shell") return { messageId: "layerToShell", target: "shell" };
if (target.layer === layer) return undefined;
if (cores.includes(target.layer)) {
return fromCore ? { messageId: "coreToCore", target: target.layer } : undefined;
}
if (fromCore) return { messageId: "coreToFeature", target: target.layer };
if (featurePage && asComponent) return undefined;
return { messageId: "featureToFeature", target: target.layer };
};
const report = (loc: Rule.Node["loc"], path: string | undefined, asComponent = false) => {
const target = path === undefined ? undefined : ownerOf(path);
const problem = target && messageFor(target, asComponent);
if (!problem || !loc) return;
context.report({
loc,
messageId: problem.messageId,
data: { ...data, target: problem.target },
});
};
const resolveSource = (source: string): string | undefined => {
if (source.startsWith("#layers/"))
return posix.join(appRoot, "layers", source.slice(8));
if (source.startsWith(".")) return posix.join(fromDir, source);
const alias = Object.keys(ALIASES).find((prefix) => source.startsWith(prefix));
return alias === undefined
? undefined
: posix.join(appRoot, ALIASES[alias] ?? "", source.slice(alias.length));
};
const autoImports = readMaps(posix.join(appRoot, ".nuxt"), MAPS[scriptKind(relative)]);
const components = readMaps(posix.join(appRoot, ".nuxt"), MAPS.components);
const templateImports = readMaps(posix.join(appRoot, ".nuxt"), MAPS.app);
const declaredAtTop = new Set<string>();
const templateVisitor = {
VElement: (node: TemplateElement) => {
report(node.loc, components?.get(toPascal(node.rawName)), true);
},
VExpressionContainer: (node: TemplateContainer) => {
for (const { id } of node.references) {
Eif (!declaredAtTop.has(id.name)) {
report(id.loc, templateImports?.get(id.name));
}
}
},
};
const parserServices = context.sourceCode.parserServices as TemplateVisitor | undefined;
const scriptVisitor: Rule.RuleListener = {
"ImportDeclaration, ExportNamedDeclaration, ExportAllDeclaration, ImportExpression": (
node: Rule.Node,
) => {
Eif ("source" in node && node.source?.type === "Literal") {
const { value } = node.source;
Eif (typeof value === "string") report(node.loc, resolveSource(value));
}
},
Program: (node) => {
if (!autoImports || !components || !templateImports) {
context.report({ node, loc: { line: 1, column: 0 }, messageId: "unprepared" });
return;
}
const { globalScope } = context.sourceCode.scopeManager;
for (const scope of globalScope?.childScopes ?? []) {
for (const { name } of scope.variables) declaredAtTop.add(name);
}
},
"Program:exit": () => {
const through: Scope.Reference[] =
context.sourceCode.scopeManager.globalScope?.through ?? [];
for (const { identifier } of through) {
report(identifier.loc, autoImports?.get(identifier.name));
}
},
};
// The parser walks the template from this visitor's own `Program:exit`, so it must wrap it.
return (
parserServices?.defineTemplateBodyVisitor?.(templateVisitor, scriptVisitor) ??
scriptVisitor
);
},
};
export default layerBoundaries;
|