@servrox/code-quality 0.1.0 → 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.
package/README.md CHANGED
@@ -4,14 +4,14 @@
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/%40servrox%2Fcode-quality)](https://www.npmjs.com/package/@servrox/code-quality) [![Package checks](https://github.com/servrox/code-quality/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/servrox/code-quality/actions/workflows/ci.yml) [![Apache-2.0 license](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/servrox/code-quality/blob/main/LICENSE)
6
6
 
7
- Share linting, formatting, duplication, and dependency rules across TypeScript projects. The package provides versioned Ultracite and Oxc presets tested together. Each consumer owns its framework selection, paths, and migration baselines.
7
+ Share linting, formatting, duplication, and dependency rules across TypeScript projects. The package provides versioned Ultracite and Oxc presets tested together. Each consumer owns its framework selection and scan paths.
8
8
 
9
9
  ## Quick start
10
10
 
11
- Use Node.js **24.15.0 or newer**. Once `0.1.0` is available on npm, install it with the matching tools.
11
+ Use Node.js **24.15.0 or newer**. Install the published npm package with the matching tools. The Git-scoped check CLI, duplicate-check CLI, runtime dependency preset, and runtime configuration factory require `0.2.0` or newer. If npm `latest` is still `0.1.0`, use a reviewed Git commit below to try those additions before the next release.
12
12
 
13
13
  ```sh
14
- pnpm add -D -E @servrox/code-quality@0.1.0 \
14
+ pnpm add -D -E @servrox/code-quality@latest \
15
15
  ultracite@8.2.1 oxlint@1.93.0 oxfmt@0.78.0 oxlint-tsgolint@7.0.2007
16
16
  ```
17
17
 
@@ -66,31 +66,112 @@ export default defineConfig({
66
66
 
67
67
  Projects keep root-only Oxlint options at their root. Environments, ignores and framework-specific paths remain explicit in each consumer. React applies only to React workspaces. Enable other framework tooling when the project adopts it.
68
68
 
69
- For an existing codebase, introduce additional policies separately from an already-passing core gate. The optional baseline helpers support measured adoption; this repository contains **no application baselines**.
69
+ For an existing codebase, run the additional checks directly and fix the reported findings. Use the optional baseline helpers only after the maintainer explicitly approves a scoped migration exception.
70
70
 
71
71
  Run `pnpm exec ultracite check` from the project root. Commit the manifest and lockfile with your project configs. Use `pnpm install --frozen-lockfile` in CI.
72
72
 
73
+ ### Adapt the presets to a monorepo
74
+
75
+ Declare framework roots in the consumer config. Apply React rules to Next.js and other React workspaces, including their TypeScript hooks. Include explicit ESM/CommonJS extensions (`.mjs`, `.cjs`, `.mts`, `.cts`) so those modules receive the same checks. Apply the Next.js plugin and its root setting to the Next.js apps. List shared UI packages explicitly.
76
+
77
+ ```ts
78
+ import react from "@servrox/code-quality/oxlint/react";
79
+ import { defineConfig } from "oxlint";
80
+
81
+ const nextRoots = ["apps/storefront", "apps/admin"];
82
+ const nextFiles = nextRoots.map((root) => `${root}/**/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts}`);
83
+
84
+ export default defineConfig({
85
+ // Add these settings and overrides to the quick-start config.
86
+ settings: { next: { rootDir: nextRoots } },
87
+ overrides: [
88
+ {
89
+ files: nextFiles,
90
+ env: { browser: true },
91
+ plugins: [...react.plugins, "nextjs"],
92
+ rules: react.rules,
93
+ },
94
+ {
95
+ files: [
96
+ "apps/docs/**/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts}",
97
+ "packages/ui/**/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts}",
98
+ ],
99
+ env: { browser: true },
100
+ plugins: react.plugins,
101
+ rules: react.rules,
102
+ },
103
+ ],
104
+ });
105
+ ```
106
+
107
+ Set import aliases, ordering, and Tailwind helpers in the consumer's formatter config. For Tailwind v4, resolve the stylesheet path from the config file so it is stable when invoked from different workspace directories.
108
+
109
+ ```ts
110
+ import path from "node:path";
111
+
112
+ import shared from "@servrox/code-quality/oxfmt";
113
+ import { defineConfig } from "oxfmt";
114
+
115
+ export default defineConfig({
116
+ ...shared,
117
+ sortImports: { ...shared.sortImports, internalPattern: ["@repo/", "@/"] },
118
+ sortTailwindcss: {
119
+ ...shared.sortTailwindcss,
120
+ functions: ["clsx", "cn", "cva"],
121
+ stylesheet: path.resolve(import.meta.dirname, "packages/ui/src/styles/globals.css"),
122
+ },
123
+ });
124
+ ```
125
+
126
+ Use precise ignore patterns for generated artifacts. For package entrypoints declared in a manifest, an exact-file Oxlint override can retain `functionRestrictions` from `@servrox/code-quality/oxlint/modularity` as the `eslint-js/no-restricted-syntax` options. That keeps the function budget in those entrypoints while permitting their public export surface.
127
+
73
128
  ### Set up with a coding agent
74
129
 
75
130
  Use the [Agent Skills repository](https://github.com/stark-ai-de/agent-skills) for installation and usage instructions for your agent. Give the agent this setup prompt from your project root.
76
131
 
77
- > Set up `@servrox/code-quality` using the [package quick start](https://github.com/servrox/code-quality#quick-start). Inspect the existing lint and format configs, package scripts, and CI first. Use an exact public npm version, or a reviewed full Git SHA if the version is unavailable. Wire the presets into the existing config, run the project's checks, and report any existing failures before expanding the enforced rules.
132
+ > Set up `@servrox/code-quality` using the [package quick start](https://github.com/servrox/code-quality#quick-start). Inspect the existing lint and format configs, package scripts, and CI first. Use an exact public npm version, or a reviewed full Git SHA if the version is unavailable. Wire the presets into the existing config, run the project's checks, and fix the reported findings. Get explicit maintainer approval before creating or using a baseline.
133
+
134
+ ## Choose which files to check
135
+
136
+ `code-quality-check` runs Oxlint and Oxfmt from the Git root and never applies fixes or refreshes the Git index. Both tools use the consumer's config discovery, supported file types, ignore rules, and language associations. With separate configs, pass `--oxlint-config <path>` and `--oxfmt-config <path>` (relative to the invoking directory). Lint warning limits apply to the complete selection.
137
+
138
+ | Scope | Files checked |
139
+ | --- | --- |
140
+ | `changed` (default) | Working-tree differences from `HEAD` or an explicit `--base <ref>`, plus non-ignored untracked files. Before the first commit, the default checks all tracked and non-ignored untracked working files. An explicit base must resolve to a commit. |
141
+ | `staged` | Files changed in the Git index. If a selected path also has unstaged changes or carries an `assume-unchanged` / `skip-worktree` flag, the command exits before checking to avoid checking different content from the one being committed. Clear those index flags before checking staged content. |
142
+ | `unstaged` | Working-tree differences from the index, plus non-ignored untracked files |
143
+ | `all` | Tracked files and non-ignored untracked files in the working tree |
144
+
145
+ Scopes select whole files and skip deleted paths, symlinks, and paths outside the checkout. Git pathspecs after `--` are relative to the Git root, including when invoked from a subdirectory. A check with no selected files succeeds without launching the tool. If a tool ignores every selected file or supports none of them, its check also succeeds without scanning other files.
146
+
147
+ Git selection compares file content without external diff or `textconv` display drivers, so those drivers cannot hide changes or write textconv caches. Selected filenames are passed literally to the tools, including names beginning with `!`.
148
+
149
+ ```sh
150
+ pnpm exec code-quality-check --scope staged --check lint
151
+ pnpm exec code-quality-check --scope unstaged --check format
152
+ pnpm exec code-quality-check --scope changed --base "$(git merge-base HEAD origin/main)" -- apps packages
153
+ pnpm exec code-quality-check --scope all
154
+ ```
155
+
156
+ Choose the base explicitly for branch or PR comparisons. Checks that need a full graph, such as dependency analysis and duplicate detection across unchanged files, have their own commands.
78
157
 
79
158
  ## Public exports
80
159
 
81
- | Export | Responsibility |
82
- | --------------------- | ---------------------------------------------------------- |
83
- | `/oxlint/core` | Ultracite core |
84
- | `/oxlint/strict` | Native complexity/size rules, selected Unicorn and SonarJS |
85
- | `/oxlint/modularity` | File length and syntax-based function/export budgets |
86
- | `/oxlint/anti-slop` | Ultracite's bundled Anti-Slop |
87
- | `/oxlint/react` | Ultracite React rules |
88
- | `/oxlint/playwright` | Native Ultracite Playwright compatibility overrides |
89
- | `/oxfmt` | Ultracite formatting, 100-column width |
90
- | `/jscpd` | Duplicate-detection defaults, 3% target |
91
- | `/dependency-cruiser` | Runtime-cycle policy and runtime resolution defaults |
92
- | `/baseline` | Validated reports and non-increasing diagnostic budgets |
93
- | `/package.json` | Version and export metadata |
160
+ | Export | Responsibility |
161
+ | --- | --- |
162
+ | `/oxlint/core` | Ultracite core |
163
+ | `/oxlint/strict` | Native complexity/size rules, selected Unicorn and SonarJS |
164
+ | `/oxlint/modularity` | File length and syntax-based function/export budgets |
165
+ | `/oxlint/anti-slop` | Ultracite's bundled Anti-Slop |
166
+ | `/oxlint/react` | Ultracite React rules |
167
+ | `/oxlint/playwright` | Native Ultracite Playwright compatibility overrides |
168
+ | `/oxfmt` | Ultracite formatting, 100-column width |
169
+ | `/jscpd` | Duplicate-detection defaults, 3% total limit |
170
+ | `/dependency-cruiser` | Runtime-cycle policy and runtime resolution defaults |
171
+ | `/dependency-cruiser/runtime` | Runtime cycles and invalid runtime imports |
172
+ | `/dependency-cruiser/create-runtime-config` | Runtime policy bound to an explicit analysis directory |
173
+ | `/baseline` | Validated reports and non-increasing diagnostic budgets |
174
+ | `/package.json` | Version and export metadata |
94
175
 
95
176
  The Playwright export is the limited native Ultracite preset, not the complete `eslint-plugin-playwright` rule set. Solid, TanStack, Jest, Vitest and Storybook are not forced on unrelated consumers.
96
177
 
@@ -98,8 +179,49 @@ Dependency Cruiser is an **optional peer**. Install `dependency-cruiser@18.9.0`
98
179
 
99
180
  When enforcing application imports against external tooling, retain dependency edges into `node_modules` with `doNotFollow`; excluding those targets completely would remove the edges that the boundary rule needs.
100
181
 
182
+ The opt-in runtime preset adds errors for unresolved imports, installed npm dependencies omitted from the manifest or whose manifest classification is unknown, and runtime imports of `@servrox/code-quality`. Pass the runtime roots to `depcruise` from the consumer and add its own package boundaries and TypeScript aliases there. If the consumer ships runtime code without its devDependencies, it can also add a scoped `npm-dev` rule. Packaged Electron apps can resolve Electron as a devDependency while providing it at runtime, so apply that rule only where the manifest classification reflects deployment.
183
+
184
+ Dependency Cruiser 18.9.0 checks `package.json` import aliases such as `#foo` against the alias name instead of the mapped npm package. These aliases are excluded only from the declaration rule to avoid rejecting valid imports. The consumer must validate the mapped packages' manifest declarations. Unresolved aliases and aliases importing quality tooling still fail their respective rules.
185
+
101
186
  Runtime-cycle analysis excludes erased type-only imports **before** detecting cycles. Filtering a reported cycle afterwards can miss a runtime cycle when shorter type-only cycles overlap it. Supply the project's actual TypeScript configuration: the graph follows its emit semantics. For native TypeScript type-stripping runtimes, use `verbatimModuleSyntax: true` so unused value imports remain runtime edges.
102
187
 
188
+ ### Runtime analysis from another directory
189
+
190
+ The `/dependency-cruiser/runtime` preset uses the working directory when it is loaded. For a different analysis root, use the factory so Dependency Cruiser's `baseDir` and the linked quality-package boundary are generated together. For example, in the repository's `dependency-cruiser.config.mjs`:
191
+
192
+ ```js
193
+ import { fileURLToPath } from "node:url";
194
+
195
+ import createRuntimeConfig from "@servrox/code-quality/dependency-cruiser/create-runtime-config";
196
+
197
+ export default createRuntimeConfig({
198
+ baseDir: fileURLToPath(new URL("./apps/api/", import.meta.url)),
199
+ });
200
+ ```
201
+
202
+ From the repository root, run `pnpm exec depcruise --config dependency-cruiser.config.mjs --output-type err-long src`. Here `src` is relative to the generated `options.baseDir`, so it scans `apps/api/src`.
203
+
204
+ Add project-specific options and boundaries to this config as needed, retaining its generated `baseDir`. Overriding `options.baseDir` on an already-created preset would leave its linked-package matcher relative to the previous directory. Calling the factory without arguments uses the current working directory. Other workspace packages keep their normal symlink resolution.
205
+
206
+ ## Duplicate checks
207
+
208
+ Install the optional `jscpd@5.4.3` peer to use the `code-quality-duplicates` CLI. Start with the strict check. It prints jscpd's clone locations and summary table and fails for any detected duplication.
209
+
210
+ ```sh
211
+ pnpm exec code-quality-duplicates check -- src
212
+ ```
213
+
214
+ The scanner runs directly with jscpd. The optional `dry-refactoring` skill is independent of the package and CI.
215
+
216
+ For an explicitly approved migration, create and use a native baseline:
217
+
218
+ ```sh
219
+ pnpm exec code-quality-duplicates update-baseline --baseline tools/duplicates.json -- src
220
+ pnpm exec code-quality-duplicates check --baseline tools/duplicates.json -- src
221
+ ```
222
+
223
+ A baseline-backed check defaults to 3% duplicated lines and fails on any new clone. Reuse the same roots and exclusions in each mode. Use `--ignore <glob>` for extra exclusions and `--threshold` to set an explicit limit. The destination directory must exist. For a symlinked baseline, pass the target file when updating it.
224
+
103
225
  ## Limits and counting
104
226
 
105
227
  | Metric | Default |
@@ -123,6 +245,8 @@ These limits are policy choices. Each project must still review cohesion and int
123
245
 
124
246
  ## Baseline helpers
125
247
 
248
+ Use these helpers only for an explicitly approved migration exception.
249
+
126
250
  `normalizeLint` validates Oxlint JSON; `normalizeKnip` validates Knip 6 JSON. `createBaseline` groups findings by file, rule and normalized message. `findRegressions` compares the current values with committed allowances. Uncountable module syntax is reported with an allowance of zero alongside other regressions. Baseline creation rejects that syntax.
127
251
 
128
252
  Knip member and catalog identities retain their declared owner, for example `First["Unused"]`; an allowance for one enum, namespace or catalog cannot cover a same-named member in another. Export/type identities use the declaration's name: their reported namespace is a consumer-local import alias, so changing that alias does not change the budget.
@@ -151,7 +275,7 @@ pnpm verify
151
275
  1. Core/type-aware lint, formatting and additional policy checks.
152
276
  2. TypeScript and exported-file checks.
153
277
  3. Real Oxlint boundary fixtures, baseline tests and runtime-cycle regression tests.
154
- 4. `pnpm pack`, installation outside the checkout, all runtime exports, actual ESLint/SonarJS/Anti-Slop plugin execution and strict consumer types.
278
+ 4. `pnpm pack`, installation outside the checkout, all runtime exports, actual ESLint/SonarJS/Anti-Slop plugin execution, Git-scoped lint and format checks, and strict consumer types.
155
279
 
156
280
  Implementation files are explicit TypeScript roots; sibling declaration files are excluded from glob discovery to prevent them from hiding JavaScript sources. Imported declarations remain type-checked, including the strict packed consumer.
157
281
 
package/check/cli.mjs ADDED
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ import path from "node:path";
3
+ import { parseArgs } from "node:util";
4
+
5
+ import { z } from "zod";
6
+
7
+ import { regularFiles, repositoryRoot, selectFiles } from "./git-files.mjs";
8
+ import { runTool } from "./run-tools.mjs";
9
+
10
+ const usage =
11
+ "Usage: code-quality-check [--scope all|staged|unstaged|changed] [--check lint|format|both] [--base <git-ref>] [--oxlint-config <path>] [--oxfmt-config <path>] [-- <git-pathspec>...]";
12
+
13
+ const scopes = z.enum(["all", "staged", "unstaged", "changed"]);
14
+ const checks = z.enum(["lint", "format", "both"]);
15
+
16
+ /** @param {string | undefined} config - Optional config path supplied by the caller. */
17
+ const configPath = (config) => (config === undefined ? undefined : path.resolve(config));
18
+
19
+ const main = () => {
20
+ const { values, positionals } = parseArgs({
21
+ allowPositionals: true,
22
+ options: {
23
+ base: { type: "string" },
24
+ check: { default: "both", type: "string" },
25
+ help: { short: "h", type: "boolean" },
26
+ "oxfmt-config": { type: "string" },
27
+ "oxlint-config": { type: "string" },
28
+ scope: { default: "changed", type: "string" },
29
+ },
30
+ });
31
+
32
+ if (values.help === true) {
33
+ console.log(usage);
34
+
35
+ return 0;
36
+ }
37
+
38
+ const scope = scopes.parse(values.scope);
39
+ const check = checks.parse(values.check);
40
+
41
+ if (values.base !== undefined && scope !== "changed") {
42
+ throw new Error("--base applies to --scope changed only.");
43
+ }
44
+
45
+ const root = repositoryRoot(process.cwd());
46
+
47
+ const files = regularFiles(
48
+ root,
49
+ selectFiles({ base: values.base, pathspecs: positionals, root, scope })
50
+ );
51
+
52
+ const lint =
53
+ check === "format" ? 0 : runTool(root, "oxlint", configPath(values["oxlint-config"]), files);
54
+
55
+ const format =
56
+ check === "lint" ? 0 : runTool(root, "oxfmt", configPath(values["oxfmt-config"]), files);
57
+
58
+ return Math.max(lint, format);
59
+ };
60
+
61
+ try {
62
+ process.exitCode = main();
63
+ } catch (error) {
64
+ console.error(error instanceof Error ? error.message : error);
65
+ process.exitCode = 1;
66
+ }
@@ -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,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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@servrox/code-quality",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Reusable Ultracite/Oxc presets and quality policy for servrox projects.",
5
5
  "homepage": "https://github.com/servrox/code-quality#readme",
6
6
  "bugs": {
@@ -11,12 +11,17 @@
11
11
  "type": "git",
12
12
  "url": "git+https://github.com/servrox/code-quality.git"
13
13
  },
14
+ "bin": {
15
+ "code-quality-check": "./check/cli.mjs",
16
+ "code-quality-duplicates": "./jscpd/cli.mjs"
17
+ },
14
18
  "files": [
15
19
  "oxlint",
16
20
  "oxfmt",
17
21
  "jscpd",
18
22
  "dependency-cruiser",
19
- "src"
23
+ "src",
24
+ "check"
20
25
  ],
21
26
  "type": "module",
22
27
  "exports": {
@@ -53,6 +58,14 @@
53
58
  "types": "./dependency-cruiser/core.d.cts",
54
59
  "default": "./dependency-cruiser/core.cjs"
55
60
  },
61
+ "./dependency-cruiser/runtime": {
62
+ "types": "./dependency-cruiser/core.d.cts",
63
+ "default": "./dependency-cruiser/runtime.cjs"
64
+ },
65
+ "./dependency-cruiser/create-runtime-config": {
66
+ "types": "./dependency-cruiser/create-runtime-config.d.cts",
67
+ "default": "./dependency-cruiser/create-runtime-config.cjs"
68
+ },
56
69
  "./baseline": {
57
70
  "types": "./src/baseline.d.mts",
58
71
  "default": "./src/baseline.mjs"
@@ -65,7 +78,7 @@
65
78
  },
66
79
  "scripts": {
67
80
  "lint": "ultracite check",
68
- "lint:policy": "oxlint --config oxlint.policy.config.mjs oxlint oxfmt src dependency-cruiser scripts",
81
+ "lint:policy": "oxlint --config oxlint.policy.config.mjs oxlint oxfmt src dependency-cruiser jscpd scripts check",
69
82
  "fix": "ultracite fix",
70
83
  "check": "pnpm lint && pnpm lint:policy && tsc --noEmit && node scripts/check.mjs",
71
84
  "test": "node --test tests/*.test.mjs",
@@ -82,6 +95,7 @@
82
95
  "devDependencies": {
83
96
  "@types/node": "26.6.6",
84
97
  "dependency-cruiser": "18.9.0",
98
+ "jscpd": "5.4.3",
85
99
  "oxfmt": "0.78.0",
86
100
  "oxlint": "1.93.0",
87
101
  "oxlint-tsgolint": "7.0.2007",
@@ -90,6 +104,7 @@
90
104
  },
91
105
  "peerDependencies": {
92
106
  "dependency-cruiser": "18.9.0",
107
+ "jscpd": "5.4.3",
93
108
  "oxfmt": "0.78.0",
94
109
  "oxlint": "1.93.0",
95
110
  "ultracite": "8.2.1"
@@ -97,6 +112,9 @@
97
112
  "peerDependenciesMeta": {
98
113
  "dependency-cruiser": {
99
114
  "optional": true
115
+ },
116
+ "jscpd": {
117
+ "optional": true
100
118
  }
101
119
  },
102
120
  "engines": {