@servrox/code-quality 0.0.0-stage → 0.2.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.
@@ -0,0 +1,163 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { lstatSync, realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ /** @typedef {"all" | "changed" | "staged" | "unstaged"} Scope */
6
+
7
+ /** @param {string} cwd @param {string[]} args @param {number[]} [successStatuses] */
8
+ const git = (cwd, args, successStatuses = [0]) => {
9
+ const result = spawnSync("git", args, {
10
+ cwd,
11
+ encoding: "utf-8",
12
+ maxBuffer: 32 * 1024 * 1024,
13
+ });
14
+
15
+ if (result.error !== undefined) {
16
+ throw result.error;
17
+ }
18
+
19
+ if (result.status === null || !successStatuses.includes(result.status)) {
20
+ throw new Error(result.stderr.trim() || "Git did not complete.");
21
+ }
22
+
23
+ return result.stdout;
24
+ };
25
+
26
+ /** @param {string} cwd - Directory inside the Git worktree. */
27
+ export const repositoryRoot = (cwd) => git(cwd, ["rev-parse", "--show-toplevel"]).slice(0, -1);
28
+
29
+ /** @param {string} output - NUL-delimited Git paths. */
30
+ const pathsFrom = (output) => output.split("\0").filter((file) => file !== "");
31
+
32
+ /** @param {string} root @param {string | undefined} base */
33
+ const baseCommit = (root, base) => {
34
+ const revision = git(
35
+ root,
36
+ [
37
+ "rev-parse",
38
+ "--verify",
39
+ ...(base === undefined ? ["--quiet"] : []),
40
+ "--end-of-options",
41
+ `${base ?? "HEAD"}^{commit}`,
42
+ ],
43
+ base === undefined ? [0, 1] : [0]
44
+ ).trim();
45
+
46
+ return revision === "" ? undefined : revision;
47
+ };
48
+
49
+ // Numstat compares contents even with external diff drivers disabled, avoiding
50
+ // stat-only changes without refreshing the index. Renames stay disabled so each
51
+ // NUL-delimited record contains two counts followed by one literal path.
52
+ /** @param {string} root @param {string[]} args @param {string[]} pathspecs @param {boolean} [includeDeleted] */
53
+ const changed = (root, args, pathspecs, includeDeleted = false) =>
54
+ pathsFrom(
55
+ git(
56
+ root,
57
+ [
58
+ "-c",
59
+ "diff.autoRefreshIndex=false",
60
+ "diff",
61
+ "--no-renames",
62
+ "--no-ext-diff",
63
+ "--no-textconv",
64
+ "--numstat",
65
+ "--exit-code",
66
+ ...(includeDeleted ? [] : ["--diff-filter=ACMTU"]),
67
+ "-z",
68
+ ...args,
69
+ "--",
70
+ ...pathspecs,
71
+ ],
72
+ [0, 1]
73
+ )
74
+ ).map((record) => record.split("\t").slice(2).join("\t"));
75
+
76
+ /** @param {string} root @param {string[]} staged @param {string[]} pathspecs */
77
+ const requireIndexContent = (root, staged, pathspecs) => {
78
+ const hidden = new Set(
79
+ pathsFrom(git(root, ["ls-files", "-v", "-z", "--", ...pathspecs]))
80
+ .filter((entry) => /^[a-zS] /u.test(entry))
81
+ .map((entry) => entry.slice(2))
82
+ );
83
+
84
+ const flagged = staged.filter((file) => hidden.has(file));
85
+
86
+ if (flagged.length > 0) {
87
+ const files = flagged.map((file) => JSON.stringify(file)).join(", ");
88
+
89
+ throw new Error(
90
+ `Cannot verify staged content for paths marked assume-unchanged or skip-worktree: ${files}. Clear these index flags before checking staged content.`
91
+ );
92
+ }
93
+
94
+ const unstaged = new Set(changed(root, [], pathspecs, true));
95
+
96
+ const mismatches = staged.filter((file) => unstaged.has(file));
97
+
98
+ if (mismatches.length > 0) {
99
+ const files = mismatches.map((file) => JSON.stringify(file)).join(", ");
100
+
101
+ throw new Error(
102
+ `Staged paths also have unstaged changes: ${files}. Use --scope changed to check the working copy, or make the index and working copy agree for these paths.`
103
+ );
104
+ }
105
+ };
106
+
107
+ /** @param {{ root: string, scope: Scope, base?: string, pathspecs: string[] }} options - Git selection arguments. */
108
+ export const selectFiles = ({ root, scope, base, pathspecs }) => {
109
+ const revision = scope === "changed" ? baseCommit(root, base) : undefined;
110
+
111
+ if (scope === "all" || (scope === "changed" && revision === undefined)) {
112
+ return pathsFrom(
113
+ git(root, [
114
+ "ls-files",
115
+ "--cached",
116
+ "--others",
117
+ "--exclude-standard",
118
+ "-z",
119
+ "--",
120
+ ...pathspecs,
121
+ ])
122
+ );
123
+ }
124
+
125
+ if (scope === "staged") {
126
+ const staged = changed(root, ["--cached"], pathspecs);
127
+
128
+ requireIndexContent(root, staged, pathspecs);
129
+
130
+ return staged;
131
+ }
132
+
133
+ const untracked = pathsFrom(
134
+ git(root, ["ls-files", "--others", "--exclude-standard", "-z", "--", ...pathspecs])
135
+ );
136
+
137
+ return [...changed(root, revision === undefined ? [] : [revision], pathspecs), ...untracked];
138
+ };
139
+
140
+ /** @param {string} root @param {string[]} files */
141
+ export const regularFiles = (root, files) => {
142
+ const canonicalRoot = realpathSync(root);
143
+
144
+ return [...new Set(files)]
145
+ .filter((file) => {
146
+ const candidate = path.resolve(root, file);
147
+ let directory = canonicalRoot;
148
+
149
+ for (const component of file.split("/").slice(0, -1)) {
150
+ directory = path.join(directory, component);
151
+
152
+ if (lstatSync(directory, { throwIfNoEntry: false })?.isDirectory() !== true) {
153
+ return false;
154
+ }
155
+ }
156
+
157
+ return (
158
+ lstatSync(candidate, { throwIfNoEntry: false })?.isFile() === true &&
159
+ realpathSync(candidate).startsWith(canonicalRoot + path.sep)
160
+ );
161
+ })
162
+ .toSorted();
163
+ };
@@ -0,0 +1,46 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const require = createRequire(import.meta.url);
7
+ const toolProcess = fileURLToPath(new URL("tool-process.mjs", import.meta.url));
8
+
9
+ /** @param {"oxlint" | "oxfmt"} tool - Installed Oxc tool. */
10
+ const toolEntry = (tool) =>
11
+ path.join(path.dirname(require.resolve(`${tool}/package.json`)), "bin", tool);
12
+
13
+ /** @param {string} root @param {"oxlint" | "oxfmt"} tool @param {string | undefined} config @param {string[]} files */
14
+ export const runTool = (root, tool, config, files) => {
15
+ console.log(`${tool}: ${files.length} selected files`);
16
+
17
+ if (files.length === 0) {
18
+ return 0;
19
+ }
20
+
21
+ const args = ["--no-error-on-unmatched-pattern"];
22
+
23
+ if (tool === "oxfmt") {
24
+ args.push("--check");
25
+ }
26
+
27
+ if (config !== undefined) {
28
+ args.push("--config", config);
29
+ }
30
+
31
+ // Keep leading `!` filenames literal for Oxfmt's glob parser.
32
+ const operands = files.map((file) => `./${file}`);
33
+
34
+ // Transport argv over stdin to preserve one warning budget without OS argument limits.
35
+ const result = spawnSync(process.execPath, [toolProcess], {
36
+ cwd: root,
37
+ input: JSON.stringify({ args: [...args, "--", ...operands], entry: toolEntry(tool) }),
38
+ stdio: ["pipe", "inherit", "inherit"],
39
+ });
40
+
41
+ if (result.error !== undefined) {
42
+ throw result.error;
43
+ }
44
+
45
+ return result.status ?? 1;
46
+ };
@@ -0,0 +1,13 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { pathToFileURL } from "node:url";
3
+
4
+ import { z } from "zod";
5
+
6
+ const invocation = z
7
+ .object({ args: z.array(z.string()), entry: z.string() })
8
+ .strict()
9
+ .parse(JSON.parse(readFileSync(0, "utf-8")));
10
+
11
+ process.argv = [process.execPath, invocation.entry, ...invocation.args];
12
+
13
+ await import(pathToFileURL(invocation.entry).href);
@@ -0,0 +1,20 @@
1
+ module.exports = {
2
+ forbidden: [
3
+ {
4
+ name: "no-runtime-cycles",
5
+ severity: "error",
6
+ comment: "Keep runtime imports acyclic; type-only references are excluded.",
7
+ from: {},
8
+ to: { circular: true },
9
+ },
10
+ ],
11
+ options: {
12
+ doNotFollow: { path: "node_modules" },
13
+ // Remove erased imports before cycle detection; filtering one reported cycle can hide another.
14
+ tsPreCompilationDeps: false,
15
+ enhancedResolveOptions: {
16
+ exportsFields: ["exports"],
17
+ conditionNames: ["import", "require", "node", "default"],
18
+ },
19
+ },
20
+ };
@@ -0,0 +1,8 @@
1
+ import type { IConfiguration } from "dependency-cruiser" with { "resolution-mode": "import" };
2
+
3
+ declare const config: IConfiguration & {
4
+ forbidden: NonNullable<IConfiguration["forbidden"]>;
5
+ options: NonNullable<IConfiguration["options"]>;
6
+ };
7
+
8
+ export = config;
@@ -0,0 +1,54 @@
1
+ const path = require("node:path");
2
+
3
+ const core = require("./core.cjs");
4
+
5
+ /** @param {string} baseDir - Absolute directory used for graph paths. */
6
+ const qualityPackagePaths = (baseDir) => {
7
+ const paths = ["(^|/)node_modules/@servrox/code-quality(/|$)"];
8
+
9
+ const linkedRoot = path
10
+ .relative(baseDir, path.resolve(__dirname, ".."))
11
+ .replaceAll(path.sep, "/");
12
+
13
+ if (linkedRoot !== "") {
14
+ const escapedRoot = linkedRoot.replaceAll(/[.*+?^$(){}|[\]\\]/gu, "\\$&");
15
+
16
+ paths.push(`^${escapedRoot}(/|$)`);
17
+ }
18
+
19
+ return paths;
20
+ };
21
+
22
+ /** @param {{ baseDir?: string }} [settings] - Consumer analysis root. */
23
+ module.exports = function createRuntimeConfig({ baseDir = process.cwd() } = {}) {
24
+ const resolvedBaseDir = path.resolve(baseDir);
25
+
26
+ return {
27
+ options: { ...core.options, baseDir: resolvedBaseDir },
28
+ forbidden: [
29
+ ...core.forbidden,
30
+ {
31
+ name: "no-unresolved-runtime-imports",
32
+ severity: "error",
33
+ from: {},
34
+ to: { couldNotResolve: true },
35
+ },
36
+ {
37
+ name: "no-undeclared-runtime-imports",
38
+ severity: "error",
39
+ from: {},
40
+ to: {
41
+ dependencyTypes: ["npm-no-pkg", "npm-unknown"],
42
+ // Dependency Cruiser checks the #alias rather than its mapped package in the manifest.
43
+ dependencyTypesNot: ["aliased-subpath-import"],
44
+ },
45
+ },
46
+ {
47
+ name: "no-runtime-to-quality-tooling",
48
+ severity: "error",
49
+ from: {},
50
+ to: { path: qualityPackagePaths(resolvedBaseDir) },
51
+ },
52
+ ],
53
+ };
54
+ };
@@ -0,0 +1,8 @@
1
+ import type { IConfiguration } from "dependency-cruiser" with { "resolution-mode": "import" };
2
+
3
+ declare function createRuntimeConfig(settings?: { baseDir?: string }): IConfiguration & {
4
+ forbidden: NonNullable<IConfiguration["forbidden"]>;
5
+ options: NonNullable<IConfiguration["options"]> & { baseDir: string };
6
+ };
7
+
8
+ export = createRuntimeConfig;
@@ -0,0 +1,9 @@
1
+ const core = require("./core.cjs");
2
+ const createRuntimeConfig = require("./create-runtime-config.cjs");
3
+
4
+ const config = createRuntimeConfig();
5
+
6
+ module.exports = {
7
+ options: core.options,
8
+ forbidden: config.forbidden,
9
+ };
package/jscpd/cli.mjs ADDED
@@ -0,0 +1,204 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from "node:child_process";
3
+ import {
4
+ copyFileSync,
5
+ existsSync,
6
+ lstatSync,
7
+ mkdtempSync,
8
+ readFileSync,
9
+ renameSync,
10
+ rmSync,
11
+ writeFileSync,
12
+ } from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import path from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+ import { parseArgs } from "node:util";
17
+
18
+ import { z } from "zod";
19
+
20
+ import preset from "./core.json" with { type: "json" };
21
+
22
+ const usage =
23
+ "Usage: code-quality-duplicates <check|report|update-baseline> " +
24
+ "[--baseline <file>] [--threshold <0..100>] [--ignore <glob> ...] -- <roots...>";
25
+
26
+ const modes = z.enum(["check", "report", "update-baseline"]);
27
+
28
+ const defaults = z
29
+ .looseObject({ threshold: z.number(), ignore: z.array(z.string()) })
30
+ .parse(preset);
31
+
32
+ const thresholdWithoutBaseline = {
33
+ check: 0,
34
+ report: defaults.threshold,
35
+ "update-baseline": defaults.threshold,
36
+ };
37
+
38
+ const baselineSchema = z.object({
39
+ version: z.literal(1),
40
+ fingerprints: z.record(z.string().regex(/^[0-9a-f]{16}$/u), z.number().int().positive()),
41
+ });
42
+
43
+ const runnerManifest = z.object({ bin: z.object({ jscpd: z.string().min(1) }) });
44
+
45
+ /** @param {string} file - Native jscpd baseline file. */
46
+ const readBaseline = (file) => {
47
+ try {
48
+ baselineSchema.parse(JSON.parse(readFileSync(file, "utf-8")));
49
+ } catch (error) {
50
+ throw new Error(`Missing or invalid jscpd baseline: ${file}`, { cause: error });
51
+ }
52
+ };
53
+
54
+ const resolveRunner = () => {
55
+ let manifest;
56
+
57
+ try {
58
+ manifest = new URL(import.meta.resolve("jscpd/package.json"));
59
+ } catch (error) {
60
+ throw new Error("Install the jscpd peer dependency to run this command.", { cause: error });
61
+ }
62
+
63
+ const { bin } = runnerManifest.parse(JSON.parse(readFileSync(manifest, "utf-8")));
64
+
65
+ return fileURLToPath(new URL(bin.jscpd, manifest));
66
+ };
67
+
68
+ /**
69
+ * @param {string | undefined} value - Optional total limit.
70
+ * @param {z.infer<typeof modes>} mode - Scan mode.
71
+ * @param {string | undefined} baseline - Explicit baseline path.
72
+ */
73
+ const parseThreshold = (value, mode, baseline) => {
74
+ const fallback = baseline === undefined ? thresholdWithoutBaseline[mode] : defaults.threshold;
75
+ const threshold = Number(value ?? fallback);
76
+
77
+ if (value?.trim() === "" || !Number.isFinite(threshold) || threshold < 0 || threshold > 100) {
78
+ throw new Error("--threshold must be a percentage between 0 and 100.");
79
+ }
80
+
81
+ return threshold;
82
+ };
83
+
84
+ const parseInvocation = () => {
85
+ const { positionals, values } = parseArgs({
86
+ allowPositionals: true,
87
+ options: {
88
+ baseline: { type: "string" },
89
+ help: { type: "boolean", short: "h" },
90
+ ignore: { type: "string", multiple: true, default: [] },
91
+ threshold: { type: "string" },
92
+ },
93
+ });
94
+
95
+ if (values.help === true) {
96
+ return null;
97
+ }
98
+
99
+ const mode = modes.parse(positionals[0]);
100
+ const roots = z.array(z.string().min(1)).min(1).parse(positionals.slice(1));
101
+
102
+ const baseline =
103
+ values.baseline === undefined
104
+ ? undefined
105
+ : path.resolve(z.string().min(1).parse(values.baseline));
106
+
107
+ if (mode === "update-baseline" && baseline === undefined) {
108
+ throw new Error(`${mode} requires --baseline <file>.`);
109
+ }
110
+
111
+ if (mode === "report" && baseline !== undefined) {
112
+ throw new Error("report does not use a baseline.");
113
+ }
114
+
115
+ const threshold = parseThreshold(values.threshold, mode, baseline);
116
+
117
+ return { mode, roots, threshold, baseline, ignore: values.ignore };
118
+ };
119
+
120
+ /** @typedef {NonNullable<ReturnType<typeof parseInvocation>>} Invocation */
121
+
122
+ /**
123
+ * @param {Invocation} invocation - Parsed scan settings.
124
+ * @param {string} directory - Isolated configuration directory.
125
+ */
126
+ const runScan = ({ mode, roots, threshold, baseline, ignore }, directory) => {
127
+ const config = path.join(directory, "jscpd.json");
128
+
129
+ writeFileSync(
130
+ config,
131
+ JSON.stringify({ ...defaults, threshold, baseline, ignore: [...defaults.ignore, ...ignore] })
132
+ );
133
+
134
+ const args = [resolveRunner(), "--config", config, "--fail-on-empty", "--no-tips"];
135
+
136
+ if (mode === "check" && baseline !== undefined) {
137
+ readBaseline(baseline);
138
+ console.log(`Duplicate limits: ${threshold}% total and 0 new clones.`);
139
+ args.push("--fail-on-new-clones", "0");
140
+ } else if (mode === "update-baseline") {
141
+ args.push("--update-baseline");
142
+ }
143
+
144
+ const result = spawnSync(process.execPath, [...args, "--", ...roots], { stdio: "inherit" });
145
+
146
+ if (result.status === null) {
147
+ throw result.error ?? new Error(`jscpd was interrupted (${result.signal}).`);
148
+ }
149
+
150
+ return result.status;
151
+ };
152
+
153
+ /**
154
+ * @param {Invocation} invocation - Parsed baseline update.
155
+ * @param {string} directory - Staging directory on the baseline's filesystem.
156
+ */
157
+ const updateBaseline = (invocation, directory) => {
158
+ const { baseline } = invocation;
159
+ const candidate = path.join(directory, "baseline.json");
160
+ const destination = lstatSync(baseline, { throwIfNoEntry: false });
161
+
162
+ if (destination !== undefined && destination.isSymbolicLink()) {
163
+ throw new Error("The jscpd baseline is a symbolic link. Update its target directly.");
164
+ }
165
+
166
+ if (existsSync(baseline)) {
167
+ copyFileSync(baseline, candidate);
168
+ }
169
+
170
+ const status = runScan({ ...invocation, baseline: candidate }, directory);
171
+
172
+ if (status === 0) {
173
+ readBaseline(candidate);
174
+ renameSync(candidate, baseline);
175
+ }
176
+
177
+ return status;
178
+ };
179
+
180
+ /** @param {Invocation} invocation - Parsed CLI settings. */
181
+ const run = (invocation) => {
182
+ const updating = invocation.mode === "update-baseline";
183
+ const parent = updating ? path.dirname(invocation.baseline) : tmpdir();
184
+ const directory = mkdtempSync(path.join(parent, ".quality-jscpd-"));
185
+
186
+ try {
187
+ return updating ? updateBaseline(invocation, directory) : runScan(invocation, directory);
188
+ } finally {
189
+ rmSync(directory, { recursive: true, force: true });
190
+ }
191
+ };
192
+
193
+ try {
194
+ const invocation = parseInvocation();
195
+
196
+ if (invocation === null) {
197
+ console.log(usage);
198
+ } else {
199
+ process.exitCode = run(invocation);
200
+ }
201
+ } catch (error) {
202
+ console.error("code-quality-duplicates:", error instanceof Error ? error.message : error);
203
+ process.exitCode = 1;
204
+ }
@@ -0,0 +1,24 @@
1
+ {
2
+ "threshold": 3,
3
+ "minLines": 5,
4
+ "minTokens": 50,
5
+ "mode": "mild",
6
+ "pattern": "**/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}",
7
+ "reporters": ["console"],
8
+ "ignore": [
9
+ "**/node_modules/**",
10
+ "**/dist/**",
11
+ "**/build/**",
12
+ "**/coverage/**",
13
+ "**/generated/**",
14
+ "**/_generated/**",
15
+ "**/*.gen.*",
16
+ "**/.astro/**",
17
+ "**/.next/**",
18
+ "**/.output/**",
19
+ "**/.cache/**",
20
+ "**/test-results/**",
21
+ "**/playwright-report/**",
22
+ "**/reports/**"
23
+ ]
24
+ }
@@ -0,0 +1,4 @@
1
+ import type ultracite from "ultracite/oxfmt";
2
+
3
+ declare const config: typeof ultracite & { printWidth: 100 };
4
+ export default config;
package/oxfmt/core.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import ultracite from "ultracite/oxfmt";
2
+
3
+ export default { ...ultracite, printWidth: 100 };
@@ -0,0 +1 @@
1
+ export { default } from "ultracite/oxlint/anti-slop";
@@ -0,0 +1 @@
1
+ export { default } from "ultracite/oxlint/anti-slop";
@@ -0,0 +1 @@
1
+ export { default } from "ultracite/oxlint/core";
@@ -0,0 +1 @@
1
+ export { default } from "ultracite/oxlint/core";
@@ -0,0 +1,6 @@
1
+ import type { OxlintConfig } from "oxlint";
2
+
3
+ export declare const functionRestrictions: { selector: string; message: string }[];
4
+ export declare const exportRestrictions: { selector: string; message: string }[];
5
+ declare const config: OxlintConfig;
6
+ export default config;