@vwala/tooling-config 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/.vwala/docs/README.md +4 -0
  2. package/.vwala/docs/react-19.md +119 -0
  3. package/.vwala/docs/react-compiler.md +128 -0
  4. package/README.md +20 -2
  5. package/package.json +16 -4
  6. package/src/_scripts/check-conventions.mjs +8 -0
  7. package/src/biome/biome.config.json +1 -1
  8. package/src/biome/plugins/no-manual-react-memoization.grit +5 -0
  9. package/src/biome/plugins/no-react-use-context.grit +5 -0
  10. package/src/react-compiler/build/artifact-inventory.mjs +39 -0
  11. package/src/react-compiler/build/build-command-process.mjs +58 -0
  12. package/src/react-compiler/build/compile-react-library.mjs +39 -0
  13. package/src/react-compiler/build/emitted-artifacts.mjs +34 -0
  14. package/src/react-compiler/build/is-react-source.mjs +43 -0
  15. package/src/react-compiler/build/mark-library-compiler-ownership.mjs +47 -0
  16. package/src/react-compiler/build/overlay-react-library.mjs +53 -0
  17. package/src/react-compiler/build/read-build-project.mjs +33 -0
  18. package/src/react-compiler/build/transform-react-source.mjs +72 -0
  19. package/src/react-compiler/build/watch-react-library.mjs +111 -0
  20. package/src/react-compiler/policy/advisory-diagnostic.mjs +30 -0
  21. package/src/react-compiler/policy/biome-exit-code.mjs +30 -0
  22. package/src/react-compiler/policy/biome-report.mjs +46 -0
  23. package/src/react-compiler/policy/check-react-19-apis.mjs +30 -0
  24. package/src/react-compiler/policy/check-react-19-repository.mjs +33 -0
  25. package/src/react-compiler/policy/check-react-memoization.mjs +30 -0
  26. package/src/react-compiler/policy/check-repository.mjs +33 -0
  27. package/src/react-compiler/policy/compiler-scope.mjs +73 -0
  28. package/src/react-compiler/policy/find-manual-memoization.mjs +50 -0
  29. package/src/react-compiler/policy/find-react-19-apis.mjs +33 -0
  30. package/src/react-compiler/policy/memoization-exception.mjs +34 -0
  31. package/src/react-compiler/policy/react-19-scope.mjs +74 -0
  32. package/src/react-compiler/policy/react-call-name.mjs +42 -0
  33. package/src/react-compiler/policy/repository-files.mjs +48 -0
  34. package/src/react-compiler/policy/run-biome.mjs +55 -0
  35. package/src/react-compiler/policy/scoped-source.mjs +35 -0
