@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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,288 @@
1
- # Temporary Holding Version
1
+ # @servrox/code-quality
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ![Abstract code with diagnostic markers and a dependency graph](./docs/assets/code-quality-banner.svg)
4
+
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
+
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
+
9
+ ## Quick start
10
+
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
+
13
+ ```sh
14
+ pnpm add -D -E @servrox/code-quality@latest \
15
+ ultracite@8.2.1 oxlint@1.93.0 oxfmt@0.78.0 oxlint-tsgolint@7.0.2007
16
+ ```
17
+
18
+ <details>
19
+ <summary>Install from a reviewed Git commit</summary>
20
+
21
+ Replace `COMMIT_SHA` with a full 40-character SHA retained in the public repository.
22
+
23
+ ```sh
24
+ pnpm add -D -E '@servrox/code-quality@git+https://github.com/servrox/code-quality.git#COMMIT_SHA' \
25
+ ultracite@8.2.1 oxlint@1.93.0 oxfmt@0.78.0 oxlint-tsgolint@7.0.2007
26
+ ```
27
+
28
+ Review lockfile updates if GitHub regenerates archive compression and the archive integrity changes.
29
+
30
+ </details>
31
+
32
+ ### Configure a project
33
+
34
+ `oxlint.config.ts`:
35
+
36
+ ```ts
37
+ import antiSlop from "@servrox/code-quality/oxlint/anti-slop";
38
+ import core from "@servrox/code-quality/oxlint/core";
39
+ import modularity from "@servrox/code-quality/oxlint/modularity";
40
+ import strict from "@servrox/code-quality/oxlint/strict";
41
+ import { defineConfig } from "oxlint";
42
+
43
+ export default defineConfig({
44
+ extends: [core, strict, modularity, antiSlop],
45
+ env: { node: true, browser: false },
46
+ options: {
47
+ typeAware: true,
48
+ denyWarnings: true,
49
+ reportUnusedDisableDirectives: "error",
50
+ },
51
+ ignorePatterns: [...(core.ignorePatterns ?? []), "**/_generated/**"],
52
+ });
53
+ ```
54
+
55
+ `oxfmt.config.ts`:
56
+
57
+ ```ts
58
+ import shared from "@servrox/code-quality/oxfmt";
59
+ import { defineConfig } from "oxfmt";
60
+
61
+ export default defineConfig({
62
+ ...shared,
63
+ ignorePatterns: [...(shared.ignorePatterns ?? []), "pnpm-lock.yaml"],
64
+ });
65
+ ```
66
+
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
+
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
+
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
+
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
+
128
+ ### Set up with a coding agent
129
+
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.
131
+
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.
157
+
158
+ ## Public exports
159
+
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 |
175
+
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.
177
+
178
+ Dependency Cruiser is an **optional peer**. Install `dependency-cruiser@18.9.0` only when using that export. Its analyzer requires a supported TypeScript compiler API; projects using TypeScript 7.0 can supply TypeScript 6.0.3 to that tool through pnpm `packageExtensions`, as this repository does for tests.
179
+
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.
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
+
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.
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
+
225
+ ## Limits and counting
226
+
227
+ | Metric | Default |
228
+ | ------------------------------------------------------- | ------: |
229
+ | Physical file lines, including comments and blank lines | 300 |
230
+ | Test/spec file lines | 500 |
231
+ | Top-level function declarations/bindings | 8 |
232
+ | Explicit ESM exports | 5 |
233
+ | Properties in an inline CommonJS export object | 5 |
234
+ | Function lines, excluding comments and blank lines | 50 |
235
+ | Cyclomatic / cognitive complexity | 8 / 10 |
236
+ | Block nesting / nested callbacks | 3 / 3 |
237
+ | Parameters / statements per function | 4 / 20 |
238
+ | Classes per file | 1 |
239
+
240
+ Function counting recognizes declarations with bodies, direct arrow/function bindings, exported declarations, default functions and inline CommonJS export functions, including TypeScript `export =` functions. One direct `as`, `satisfies` or non-null wrapper is supported for bindings and ESM default expressions. Nested callbacks, methods, arbitrary aliases and factory-returned implementations are outside this syntax policy.
241
+
242
+ Value, type, default and namespace ESM exports count. Grouped declarations, specifier lists, destructuring and wildcard exports are marked outside explicit consumer-owned entrypoints. CommonJS supports inline export objects and functions in both `module.exports` and TypeScript `export =` forms; spreads, incremental assignments, indirect values and common mutation helpers are marked. Dot and literal bracket spellings of the configured mutation helpers are checked. Arbitrary runtime mutation is not inferred.
243
+
244
+ These limits are policy choices. Each project must still review cohesion and intentional public API boundaries.
245
+
246
+ ## Baseline helpers
247
+
248
+ Use these helpers only for an explicitly approved migration exception.
249
+
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.
251
+
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.
253
+
254
+ - New groups or occurrences fail.
255
+ - Increased numeric metrics fail even when the diagnostic count stays constant.
256
+ - Source-line movement in supported Sonar messages is normalized.
257
+ - Within an identical group, metrics are compared in descending order.
258
+ - Improvements become permanent when the consumer prunes and commits its baseline.
259
+ - Uncountable module syntax cannot be grandfathered; fix it or scope a deliberate entrypoint exception in the project.
260
+ - Missing, malformed or unclassified reports fail closed.
261
+
262
+ Baseline storage, command orchestration and migration approval remain with each consumer. Native jscpd/Dependency Cruiser baselines likewise stay project-local.
263
+
264
+ ## Develop and verify
265
+
266
+ Requires Node **>=24.15.0** and pnpm **12.16.1**.
267
+
268
+ ```sh
269
+ pnpm install --frozen-lockfile
270
+ pnpm verify
271
+ ```
272
+
273
+ `verify` runs:
274
+
275
+ 1. Core/type-aware lint, formatting and additional policy checks.
276
+ 2. TypeScript and exported-file checks.
277
+ 3. Real Oxlint boundary fixtures, baseline tests and runtime-cycle regression tests.
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.
279
+
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.
281
+
282
+ The install smoke test clears `NODE_PATH` and checks that source tests, development scripts and repository configs are absent from the installed package. CI uses pinned actions and runs on Node 24.15.0 and Node 26.
283
+
284
+ ## Contributing and security
285
+
286
+ See the [contribution guide](https://github.com/servrox/code-quality/blob/main/CONTRIBUTING.md) for changes and release steps, the [changelog](https://github.com/servrox/code-quality/blob/main/CHANGELOG.md) for consumer-visible changes, and the [security policy](https://github.com/servrox/code-quality/blob/main/SECURITY.md) for private reporting.
287
+
288
+ This project is licensed under [Apache-2.0](https://github.com/servrox/code-quality/blob/main/LICENSE).
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
+ }