Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ name: Release

on:
push:
tags: ["v*"]
# Full versions only: moving the major tag (v1) must not start a release.
tags: ["v[0-9]+.[0-9]+.[0-9]+"]

permissions:
contents: read
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ benchmark/.data
benchmark/.cache
playground/dist
*.sarif
study/.cache
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,17 @@ A rewrite. The 2021 idea (normalize syntax trees, then compare) stays; everythin
- Functions, methods and classes as units, including nested ones.
- Type-1, Type-2 and Type-3 classification, with clone classes.
- `jscd` CLI with text, JSON and SARIF reports, `--ignore` and `--fail`.
- `--changed <ref>` (and the Action's `changed-since`): only report clones touching lines changed since a git ref, for pull requests.
- Node API (`detectClonesInPaths`) and a browser-safe core (`javascript-clone-detection/core`).
- GitHub Action for code scanning.
- Browser playground.
- Benchmark against jscpd, with real-code precision and an embeddings experiment.
- Empirical study: a replication of the 2021 thesis and 12 open-source React apps.

### Changed

- Consistent renaming, with a separate namespace for property names (v0.6 renamed every name to one placeholder).
- Scoring by bit-parallel LCS over normalized tokens, behind a candidate index (v0.6 ran Levenshtein on regenerated code for every pair).
- Scoring by bit-parallel LCS over normalized tokens, behind a candidate index of 8-token shingles and a length window (v0.6 ran Levenshtein on regenerated code for every pair).
- Deterministic output; nothing is written to the scanned directory.

### Removed
Expand Down
24 changes: 24 additions & 0 deletions CITATION.cff
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
cff-version: 1.2.0
message: If you use this software, please cite it, and the thesis it started from.
title: JavaScript Clone Detection
type: software
authors:
- family-names: Leal de Faria
given-names: Luís Felipe
repository-code: https://github.com/felipelealdefaria/javascript-clone-detection
url: https://felipelealdefaria.github.io/javascript-clone-detection/
license: MIT
version: 1.0.0
keywords: [clone detection, code duplication, JavaScript, TypeScript, React, static analysis]
references:
- type: thesis
thesis-type: Bachelor's thesis (Trabalho de Conclusão de Curso)
title: Estudo empírico sobre duplicação de código em aplicações JavaScript
authors:
- family-names: Leal de Faria
given-names: Luís Felipe
institution:
name: Universidade Tecnológica Federal do Paraná (UTFPR), Dois Vizinhos
year: 2021
languages: [pt]
url: http://repositorio.utfpr.edu.br/jspui/handle/1/30141
55 changes: 42 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Finds copy-pasted code in JavaScript, TypeScript and React projects, including c

![The playground comparing two snippets: a Type-3 clone, 96% similar, with the added statement marked](.github/assets/playground.png)

This started in 2021 as my undergraduate thesis research on code duplication in React apps ([background](#background-the-2021-thesis)). Version 1 is a rewrite, with a benchmark that checks it.
This started in 2021 as my bachelor's thesis on code duplication in JavaScript applications ([background](#background-the-2021-thesis)). Version 1 is a rewrite, with a benchmark that checks it and an [empirical study](#empirical-study) that uses it.

## Quick start

Expand Down Expand Up @@ -63,6 +63,18 @@ steps:
sarif_file: jscd.sarif
```

On pull requests, report only the duplication the PR introduces or touches:

```yaml
- uses: actions/checkout@v5
with:
fetch-depth: 0
- uses: felipelealdefaria/javascript-clone-detection@v1
with:
changed-since: origin/${{ github.base_ref }}
fail-on-clones: true
```

### From code

```ts
Expand Down Expand Up @@ -137,10 +149,10 @@ flowchart LR
}
```

4. **Type-3** pairs are found without comparing every pair. One representative per normalized shape is indexed by 3-token shingles. Each candidate pair must pass two cheap upper bounds, from length and from token counts, before the exact score: 2·LCS / (|a| + |b|) over normalized tokens, computed with a bit-parallel LCS that handles 32 cells of the table per step.
4. **Type-3** pairs are found without comparing every pair. One representative per normalized shape is indexed by 8-token shingles (plus 3-token shingles for short units). Units are sorted by length, so each one only visits partners whose length can still reach the threshold. A candidate must then pass an upper bound from token counts before the exact score: 2·LCS / (|a| + |b|) over normalized tokens, computed with a bit-parallel LCS that handles 32 cells of the table per step.
5. **Report.** A clone nested inside a reported clone is dropped, and pairs are grouped into clone classes. Text and SARIF reports list classes; JSON has every pair.

A 1,600-file TypeScript monorepo (5,000 units) takes about 1 s and 370 MB on an M5 Pro.
On an M5 Pro, grafana's frontend (7,200 files, 1.1 million lines, 39,000 units) takes 12 s, and all 12 apps in the [empirical study](#empirical-study) (6.1 million lines) take 42 s.

### Design decisions

Expand All @@ -152,6 +164,7 @@ A 1,600-file TypeScript monorepo (5,000 units) takes about 1 s and 370 MB on an
| Units are functions, methods and classes | Fixed-size token windows (jscpd) | Reports name what was copied. It misses copies smaller than a function. |
| Default 50-token minimum | 30 | On a real shadcn/ui project, half the reported units were one-line wrapper components. |
| Default threshold 0.8 | Lower | Precision falls from 88% at 0.7 to 44% at 0.6 ([sweep](benchmark/results/results.md#type-3-threshold-sweep)). |
| 8-token shingles and a length window | 3-token shingles only | Tuned against an exhaustive run on grafana: 99.9% of its Type-3 pairs at about 1/13 of the cost, with no change on the benchmark. |

## Results

Expand All @@ -168,6 +181,19 @@ On a [mutation-based benchmark](benchmark/README.md): 179 real functions and com

Full results: [benchmark/results/results.md](benchmark/results/results.md). Method and threats to validity: [benchmark/README.md](benchmark/README.md).

## Empirical study

The thesis asked how much real JavaScript code is cloned. [The study](study/README.md) answers it again with v1, in two parts.

**Replication of the thesis** on its three projects, at their 2021 commits. The minimum size explains most of the precision gap. Run like v0.6 (no size minimum), v1's sampled precision is 64%, against v0.6's 68.4%; with the 50-token default it is 96% (26 of 27).

**12 open-source React apps** (excalidraw, grafana, sentry, mastodon, Signal and others; 6.1 million lines):

- **3.8%** of production code (median) sits in a cloned function, method or class; tests are cloned about six times as often (24.9%).
- 70% of clone classes are in tests. Of the production ones, only 21.5% are components; most are services, thunks, handlers and utilities.
- **83% of clone classes are Type-3:** copies that were edited after pasting.
- 31 of 36 sampled pairs are real clones (86%).

## Limitations

- Type-4 clones (same behavior, different code) are out of scope for a structural detector.
Expand All @@ -177,18 +203,20 @@ Full results: [benchmark/results/results.md](benchmark/results/results.md). Meth

## Background: the 2021 thesis

This project began as my undergraduate thesis research at UTFPR, _Estudo empírico sobre duplicação de código em aplicações React.js_ ([PDF, Portuguese](https://drive.google.com/file/d/1MN8iBSfdD1yGMQ9aV-jwjdwJvRckiLfy/view?usp=sharing)). The study cites estimates that 7–23% of a typical system is cloned code. When it ran JSInspect, jscpd and Code Climate on a small React app, none of them flagged similar components as clones. The goal was a detector that understands React.
This project began as my bachelor's thesis in Software Engineering at UTFPR, _Estudo empírico sobre duplicação de código em aplicações JavaScript_ (2021, advised by Prof. Dr. Gustavo Jansen de Souza Santos; [UTFPR repository](http://repositorio.utfpr.edu.br/jspui/handle/1/30141), in Portuguese). It cites estimates that 7–23% of a typical system is cloned code. In its [proposal](https://drive.google.com/file/d/1MN8iBSfdD1yGMQ9aV-jwjdwJvRckiLfy/view?usp=sharing), JSInspect, jscpd and Code Climate, run on a small React app, flagged no similar components as clones.

The thesis built v0.6 and ran it on freeCodeCamp, trekhleb/javascript-algorithms and TheAlgorithms/JavaScript. Every candidate was validated by hand: 219 of 320 were real clones (68.4% precision), mostly Type-3. Its conclusion was that manual validation stays necessary, because what counts as a clone depends on the reader.

Version 0.6 (2021) proved the core idea: normalizing syntax trees turns arrow-vs-regular and renamed copies into identical text. But it couldn't parse JSX, so it couldn't read React components. It scored with Levenshtein distance on text, compared every pair, wrote its working files into the scanned directory, and had no way to measure accuracy. Version 1 keeps the idea and rebuilds everything else:
Version 0.6 (2021) proved the core idea: normalizing syntax trees turns arrow-vs-regular and renamed copies into identical text. But it couldn't parse JSX, so it couldn't read React components. It scored with Levenshtein distance on text, compared every pair, and wrote its working files into the scanned directory. Version 1 keeps the idea and rebuilds everything else:

| | v0.6 (2021) | v1 (2026) |
| ---------- | ---------------------------------------------- | --------------------------------------------------------- |
| Languages | JavaScript, no JSX | JavaScript, JSX, TypeScript, TSX |
| Units | Top-level functions | Functions, methods, classes, nested |
| Renaming | Every name → one placeholder | Consistent, with separate property names |
| Scoring | Levenshtein on regenerated code, all pairs | Hashing, candidate index and bit-parallel LCS |
| Output | A score; files written into the scanned folder | Type-1/2/3 classes; text, JSON or SARIF |
| Evaluation | One hand-written pair per type | 179-family benchmark, jscpd baseline, real-code precision |
| | v0.6 (2021) | v1 (2026) |
| ---------- | ---------------------------------------------- | -------------------------------------------------------- |
| Languages | JavaScript, no JSX | JavaScript, JSX, TypeScript, TSX |
| Units | Top-level functions | Functions, methods, classes, nested |
| Renaming | Every name → one placeholder | Consistent, with separate property names |
| Scoring | Levenshtein on regenerated code, all pairs | Hashing, candidate index and bit-parallel LCS |
| Output | A score; files written into the scanned folder | Type-1/2/3 classes; text, JSON or SARIF |
| Evaluation | 3 projects, every candidate validated by hand | Mutation benchmark vs. jscpd, replication, 12 React apps |

The 2021 examples live on as [test fixtures](test/fixtures/legacy) and as presets in the playground. The original code is at [v0.6.0](https://github.com/felipelealdefaria/javascript-clone-detection/tree/e46ca101352ca0f8dd1e5317982fa9da3a629cab).

Expand All @@ -202,6 +230,7 @@ npm run typecheck
npm run build # dist/
npm run playground # local playground at http://localhost:5173
npm run bench # benchmark (downloads the corpus once)
npm run study # empirical study (fetches 15 projects once)
```

Requires Node 22.18 or later.
Expand Down
7 changes: 7 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ inputs:
ignore:
description: Glob patterns to exclude, one per line.
default: ""
changed-since:
description: >-
Git ref, e.g. origin/main. Only clones with a copy on a line changed since the merge-base
with this ref are reported. Needs history: use actions/checkout with fetch-depth 0.
default: ""
sarif-file:
description: Where to write the SARIF report. Upload it with github/codeql-action/upload-sarif.
default: jscd.sarif
Expand All @@ -43,6 +48,7 @@ runs:
THRESHOLD: ${{ inputs.threshold }}
MIN_TOKENS: ${{ inputs.min-tokens }}
IGNORE: ${{ inputs.ignore }}
CHANGED_SINCE: ${{ inputs.changed-since }}
SARIF_FILE: ${{ inputs.sarif-file }}
FAIL: ${{ inputs.fail-on-clones }}
VERSION: ${{ inputs.version }}
Expand All @@ -53,6 +59,7 @@ runs:
while IFS= read -r pattern; do
[ -n "$pattern" ] && args+=(--ignore "$pattern")
done <<< "$IGNORE"
[ -n "$CHANGED_SINCE" ] && args+=(--changed "$CHANGED_SINCE")
jscd=(npx --yes "javascript-clone-detection@$VERSION")

NO_COLOR=1 "${jscd[@]}" "${paths[@]}" "${args[@]}" > jscd-report.txt
Expand Down
1 change: 1 addition & 0 deletions benchmark/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ Both tools' Type-3 scores are also swept from 0.6 to 0.9, because they measure d

- **Type-1 and Type-2 recall are expected to be 100% for jscd.** The mutations are exactly what its normalizer erases. These rows show that the normalizer is correct, not that the approach is clever. The informative rows are Type-3, Type-4, the threshold sweep, and precision on real code.
- **The benchmark was used during development.** It exposed a real bug: renaming a destructured prop (`{ title }` → `{ title: heading }`) made React components look different. Fixing it (property names got their own renaming namespace) raised React Type-2 recall from 21% to 100%. The fix is a general correctness change, but the numbers are post-fix.
- **The candidate search was tuned outside the benchmark.** The benchmark is too small to stress it. Shingle size and posting cap were tuned against an exhaustive run on grafana (39,000 units), keeping 99.9% of its Type-3 pairs. Benchmark results did not change.
- **Mutants are synthetic.** Real copy-paste edits are messier. Real-code precision partly covers this gap; real-code recall is not measured.
- **Type-4 is small and hand-written:** 16 pairs, written by the same author as the tool.
- **Precision on real code covers jscd only,** with 29 labeled pairs. The table shows 95% Wilson lower bounds for that reason.
Expand Down
64 changes: 64 additions & 0 deletions benchmark/metrics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import type { Dataset } from './build.js'
import { pairKey, type ToolRun } from './tools.js'

export interface Rate {
hits: number
total: number
}

export interface Metrics {
tool: string
durationMs: number
recall: { t1: Rate; t2: Rate; t3: Rate; t4: Rate }
recallByDomain: Record<string, { t1: Rate; t2: Rate; t3: Rate }>
t3ByEdits: Record<string, Rate>
precision: { truePositives: number; falsePositives: number }
}

export const rate = (r: Rate) => (r.total === 0 ? 0 : r.hits / r.total)
export const pct = (r: Rate) => `${(rate(r) * 100).toFixed(1)}%`
const add = (r: Rate, hit: boolean) => {
r.total++
if (hit) r.hits++
}
const empty = (): Rate => ({ hits: 0, total: 0 })

export function evaluate(dataset: Dataset, run: ToolRun): Metrics {
const groupOf = new Map<string, string>()
for (const f of dataset.families)
for (const file of Object.values(f.files)) groupOf.set(file, f.id)
for (const p of dataset.type4) {
groupOf.set(p.a, p.id)
groupOf.set(p.b, p.id)
}

const m: Metrics = {
tool: run.tool,
durationMs: Math.round(run.durationMs),
recall: { t1: empty(), t2: empty(), t3: empty(), t4: empty() },
recallByDomain: {},
t3ByEdits: {},
precision: { truePositives: 0, falsePositives: 0 },
}
for (const f of dataset.families) {
m.recallByDomain[f.domain] ??= { t1: empty(), t2: empty(), t3: empty() }
const domain = m.recallByDomain[f.domain] as { t1: Rate; t2: Rate; t3: Rate }
m.t3ByEdits[f.t3Edits] ??= empty()
for (const type of ['t1', 't2', 't3'] as const) {
const hit = run.pairs.has(pairKey(f.files.original, f.files[type]))
add(m.recall[type], hit)
add(domain[type], hit)
if (type === 't3') add(m.t3ByEdits[f.t3Edits] as Rate, hit)
}
}
for (const p of dataset.type4) add(m.recall.t4, run.pairs.has(pairKey(p.a, p.b)))

// Any detected pair across groups is a false positive: originals were chosen not to be clones.
for (const key of run.pairs) {
const [a, b] = key.split('|') as [string, string]
if (groupOf.get(a) !== undefined && groupOf.get(a) === groupOf.get(b))
m.precision.truePositives++
else m.precision.falsePositives++
}
return m
}
Loading
Loading