@@ -0,0 +1,47 @@
1
+ /** Mark generated artifacts after the original-source compiler traversal. */
2
+ export function markLibraryCompilerOwnership({ types }) {
3
+ return {
4
+ visitor: {
5
+ Program: {
6
+ exit(programPath) {
7
+ programPath.traverse({
8
+ enter(functionPath) {
9
+ if (!functionPath.isFunction()) {
10
+ return;
11
+ }
12
+ if (!types.isBlockStatement(functionPath.node.body)) {
13
+ functionPath.node.body = types.blockStatement([
14
+ types.returnStatement(functionPath.node.body),
15
+ ]);
16
+ }
17
+ const directives = functionPath.node.body.directives;
18
+ if (
19
+ !directives.some(
20
+ (directive) => directive.value.value === "use no memo",
21
+ )
22
+ ) {
23
+ directives.push(
24
+ types.directive(types.directiveLiteral("use no memo")),
25
+ );
26
+ }
27
+ },
28
+ });
29
+ if (
30
+ programPath.node.directives.some(
31
+ (directive) => directive.value.value === "use no memo",
32
+ )
33
+ ) {
34
+ return;
35
+ }
36
+ const marker = types.directive(types.directiveLiteral("use no memo"));
37
+ types.addComment(
38
+ marker,
39
+ "leading",
40
+ " Generated library output: compilation is owned by the library build.",
41
+ );
42
+ programPath.node.directives.push(marker);
43
+ },
44
+ },
45
+ },
46
+ };
47
+ }
@@ -0,0 +1,53 @@
1
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { artifactInventory } from "./artifact-inventory.mjs";
4
+ import { emittedArtifacts } from "./emitted-artifacts.mjs";
5
+ import { isReactSource } from "./is-react-source.mjs";
6
+ import { transformReactSource } from "./transform-react-source.mjs";
7
+
8
+ export async function overlayReactLibrary({ project, format, compiler }) {
9
+ const inventory = await artifactInventory({
10
+ outDir: project.outDir,
11
+ current: emittedArtifacts(project),
12
+ });
13
+ await inventory.prune();
14
+ try {
15
+ for (const filename of project.files.filter(
16
+ (file) => /\.[cm]?tsx?$/.test(file) && !/\.d\.[cm]?ts$/.test(file),
17
+ )) {
18
+ const source = await readFile(filename, "utf8");
19
+ if (!isReactSource({ source, filename })) {
20
+ continue;
21
+ }
22
+ const output = path.join(
23
+ project.outDir,
24
+ emittedArtifacts({ ...project, files: [filename] })[0],
25
+ );
26
+ const result = await transformReactSource({
27
+ source,
28
+ filename,
29
+ output,
30
+ format,
31
+ compiler,
32
+ options: project.options,
33
+ });
34
+ await mkdir(path.dirname(output), { recursive: true });
35
+ await writeFile(
36
+ output,
37
+ `${result.code}${project.options.sourceMap ? `\n//# sourceMappingURL=${path.basename(output)}.map` : ""}\n`,
38
+ );
39
+ if (project.options.sourceMap) {
40
+ await writeFile(`${output}.map`, JSON.stringify(result.map));
41
+ } else {
42
+ await rm(`${output}.map`, { force: true });
43
+ }
44
+ console.log(
45
+ `[react-compiler] Transformed: ${filename} -> ${output} (compiler ${compiler ? "on" : "off"})`,
46
+ );
47
+ }
48
+ await inventory.save();
49
+ } catch (error) {
50
+ await inventory.invalidate();
51
+ throw error;
52
+ }
53
+ }
@@ -0,0 +1,33 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import path from "node:path";
3
+
4
+ export function readBuildProject(projectPath) {
5
+ const configPath = path.resolve(projectPath);
6
+ const directory = path.dirname(configPath);
7
+ const config = JSON.parse(
8
+ execFileSync(
9
+ "pnpm",
10
+ ["exec", "tsc", "--project", configPath, "--showConfig"],
11
+ { cwd: directory, encoding: "utf8" },
12
+ ),
13
+ );
14
+ const { compilerOptions: options, files } = config;
15
+ if (!options.rootDir || !options.outDir) {
16
+ throw new Error(
17
+ "React library builds require explicit rootDir and outDir in the build tsconfig.",
18
+ );
19
+ }
20
+ const rootDir = path.resolve(directory, options.rootDir);
21
+ const outDir = path.resolve(directory, options.outDir);
22
+ if (rootDir === outDir || rootDir.startsWith(`${outDir}${path.sep}`)) {
23
+ throw new Error("React library outDir must not contain rootDir.");
24
+ }
25
+ return {
26
+ configPath,
27
+ directory,
28
+ options,
29
+ rootDir,
30
+ outDir,
31
+ files: files.map((file) => path.resolve(directory, file)),
32
+ };
33
+ }
@@ -0,0 +1,72 @@
1
+ import path from "node:path";
2
+ import { transformAsync } from "@babel/core";
3
+ import transformCommonjs from "@babel/plugin-transform-modules-commonjs";
4
+ import presetReact from "@babel/preset-react";
5
+ import presetTypescript from "@babel/preset-typescript";
6
+ import reactCompiler from "babel-plugin-react-compiler";
7
+ import { markLibraryCompilerOwnership } from "./mark-library-compiler-ownership.mjs";
8
+
9
+ export async function transformReactSource({
10
+ source,
11
+ filename,
12
+ output,
13
+ compiler,
14
+ format,
15
+ options,
16
+ }) {
17
+ const extension = path.extname(filename);
18
+ if (
19
+ (extension === ".cts" && format === "esm") ||
20
+ (extension === ".mts" && format === "commonjs")
21
+ ) {
22
+ throw new Error(
23
+ `Source extension ${extension} conflicts with --format ${format}: ${filename}`,
24
+ );
25
+ }
26
+ const reactOptions =
27
+ options.jsx === "react"
28
+ ? {
29
+ runtime: "classic",
30
+ pragma: options.jsxFactory,
31
+ pragmaFrag: options.jsxFragmentFactory,
32
+ }
33
+ : {
34
+ runtime: "automatic",
35
+ importSource: options.jsxImportSource,
36
+ development: options.jsx === "react-jsxdev",
37
+ };
38
+ return transformAsync(source, {
39
+ filename,
40
+ configFile: false,
41
+ babelrc: false,
42
+ plugins: [
43
+ ...(compiler
44
+ ? [
45
+ [
46
+ reactCompiler,
47
+ {
48
+ target: "19",
49
+ compilationMode: "infer",
50
+ panicThreshold: "none",
51
+ logger: {
52
+ logEvent(file, event) {
53
+ console.log(
54
+ `[react-compiler] ${event.kind}: ${file} ${event.fnName ?? event.detail?.reason ?? ""}`,
55
+ );
56
+ },
57
+ },
58
+ },
59
+ ],
60
+ ]
61
+ : []),
62
+ ...(format === "commonjs" ? [transformCommonjs] : []),
63
+ markLibraryCompilerOwnership,
64
+ ],
65
+ presets: [
66
+ ...(options.jsx === "preserve" ? [] : [[presetReact, reactOptions]]),
67
+ [presetTypescript, { onlyRemoveTypeImports: true }],
68
+ ],
69
+ sourceMaps: options.inlineSourceMap ? "inline" : Boolean(options.sourceMap),
70
+ sourceFileName: path.relative(path.dirname(output), filename),
71
+ });
72
+ }
@@ -0,0 +1,111 @@
1
+ import { watch } from "node:fs";
2
+ import path from "node:path";
3
+ import { artifactInventory } from "./artifact-inventory.mjs";
4
+ import { createBuildCommandProcess } from "./build-command-process.mjs";
5
+ import { emittedArtifacts } from "./emitted-artifacts.mjs";
6
+ import { overlayReactLibrary } from "./overlay-react-library.mjs";
7
+ import { readBuildProject } from "./read-build-project.mjs";
8
+
9
+ export async function watchReactLibrary({
10
+ project: initialProject,
11
+ format,
12
+ compiler,
13
+ after,
14
+ }) {
15
+ let running = false;
16
+ let stopped = false;
17
+ const command = createBuildCommandProcess();
18
+ let pending = false;
19
+ let timer;
20
+ let project = initialProject;
21
+ const rebuild = async () => {
22
+ if (stopped) {
23
+ return;
24
+ }
25
+ if (running) {
26
+ pending = true;
27
+ return;
28
+ }
29
+ running = true;
30
+ let inventory = await artifactInventory({
31
+ outDir: project.outDir,
32
+ current: emittedArtifacts(project),
33
+ });
34
+ try {
35
+ await inventory.invalidate();
36
+ project = readBuildProject(project.configPath);
37
+ inventory = await artifactInventory({
38
+ outDir: project.outDir,
39
+ current: emittedArtifacts(project),
40
+ });
41
+ await command.run({
42
+ args: ["exec", "tsc", "--project", project.configPath],
43
+ cwd: project.directory,
44
+ });
45
+ await overlayReactLibrary({ project, format, compiler });
46
+ if (stopped) {
47
+ throw new Error("Build stopped");
48
+ }
49
+ if (after) {
50
+ const result = await command.run({
51
+ args: ["run", after],
52
+ cwd: project.directory,
53
+ });
54
+ process.stdout.write(result.stdout);
55
+ process.stderr.write(result.stderr);
56
+ }
57
+ console.log("[react-compiler] Build complete");
58
+ } catch (error) {
59
+ await inventory.invalidate();
60
+ console.error(
61
+ `[react-compiler] Build failed: ${error.message}\n${error.stdout ?? ""}${error.stderr ?? ""}`,
62
+ );
63
+ } finally {
64
+ running = false;
65
+ if (pending) {
66
+ pending = false;
67
+ void rebuild();
68
+ }
69
+ }
70
+ };
71
+ const watcher = watch(
72
+ project.directory,
73
+ { recursive: true },
74
+ (_event, filename) => {
75
+ if (!filename) {
76
+ return;
77
+ }
78
+ const absolute = path.resolve(project.directory, filename.toString());
79
+ if (
80
+ absolute === project.outDir ||
81
+ absolute.startsWith(`${project.outDir}${path.sep}`)
82
+ ) {
83
+ return;
84
+ }
85
+ if (
86
+ absolute !== project.configPath &&
87
+ !(
88
+ absolute.startsWith(`${project.rootDir}${path.sep}`) &&
89
+ /\.[cm]?tsx?$/.test(absolute)
90
+ )
91
+ ) {
92
+ return;
93
+ }
94
+ clearTimeout(timer);
95
+ timer = setTimeout(() => {
96
+ void rebuild();
97
+ }, 80);
98
+ },
99
+ );
100
+ const stop = (exitCode) => {
101
+ stopped = true;
102
+ pending = false;
103
+ clearTimeout(timer);
104
+ watcher.close();
105
+ command.stop();
106
+ process.exitCode = exitCode;
107
+ };
108
+ process.once("SIGTERM", () => stop(143));
109
+ process.once("SIGINT", () => stop(130));
110
+ await rebuild();
111
+ }
@@ -0,0 +1,30 @@
1
+ import path from "node:path";
2
+ import { isScopedSource } from "./scoped-source.mjs";
3
+
4
+ /** Only explicitly adopted compiler and React 19 policies are advisory. */
5
+ export function isAdvisoryDiagnostic({
6
+ diagnostic,
7
+ root,
8
+ scopes,
9
+ react19Scopes = [],
10
+ }) {
11
+ if (diagnostic.severity !== "warning") {
12
+ return false;
13
+ }
14
+ const filename = path
15
+ .relative(root, path.resolve(root, diagnostic.location?.path ?? ""))
16
+ .split(path.sep)
17
+ .join("/");
18
+ const compilerAdvisory =
19
+ diagnostic.category === "lint/nursery/useReactCompiler" ||
20
+ (diagnostic.category === "plugin" &&
21
+ diagnostic.message.startsWith("[no-manual-react-memoization] "));
22
+ if (compilerAdvisory) {
23
+ return isScopedSource({ filename, scopes });
24
+ }
25
+ const react19Advisory =
26
+ diagnostic.category === "lint/suspicious/noReactForwardRef" ||
27
+ (diagnostic.category === "plugin" &&
28
+ diagnostic.message.startsWith("[no-react-use-context] "));
29
+ return react19Advisory && isScopedSource({ filename, scopes: react19Scopes });
30
+ }
@@ -0,0 +1,30 @@
1
+ import { isAdvisoryDiagnostic } from "./advisory-diagnostic.mjs";
2
+
3
+ /** Apply existing warning gates while preserving process and plugin failures. */
4
+ export function biomeExitCode({
5
+ report,
6
+ status,
7
+ warningsAsErrors,
8
+ root,
9
+ scopes,
10
+ react19Scopes = [],
11
+ }) {
12
+ const blockingWarning =
13
+ warningsAsErrors &&
14
+ report.diagnostics.some(
15
+ (diagnostic) =>
16
+ diagnostic.severity === "warning" &&
17
+ !isAdvisoryDiagnostic({ diagnostic, root, scopes, react19Scopes }),
18
+ );
19
+ const pluginFailed = report.diagnostics.some(
20
+ (diagnostic) =>
21
+ diagnostic.category === "plugin" &&
22
+ diagnostic.message.includes(" errored:"),
23
+ );
24
+ return status !== 0 ||
25
+ report.summary.errors > 0 ||
26
+ blockingWarning ||
27
+ pluginFailed
28
+ ? 1
29
+ : 0;
30
+ }
@@ -0,0 +1,46 @@
1
+ const severities = new Set(["fatal", "error", "warning", "info", "hint"]);
2
+
3
+ /** Validate the pinned Biome reporter contract before trusting its diagnostics. */
4
+ export function readBiomeReport(stdout) {
5
+ const report = JSON.parse(stdout.slice(stdout.indexOf("{")));
6
+ if (!report || !Array.isArray(report.diagnostics) || !report.summary) {
7
+ throw new Error("Invalid Biome JSON report");
8
+ }
9
+ const { summary, diagnostics } = report;
10
+ for (const key of ["errors", "warnings", "infos", "diagnosticsNotPrinted"]) {
11
+ if (!Number.isInteger(summary[key]) || summary[key] < 0) {
12
+ throw new Error(`Invalid Biome summary ${key}`);
13
+ }
14
+ }
15
+ if (summary.diagnosticsNotPrinted !== 0) {
16
+ throw new Error("Incomplete Biome report: diagnostics were not printed");
17
+ }
18
+ for (const diagnostic of diagnostics) {
19
+ if (
20
+ !diagnostic ||
21
+ !severities.has(diagnostic.severity) ||
22
+ typeof diagnostic.category !== "string" ||
23
+ typeof diagnostic.message !== "string"
24
+ ) {
25
+ throw new Error("Invalid Biome diagnostic");
26
+ }
27
+ }
28
+ const errors = diagnostics.filter(
29
+ (diagnostic) =>
30
+ diagnostic.severity === "error" || diagnostic.severity === "fatal",
31
+ ).length;
32
+ const warnings = diagnostics.filter(
33
+ (diagnostic) => diagnostic.severity === "warning",
34
+ ).length;
35
+ const infos = diagnostics.length - errors - warnings;
36
+ if (
37
+ summary.errors !== errors ||
38
+ summary.warnings !== warnings ||
39
+ summary.infos !== infos
40
+ ) {
41
+ throw new Error(
42
+ "Incomplete Biome report: diagnostic totals do not match summary",
43
+ );
44
+ }
45
+ return report;
46
+ }
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { checkReact19Apis } from "./check-react-19-repository.mjs";
5
+
6
+ export { checkReact19Apis };
7
+
8
+ if (
9
+ process.argv[1] &&
10
+ import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href
11
+ ) {
12
+ try {
13
+ const findings = checkReact19Apis({
14
+ root: process.cwd(),
15
+ baseRef: process.env.REACT_19_BASE_REF || undefined,
16
+ ci: Boolean(process.env.CI) && process.env.CI !== "false",
17
+ });
18
+ for (const finding of findings) {
19
+ console.log(
20
+ `${finding.severity} ${finding.path}:${finding.line}:${finding.column} ${finding.name}: Migrate to the React 19 API.`,
21
+ );
22
+ }
23
+ process.exitCode = findings.some((finding) => finding.severity === "error")
24
+ ? 1
25
+ : 0;
26
+ } catch (error) {
27
+ console.error(`React 19 API policy: ${error.message}`);
28
+ process.exitCode = 1;
29
+ }
30
+ }
@@ -0,0 +1,33 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { findReact19Apis } from "./find-react-19-apis.mjs";
4
+ import { readReact19Scope } from "./react-19-scope.mjs";
5
+ import { repositoryFiles } from "./repository-files.mjs";
6
+ import { isScopedSource } from "./scoped-source.mjs";
7
+
8
+ /** Check explicitly adopted packages for React APIs superseded in React 19. */
9
+ export function checkReact19Apis({ root, baseRef, ci = false }) {
10
+ const scopes = readReact19Scope({ root });
11
+ if (!scopes.length) {
12
+ return [];
13
+ }
14
+ if (ci && !baseRef) {
15
+ throw new Error(
16
+ "CI must set REACT_19_BASE_REF to the PR base or previous push commit and fetch its history",
17
+ );
18
+ }
19
+ const { files, touched } = repositoryFiles({ root, baseRef });
20
+ return files
21
+ .filter((filename) => isScopedSource({ filename, scopes }))
22
+ .flatMap((filename) => {
23
+ if (!existsSync(path.join(root, filename))) {
24
+ return [];
25
+ }
26
+ const source = readFileSync(path.join(root, filename), "utf8");
27
+ return findReact19Apis({ source, filename }).map((finding) => ({
28
+ ...finding,
29
+ path: filename,
30
+ severity: touched.has(filename) ? "error" : "warning",
31
+ }));
32
+ });
33
+ }
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { checkReactMemoization } from "./check-repository.mjs";
5
+
6
+ export { checkReactMemoization };
7
+
8
+ if (
9
+ process.argv[1] &&
10
+ import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href
11
+ ) {
12
+ try {
13
+ const findings = checkReactMemoization({
14
+ root: process.cwd(),
15
+ baseRef: process.env.REACT_COMPILER_BASE_REF || undefined,
16
+ ci: Boolean(process.env.CI) && process.env.CI !== "false",
17
+ });
18
+ for (const finding of findings) {
19
+ console.log(
20
+ `${finding.severity} ${finding.path}:${finding.line}:${finding.column} ${finding.name}: Prefer React Compiler or document a call-specific exception.`,
21
+ );
22
+ }
23
+ process.exitCode = findings.some((finding) => finding.severity === "error")
24
+ ? 1
25
+ : 0;
26
+ } catch (error) {
27
+ console.error(`React Compiler policy: ${error.message}`);
28
+ process.exitCode = 1;
29
+ }
30
+ }
@@ -0,0 +1,33 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { readCompilerScope } from "./compiler-scope.mjs";
4
+ import { findManualMemoization } from "./find-manual-memoization.mjs";
5
+ import { repositoryFiles } from "./repository-files.mjs";
6
+ import { isScopedSource } from "./scoped-source.mjs";
7
+
8
+ /** Check the adopted repository's manual React memoization policy. */
9
+ export function checkReactMemoization({ root, baseRef, ci = false }) {
10
+ const scopes = readCompilerScope({ root });
11
+ if (!scopes.length) {
12
+ return [];
13
+ }
14
+ if (ci && !baseRef) {
15
+ throw new Error(
16
+ "CI must set REACT_COMPILER_BASE_REF to the PR base or previous push commit and fetch its history",
17
+ );
18
+ }
19
+ const { files, touched } = repositoryFiles({ root, baseRef });
20
+ return files
21
+ .filter((filename) => isScopedSource({ filename, scopes }))
22
+ .flatMap((filename) => {
23
+ if (!existsSync(path.join(root, filename))) {
24
+ return [];
25
+ }
26
+ const source = readFileSync(path.join(root, filename), "utf8");
27
+ return findManualMemoization({ source, filename }).map((finding) => ({
28
+ ...finding,
29
+ path: filename,
30
+ severity: touched.has(filename) ? "error" : "warning",
31
+ }));
32
+ });
33
+ }
@@ -0,0 +1,73 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { parse } from "jsonc-parser";
4
+ import { memoizationExclusions } from "./scoped-source.mjs";
5
+
6
+ export const memoizationPlugin = "no-manual-react-memoization.grit";
7
+
8
+ /** Return the explicitly adopted package roots from the root Biome config. */
9
+ export function readCompilerScope({ root }) {
10
+ const filename = ["biome.json", "biome.jsonc"]
11
+ .map((name) => path.join(root, name))
12
+ .find(existsSync);
13
+ if (!filename) {
14
+ return [];
15
+ }
16
+ const errors = [];
17
+ const config = parse(readFileSync(filename, "utf8"), errors, {
18
+ allowTrailingComma: true,
19
+ });
20
+ if (errors.length || !config || typeof config !== "object") {
21
+ throw new Error("Invalid root Biome JSONC configuration");
22
+ }
23
+ const plugins = (config.plugins ?? []).filter(
24
+ (plugin) =>
25
+ path.basename(
26
+ typeof plugin === "string" ? plugin : (plugin.path ?? ""),
27
+ ) === memoizationPlugin,
28
+ );
29
+ if (!plugins.length) {
30
+ return [];
31
+ }
32
+ const patterns = plugins.flatMap((plugin) => {
33
+ if (
34
+ typeof plugin === "string" ||
35
+ !Array.isArray(plugin.includes) ||
36
+ !plugin.includes.length
37
+ ) {
38
+ throw new Error("Compiler scope requires explicit package-root includes");
39
+ }
40
+ return plugin.includes;
41
+ });
42
+ for (const pattern of patterns) {
43
+ if (memoizationExclusions.includes(pattern)) {
44
+ continue;
45
+ }
46
+ if (
47
+ typeof pattern !== "string" ||
48
+ !/^\*\*\/(?:[a-zA-Z0-9_-]+\/)+[a-zA-Z0-9_-]+\/\*\*$/.test(pattern)
49
+ ) {
50
+ throw new Error(
51
+ `Compiler scope must use literal package-root patterns: ${pattern}`,
52
+ );
53
+ }
54
+ }
55
+ const diagnosticPatterns = (config.overrides ?? []).flatMap((override) => {
56
+ const rule = override.linter?.rules?.nursery?.useReactCompiler;
57
+ const level = typeof rule === "string" ? rule : rule?.level;
58
+ return level && level !== "off" ? (override.includes ?? []) : [];
59
+ });
60
+ const normalize = (values) => JSON.stringify([...new Set(values)].sort());
61
+ if (normalize(patterns) !== normalize(diagnosticPatterns)) {
62
+ throw new Error(
63
+ "React Compiler diagnostic scope must exactly match manual memoization plugin scope",
64
+ );
65
+ }
66
+ return [
67
+ ...new Set(
68
+ patterns
69
+ .filter((pattern) => !pattern.startsWith("!"))
70
+ .map((pattern) => pattern.slice(3, -3)),
71
+ ),
72
+ ];
73
+ }
@@ -0,0 +1,50 @@
1
+ import { parse } from "@babel/parser";
2
+ import traverseModule from "@babel/traverse";
3
+ import { hasMemoizationException } from "./memoization-exception.mjs";
4
+ import { reactCallName } from "./react-call-name.mjs";
5
+
6
+ const traverse = traverseModule.default ?? traverseModule;
7
+ const memoizationNames = new Set(["useMemo", "useCallback", "memo"]);
8
+
9
+ /** Resolve React calls through lexical imports, rather than spelling alone. */
10
+ export function findManualMemoization({ source, filename }) {
11
+ const ast = parse(source, {
12
+ sourceType: "unambiguous",
13
+ sourceFilename: filename,
14
+ plugins: [
15
+ "typescript",
16
+ ...(/\.[cm]?ts$/.test(filename) ? [] : ["jsx"]),
17
+ "decorators-legacy",
18
+ ],
19
+ });
20
+ const findings = [];
21
+ traverse(ast, {
22
+ "CallExpression|OptionalCallExpression"(call) {
23
+ const callee = call.get("callee");
24
+ const name = reactCallName(callee);
25
+ if (!memoizationNames.has(name)) {
26
+ return;
27
+ }
28
+
29
+ findings.push({
30
+ name,
31
+ line: call.node.loc.start.line,
32
+ column: call.node.loc.start.column + 1,
33
+ canonical: callee.isIdentifier() && callee.node.name === name,
34
+ statement: call.getStatementParent()?.node,
35
+ start: call.node.start,
36
+ });
37
+ },
38
+ });
39
+ return findings
40
+ .filter(
41
+ (finding) =>
42
+ !hasMemoizationException({
43
+ finding,
44
+ findings,
45
+ source,
46
+ comments: ast.comments,
47
+ }),
48
+ )
49
+ .map(({ name, line, column }) => ({ name, line, column }));
50
+ }