9 Commits
v1.0.3 ... main

13 changed files with 9233 additions and 242 deletions

View File

@@ -1,141 +0,0 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
before_script:
- npm install -g @shipzone/npmci
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
only:
- tags
tags:
- lossless
- docker
- notpriv
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
allow_failure: true
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
allow_failure: true
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

33
changelog.md Normal file
View File

@@ -0,0 +1,33 @@
# Changelog
## 2025-12-14 - 1.1.0 - feat(smartdiff)
Migrate package to ESM, replace fast-diff with `diff` and add rich diff APIs + formatters
- Set package to ESM (added "type": "module" to package.json)
- Replaced legacy fast-diff usage with the maintained `diff` package and exported it via plugins
- Added backward-compatible compact API: createDiff(original, revision) and applyPatch(original, diff)
- Introduced character/word/line/unified diff helpers (getCharDiff, getWordDiff, getLineDiff, createUnifiedDiff)
- Added console and HTML formatters (ANSI color output and HTML span/div output) and getDefaultDiffCss helper
- Expanded and modernized test suite (many new tests) and switched test tooling to @git.zone/tstest
- Updated devDependencies and author metadata, and updated npmextra.json release metadata and registries
- Removed legacy CI configuration (.gitlab-ci.yml) and cleaned up TypeScript config
## 2024-05-29 - 1.0.3 - maintenance
Consolidated maintenance, metadata and config updates.
- Update package description.
- Update TypeScript configuration (tsconfig).
- Update npmextra.json githost settings (applied across multiple commits).
- Switch to new organization scheme.
- Multiple duplicate/housekeeping commits across 20212024 were consolidated into this release.
## 2021-12-17 - 1.0.2 - fix(core)
Core fixes and small updates.
- fix(core): update — applied core fixes (details not present in commit message).
- Release/tag commits around 2021-12-162021-12-17 consolidated here.
## 2021-12-16 - 1.0.1 - fix(core)
Initial patch with core updates.
- fix(core): update — core update/fix included.

View File

@@ -1,18 +1,37 @@
{
"gitzone": {
"@git.zone/cli": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartdiff",
"shortDescription": "a diffing lib for text",
"npmPackagename": "@pushrocks/smartdiff",
"npmPackagename": "@push.rocks/smartdiff",
"license": "MIT",
"projectDomain": "push.rocks"
"projectDomain": "push.rocks",
"description": "A library for performing text diffs.",
"keywords": [
"diff",
"text",
"patch",
"typescript",
"npm package",
"text comparison",
"text diff"
]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
"@git.zone/tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
},
"@ship.zone/szci": {
"npmGlobalTools": []
}
}

View File

@@ -1,27 +1,24 @@
{
"name": "@pushrocks/smartdiff",
"version": "1.0.3",
"name": "@push.rocks/smartdiff",
"version": "1.1.0",
"private": false,
"description": "a diffing lib for text",
"description": "A library for performing text diffs.",
"type": "module",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"author": "Lossless GmbH",
"author": "Task Venture Capital GmbH",
"license": "MIT",
"scripts": {
"test": "(tstest test/ --web)",
"test": "(tstest test/ --verbose)",
"build": "(tsbuild --web)"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.25",
"@gitzone/tsbundle": "^1.0.78",
"@gitzone/tstest": "^1.0.44",
"@pushrocks/tapbundle": "^3.2.9",
"@types/node": "^14.11.2",
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.15.0"
"@git.zone/tsbuild": "^4.0.2",
"@git.zone/tstest": "^3.1.3",
"@types/node": "^22.15.21"
},
"dependencies": {
"fast-diff": "^1.2.0"
"diff": "^8.0.2"
},
"browserslist": [
"last 1 chrome versions"
@@ -37,5 +34,24 @@
"cli.js",
"npmextra.json",
"readme.md"
]
],
"keywords": [
"diff",
"text",
"patch",
"typescript",
"npm package",
"text comparison",
"text diff",
"visualization",
"cli",
"html",
"line diff",
"word diff"
],
"homepage": "https://code.foss.global/push.rocks/smartdiff",
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smartdiff.git"
}
}

8014
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@@ -0,0 +1 @@

463
readme.md
View File

@@ -1,39 +1,446 @@
# @pushrocks/smartdiff
a diffing lib for text
# @push.rocks/smartdiff
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartdiff)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartdiff)
* [github.com (source mirror)](https://github.com/pushrocks/smartdiff)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartdiff/)
A powerful, cross-platform text diffing library for TypeScript/JavaScript with built-in visualization for CLI and browser. 🔍
## Status for master
## Issue Reporting and Security
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/smartdiff/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/smartdiff/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/smartdiff)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/smartdiff)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/smartdiff)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/smartdiff)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/smartdiff)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Install
```sh
npm install @push.rocks/smartdiff
# or
pnpm add @push.rocks/smartdiff
```
## Features ✨
- 🔤 **Character-level diffs** — See exactly which characters changed
- 📝 **Word-level diffs** — Perfect for document comparisons
- 📄 **Line-level diffs** — Ideal for code and file comparisons
- 🖥️ **CLI output** — ANSI-colored terminal output
- 🌐 **HTML output** — Styled spans for browser rendering
- 📦 **Compact storage format** — Efficient diff serialization for storage/sync
- 🔧 **Git-style unified diffs** — Standard patch format
- 💅 **Built-in CSS** — Ready-to-use styles for HTML output
## Usage
Use TypeScript for best in class intellisense
### Quick Start
## Contribution
```typescript
import {
createDiff,
applyPatch,
formatLineDiffForConsole,
formatWordDiffAsHtml,
} from '@push.rocks/smartdiff';
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
// Create and apply compact diffs
const patch = createDiff('hello world', 'hello beautiful world');
const result = applyPatch('hello world', patch);
// result: 'hello beautiful world'
For further information read the linked docs at the top of this readme.
// Visualize changes in terminal
console.log(formatLineDiffForConsole(oldCode, newCode));
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
// Generate HTML for browser display
const html = formatWordDiffAsHtml(oldText, newText);
```
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
---
## 📦 Compact Diff Storage
For storing diffs efficiently (version control, sync, undo/redo):
### `createDiff(original, revision)`
Creates a compact JSON-encoded diff optimized for storage.
```typescript
import { createDiff } from '@push.rocks/smartdiff';
const diff = createDiff('Hello World', 'Hello smart World');
console.log(diff);
// Output: [[0,6],[1,"smart "],[0,5]]
```
**Format:**
- `[0, n]` — Keep `n` characters from original
- `[1, "text"]` — Insert `"text"`
- `[-1, n]` — Delete `n` characters
### `applyPatch(original, diffString)`
Reconstructs the revised text from original + diff.
```typescript
import { createDiff, applyPatch } from '@push.rocks/smartdiff';
const original = 'hi there';
const revised = 'hi Polly, there is a Sandwich.';
const patch = createDiff(original, revised);
const reconstructed = applyPatch(original, patch);
// reconstructed === revised ✓
```
---
## 🔤 Character-Level Diff
For precise character-by-character comparison:
### `getCharDiff(original, revision)`
Returns an array of diff segments.
```typescript
import { getCharDiff } from '@push.rocks/smartdiff';
const segments = getCharDiff('hello', 'hallo');
// [
// { type: 'equal', value: 'h' },
// { type: 'delete', value: 'e' },
// { type: 'insert', value: 'a' },
// { type: 'equal', value: 'llo' }
// ]
```
### `formatCharDiffForConsole(original, revision)`
Returns ANSI-colored string for terminal output.
```typescript
import { formatCharDiffForConsole } from '@push.rocks/smartdiff';
console.log(formatCharDiffForConsole('hello world', 'hello beautiful world'));
// Displays: hello [green background]beautiful [/green]world
```
### `formatCharDiffAsHtml(original, revision)`
Returns HTML with styled spans.
```typescript
import { formatCharDiffAsHtml } from '@push.rocks/smartdiff';
const html = formatCharDiffAsHtml('hello', 'hallo');
// <span class="smartdiff-equal">h</span>
// <span class="smartdiff-delete">e</span>
// <span class="smartdiff-insert">a</span>
// <span class="smartdiff-equal">llo</span>
```
---
## 📝 Word-Level Diff
For document and prose comparison:
### `getWordDiff(original, revision)`
```typescript
import { getWordDiff } from '@push.rocks/smartdiff';
const segments = getWordDiff('The quick brown fox', 'The slow brown dog');
// [
// { type: 'equal', value: 'The ' },
// { type: 'delete', value: 'quick' },
// { type: 'insert', value: 'slow' },
// { type: 'equal', value: ' brown ' },
// { type: 'delete', value: 'fox' },
// { type: 'insert', value: 'dog' }
// ]
```
### `formatWordDiffForConsole(original, revision)`
```typescript
import { formatWordDiffForConsole } from '@push.rocks/smartdiff';
console.log(formatWordDiffForConsole('Hello World', 'Hello Beautiful World'));
// Displays: Hello [green]Beautiful [/green]World
```
### `formatWordDiffAsHtml(original, revision)`
```typescript
import { formatWordDiffAsHtml } from '@push.rocks/smartdiff';
const html = formatWordDiffAsHtml('one two three', 'one TWO three');
// <span class="smartdiff-equal">one </span>
// <span class="smartdiff-delete">two</span>
// <span class="smartdiff-insert">TWO</span>
// <span class="smartdiff-equal"> three</span>
```
---
## 📄 Line-Level Diff
For code and file comparison:
### `getLineDiff(original, revision)`
```typescript
import { getLineDiff } from '@push.rocks/smartdiff';
const lineDiff = getLineDiff('line1\nline2\nline3', 'line1\nmodified\nline3');
// [
// { lineNumber: 1, type: 'equal', value: 'line1' },
// { lineNumber: 2, type: 'delete', value: 'line2' },
// { lineNumber: -1, type: 'insert', value: 'modified' },
// { lineNumber: 3, type: 'equal', value: 'line3' }
// ]
```
### `formatLineDiffForConsole(original, revision)`
Produces unified diff-style output with colors:
```typescript
import { formatLineDiffForConsole } from '@push.rocks/smartdiff';
const oldCode = `function hello() {
console.log("hi");
}`;
const newCode = `function hello() {
console.log("hello world");
}`;
console.log(formatLineDiffForConsole(oldCode, newCode));
```
Output:
```diff
function hello() {
- console.log("hi");
+ console.log("hello world");
}
```
### `formatLineDiffAsHtml(original, revision)`
```typescript
import { formatLineDiffAsHtml } from '@push.rocks/smartdiff';
const html = formatLineDiffAsHtml('a\nb\nc', 'a\nB\nc');
// <div class="smartdiff-lines">
// <div class="smartdiff-line smartdiff-equal"><span class="smartdiff-prefix"> </span>a</div>
// <div class="smartdiff-line smartdiff-delete"><span class="smartdiff-prefix">-</span>b</div>
// <div class="smartdiff-line smartdiff-insert"><span class="smartdiff-prefix">+</span>B</div>
// <div class="smartdiff-line smartdiff-equal"><span class="smartdiff-prefix"> </span>c</div>
// </div>
```
---
## 🔧 Unified Diff (Git-style)
### `createUnifiedDiff(original, revision, options?)`
Creates a standard unified diff patch.
```typescript
import { createUnifiedDiff } from '@push.rocks/smartdiff';
const patch = createUnifiedDiff(oldContent, newContent, {
originalFileName: 'file.txt',
revisedFileName: 'file.txt',
context: 3, // lines of context
});
console.log(patch);
```
Output:
```diff
--- file.txt
+++ file.txt
@@ -1,5 +1,5 @@
line1
-line2
+modified
line3
```
### `formatUnifiedDiffForConsole(original, revision, options?)`
Same as above, but with ANSI colors for terminal display.
---
## 💅 CSS Styles for HTML Output
### `getDefaultDiffCss()`
Returns ready-to-use CSS for styling HTML diff output.
```typescript
import { getDefaultDiffCss } from '@push.rocks/smartdiff';
const css = getDefaultDiffCss();
// Inject into your page:
// <style>${css}</style>
```
**Included styles:**
- `.smartdiff-delete` — Red background, strikethrough
- `.smartdiff-insert` — Green background
- `.smartdiff-equal` — Unchanged text
- `.smartdiff-lines` — Container for line diffs
- `.smartdiff-line` — Individual line styling
- `.smartdiff-prefix` — The +/- prefix styling
---
## 🎯 Real-World Use Cases
### Collaborative Editing
Track document versions without storing full copies:
```typescript
import { createDiff, applyPatch } from '@push.rocks/smartdiff';
const versions = ['Initial draft'];
const patches: string[] = [];
function saveVersion(newText: string) {
const lastVersion = versions[versions.length - 1];
patches.push(createDiff(lastVersion, newText));
versions.push(newText);
}
function getVersion(index: number): string {
let text = versions[0];
for (let i = 0; i < index; i++) {
text = applyPatch(text, patches[i]);
}
return text;
}
```
### Network Synchronization
Send compact diffs instead of full content:
```typescript
import { createDiff, applyPatch } from '@push.rocks/smartdiff';
// Client
function sendUpdate(localText: string, serverText: string) {
const diff = createDiff(serverText, localText);
socket.emit('update', diff); // Much smaller than full text!
}
// Server
socket.on('update', (diff: string) => {
document = applyPatch(document, diff);
});
```
### Undo/Redo System
```typescript
import { createDiff, applyPatch } from '@push.rocks/smartdiff';
interface HistoryEntry {
forward: string;
backward: string;
}
const history: HistoryEntry[] = [];
let currentText = 'Start';
function edit(newText: string) {
history.push({
forward: createDiff(currentText, newText),
backward: createDiff(newText, currentText),
});
currentText = newText;
}
function undo() {
const entry = history.pop();
if (entry) {
currentText = applyPatch(currentText, entry.backward);
}
}
```
### Code Review UI
```typescript
import { formatLineDiffAsHtml, getDefaultDiffCss } from '@push.rocks/smartdiff';
function renderCodeReview(oldCode: string, newCode: string) {
return `
<style>${getDefaultDiffCss()}</style>
${formatLineDiffAsHtml(oldCode, newCode)}
`;
}
```
---
## 📖 TypeScript Types
```typescript
interface IDiffSegment {
type: 'equal' | 'insert' | 'delete';
value: string;
}
interface ILineDiff {
lineNumber: number;
type: 'equal' | 'insert' | 'delete';
value: string;
}
```
---
## API Reference
| Function | Description |
|----------|-------------|
| `createDiff(original, revision)` | Create compact diff for storage |
| `applyPatch(original, diffString)` | Reconstruct text from diff |
| `getCharDiff(original, revision)` | Character-level diff segments |
| `getWordDiff(original, revision)` | Word-level diff segments |
| `getLineDiff(original, revision)` | Line-level diff segments |
| `formatCharDiffForConsole(...)` | ANSI-colored char diff |
| `formatWordDiffForConsole(...)` | ANSI-colored word diff |
| `formatLineDiffForConsole(...)` | ANSI-colored line diff |
| `formatCharDiffAsHtml(...)` | HTML char diff |
| `formatWordDiffAsHtml(...)` | HTML word diff |
| `formatLineDiffAsHtml(...)` | HTML line diff |
| `createUnifiedDiff(...)` | Git-style unified diff |
| `formatUnifiedDiffForConsole(...)` | Colored unified diff |
| `getDefaultDiffCss()` | CSS styles for HTML output |
## License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@@ -1,14 +1,258 @@
import { expect, tap } from '@pushrocks/tapbundle';
import * as smartdiff from '../ts/index';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartdiff from '../ts/index.js';
tap.test('first test', async () => {
// =============================================================================
// Backward Compatibility Tests
// =============================================================================
tap.test('createDiff and applyPatch should work (backward compatible)', async () => {
const text1 = 'hi there';
const text2 = 'hi Polly, there is a Sandwich.';
const patch = smartdiff.createDiff(text1, text2);
console.log(patch);
console.log('Compact diff:', patch);
const result = smartdiff.applyPatch(text1, patch);
console.log(result);
expect(result).to.equal(text2);
console.log('Reconstructed:', result);
expect(result).toEqual(text2);
});
tap.start();
tap.test('createDiff should produce compact format', async () => {
const original = 'Hello World';
const revised = 'Hello smart World';
const diff = smartdiff.createDiff(original, revised);
const parsed = JSON.parse(diff);
// Should be array of tuples
expect(Array.isArray(parsed)).toBeTrue();
// Each tuple should have operation and value
for (const item of parsed) {
expect(Array.isArray(item)).toBeTrue();
expect(item.length).toEqual(2);
expect([-1, 0, 1]).toContain(item[0]);
}
});
// =============================================================================
// Character Diff Tests
// =============================================================================
tap.test('getCharDiff should return character-level diff segments', async () => {
const original = 'hello';
const revised = 'hallo';
const segments = smartdiff.getCharDiff(original, revised);
expect(Array.isArray(segments)).toBeTrue();
expect(segments.length).toBeGreaterThan(0);
// Each segment should have type and value
for (const segment of segments) {
expect(['equal', 'insert', 'delete']).toContain(segment.type);
expect(typeof segment.value).toEqual('string');
}
// Should detect the 'e' -> 'a' change
const deleteSegment = segments.find(s => s.type === 'delete');
const insertSegment = segments.find(s => s.type === 'insert');
expect(deleteSegment).toBeDefined();
expect(insertSegment).toBeDefined();
});
tap.test('formatCharDiffForConsole should produce ANSI colored output', async () => {
const original = 'hello world';
const revised = 'hello beautiful world';
const output = smartdiff.formatCharDiffForConsole(original, revised);
console.log('Char diff console output:', output);
// Should contain ANSI codes
expect(output).toInclude('\x1b[');
// Should contain the unchanged parts
expect(output).toInclude('hello');
expect(output).toInclude('world');
});
tap.test('formatCharDiffAsHtml should produce HTML spans', async () => {
const original = 'hello';
const revised = 'hallo';
const html = smartdiff.formatCharDiffAsHtml(original, revised);
console.log('Char diff HTML:', html);
expect(html).toInclude('<span class="smartdiff-');
expect(html).toInclude('smartdiff-delete');
expect(html).toInclude('smartdiff-insert');
});
// =============================================================================
// Word Diff Tests
// =============================================================================
tap.test('getWordDiff should return word-level diff segments', async () => {
const original = 'The quick brown fox';
const revised = 'The slow brown dog';
const segments = smartdiff.getWordDiff(original, revised);
console.log('Word diff segments:', segments);
expect(Array.isArray(segments)).toBeTrue();
// Should detect word changes
const hasDelete = segments.some(s => s.type === 'delete');
const hasInsert = segments.some(s => s.type === 'insert');
expect(hasDelete).toBeTrue();
expect(hasInsert).toBeTrue();
});
tap.test('formatWordDiffForConsole should produce readable output', async () => {
const original = 'Hello World';
const revised = 'Hello Beautiful World';
const output = smartdiff.formatWordDiffForConsole(original, revised);
console.log('Word diff console output:', output);
expect(output).toInclude('Hello');
expect(output).toInclude('World');
});
tap.test('formatWordDiffAsHtml should produce HTML spans', async () => {
const original = 'one two three';
const revised = 'one TWO three';
const html = smartdiff.formatWordDiffAsHtml(original, revised);
console.log('Word diff HTML:', html);
expect(html).toInclude('<span class="smartdiff-');
});
// =============================================================================
// Line Diff Tests
// =============================================================================
tap.test('getLineDiff should return line-level diff', async () => {
const original = 'line1\nline2\nline3';
const revised = 'line1\nmodified\nline3';
const lineDiff = smartdiff.getLineDiff(original, revised);
console.log('Line diff:', lineDiff);
expect(Array.isArray(lineDiff)).toBeTrue();
// Should have line numbers and types
for (const line of lineDiff) {
expect(typeof line.lineNumber).toEqual('number');
expect(['equal', 'insert', 'delete']).toContain(line.type);
expect(typeof line.value).toEqual('string');
}
});
tap.test('formatLineDiffForConsole should produce unified-style output', async () => {
const original = 'function hello() {\n console.log("hi");\n}';
const revised = 'function hello() {\n console.log("hello world");\n}';
const output = smartdiff.formatLineDiffForConsole(original, revised);
console.log('Line diff console output:\n' + output);
// Should have +/- prefixes
expect(output).toInclude('-');
expect(output).toInclude('+');
});
tap.test('formatLineDiffAsHtml should produce HTML divs', async () => {
const original = 'a\nb\nc';
const revised = 'a\nB\nc';
const html = smartdiff.formatLineDiffAsHtml(original, revised);
console.log('Line diff HTML:\n' + html);
expect(html).toInclude('<div class="smartdiff-lines">');
expect(html).toInclude('<div class="smartdiff-line');
expect(html).toInclude('smartdiff-prefix');
});
// =============================================================================
// Unified Diff Tests
// =============================================================================
tap.test('createUnifiedDiff should produce git-style unified diff', async () => {
const original = 'line1\nline2\nline3\nline4\nline5';
const revised = 'line1\nmodified\nline3\nline4\nline5';
const unifiedDiff = smartdiff.createUnifiedDiff(original, revised, {
originalFileName: 'file.txt',
revisedFileName: 'file.txt',
});
console.log('Unified diff:\n' + unifiedDiff);
expect(unifiedDiff).toInclude('---');
expect(unifiedDiff).toInclude('+++');
expect(unifiedDiff).toInclude('@@');
});
tap.test('formatUnifiedDiffForConsole should colorize unified diff', async () => {
const original = 'old content';
const revised = 'new content';
const output = smartdiff.formatUnifiedDiffForConsole(original, revised);
console.log('Unified diff console:\n' + output);
// Should contain ANSI codes
expect(output).toInclude('\x1b[');
});
// =============================================================================
// CSS Helper Test
// =============================================================================
tap.test('getDefaultDiffCss should return valid CSS', async () => {
const css = smartdiff.getDefaultDiffCss();
console.log('Default CSS:\n' + css);
expect(css).toInclude('.smartdiff-delete');
expect(css).toInclude('.smartdiff-insert');
expect(css).toInclude('.smartdiff-equal');
expect(css).toInclude('background-color');
});
// =============================================================================
// Edge Cases
// =============================================================================
tap.test('should handle empty strings', async () => {
const diff1 = smartdiff.createDiff('', 'new');
const diff2 = smartdiff.createDiff('old', '');
const diff3 = smartdiff.createDiff('', '');
expect(smartdiff.applyPatch('', diff1)).toEqual('new');
expect(smartdiff.applyPatch('old', diff2)).toEqual('');
expect(smartdiff.applyPatch('', diff3)).toEqual('');
});
tap.test('should handle identical strings', async () => {
const text = 'no changes here';
const diff = smartdiff.createDiff(text, text);
const result = smartdiff.applyPatch(text, diff);
expect(result).toEqual(text);
// Visualization should show all equal
const segments = smartdiff.getCharDiff(text, text);
expect(segments.every(s => s.type === 'equal')).toBeTrue();
});
tap.test('should escape HTML in output', async () => {
const original = '<div>test</div>';
const revised = '<span>test</span>';
const html = smartdiff.formatCharDiffAsHtml(original, revised);
console.log('HTML escaped output:', html);
// Should escape < and >
expect(html).toInclude('&lt;');
expect(html).toInclude('&gt;');
// Should not contain raw HTML tags from input
expect(html).not.toInclude('<div>');
expect(html).not.toInclude('<span>');
});
export default tap.start();

8
ts/00_commitinfo_data.ts Normal file
View File

@@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartdiff',
version: '1.1.0',
description: 'A library for performing text diffs.'
}

View File

@@ -1,42 +1,436 @@
import * as plugins from './smartdiff.plugins';
import * as plugins from './smartdiff.plugins.js';
import diff from 'fast-diff';
// =============================================================================
// Types
// =============================================================================
export const createDiff = (originalArg: string, revisionArg: string) => {
var result = diff(originalArg, revisionArg);
// According to latest jsperf tests, there's no need to cache array length
for (var i = 0; i < result.length; i++) {
var diffItem = result[i];
// If operation is DELETE or EQUAL, replace the actual text by its length
if (diffItem[0] < 1) {
// @ts-ignore
diffItem[1] = diffItem[1].length;
export interface IDiffSegment {
type: 'equal' | 'insert' | 'delete';
value: string;
}
export interface ILineDiff {
lineNumber: number;
type: 'equal' | 'insert' | 'delete';
value: string;
}
// =============================================================================
// ANSI Color Helpers (for console output)
// =============================================================================
const ANSI = {
red: '\x1b[31m',
green: '\x1b[32m',
gray: '\x1b[90m',
reset: '\x1b[0m',
bgRed: '\x1b[41m',
bgGreen: '\x1b[42m',
};
// =============================================================================
// Backward Compatible API (createDiff / applyPatch)
// =============================================================================
/**
* Creates a compact JSON-encoded diff between two strings.
* Format: [[0, length], [1, "inserted text"], [-1, length], ...]
* - [0, n] = keep n characters from original
* - [1, "text"] = insert "text"
* - [-1, n] = delete n characters from original
*/
export const createDiff = (originalArg: string, revisionArg: string): string => {
const changes = plugins.diff.diffChars(originalArg, revisionArg);
const result: Array<[number, string | number]> = [];
for (const change of changes) {
if (change.added) {
// INSERT: store the actual text
result.push([1, change.value]);
} else if (change.removed) {
// DELETE: store just the length
result.push([-1, change.value.length]);
} else {
// EQUAL: store just the length
result.push([0, change.value.length]);
}
}
return JSON.stringify(result);
};
export const applyPatch = (originalArg: string, deltaStringArg: string) => {
const deltaArg = JSON.parse(deltaStringArg);
var result = '',
index = 0;
/**
* Applies a diff to the original text to reconstruct the revised text.
*/
export const applyPatch = (originalArg: string, deltaStringArg: string): string => {
const deltaArg: Array<[number, string | number]> = JSON.parse(deltaStringArg);
let result = '';
let index = 0;
// According to latest jsperf tests, there's no need to cache array length
for (var i = 0; i < deltaArg.length; i++) {
const item = deltaArg[i];
for (const item of deltaArg) {
const operation = item[0];
const value = item[1];
if (operation === -1) {
// DELETE
index += value;
// DELETE: skip characters in original
index += value as number;
} else if (operation === 0) {
// KEEP
result += originalArg.slice(index, index += value);
// KEEP: copy characters from original
const length = value as number;
result += originalArg.slice(index, index + length);
index += length;
} else {
// INSERT
result += value;
// INSERT: add the new text
result += value as string;
}
}
return result;
};
// =============================================================================
// Character-Level Diff
// =============================================================================
/**
* Get character-level diff segments between two strings.
*/
export const getCharDiff = (original: string, revision: string): IDiffSegment[] => {
const changes = plugins.diff.diffChars(original, revision);
return changes.map((change) => ({
type: change.added ? 'insert' : change.removed ? 'delete' : 'equal',
value: change.value,
}));
};
/**
* Format character diff for console output with ANSI colors.
* - Deletions: red background
* - Insertions: green background
*/
export const formatCharDiffForConsole = (original: string, revision: string): string => {
const segments = getCharDiff(original, revision);
let result = '';
for (const segment of segments) {
switch (segment.type) {
case 'delete':
result += `${ANSI.bgRed}${segment.value}${ANSI.reset}`;
break;
case 'insert':
result += `${ANSI.bgGreen}${segment.value}${ANSI.reset}`;
break;
default:
result += segment.value;
}
}
return result;
};
/**
* Format character diff as HTML with styled spans.
*/
export const formatCharDiffAsHtml = (original: string, revision: string): string => {
const segments = getCharDiff(original, revision);
let result = '';
for (const segment of segments) {
const escaped = escapeHtml(segment.value);
switch (segment.type) {
case 'delete':
result += `<span class="smartdiff-delete">${escaped}</span>`;
break;
case 'insert':
result += `<span class="smartdiff-insert">${escaped}</span>`;
break;
default:
result += `<span class="smartdiff-equal">${escaped}</span>`;
}
}
return result;
};
// =============================================================================
// Word-Level Diff
// =============================================================================
/**
* Get word-level diff segments between two strings.
*/
export const getWordDiff = (original: string, revision: string): IDiffSegment[] => {
const changes = plugins.diff.diffWords(original, revision);
return changes.map((change) => ({
type: change.added ? 'insert' : change.removed ? 'delete' : 'equal',
value: change.value,
}));
};
/**
* Format word diff for console output with ANSI colors.
*/
export const formatWordDiffForConsole = (original: string, revision: string): string => {
const segments = getWordDiff(original, revision);
let result = '';
for (const segment of segments) {
switch (segment.type) {
case 'delete':
result += `${ANSI.red}${segment.value}${ANSI.reset}`;
break;
case 'insert':
result += `${ANSI.green}${segment.value}${ANSI.reset}`;
break;
default:
result += segment.value;
}
}
return result;
};
/**
* Format word diff as HTML with styled spans.
*/
export const formatWordDiffAsHtml = (original: string, revision: string): string => {
const segments = getWordDiff(original, revision);
let result = '';
for (const segment of segments) {
const escaped = escapeHtml(segment.value);
switch (segment.type) {
case 'delete':
result += `<span class="smartdiff-delete">${escaped}</span>`;
break;
case 'insert':
result += `<span class="smartdiff-insert">${escaped}</span>`;
break;
default:
result += `<span class="smartdiff-equal">${escaped}</span>`;
}
}
return result;
};
// =============================================================================
// Line-Level Diff
// =============================================================================
/**
* Get line-level diff between two strings.
*/
export const getLineDiff = (original: string, revision: string): ILineDiff[] => {
const changes = plugins.diff.diffLines(original, revision);
const result: ILineDiff[] = [];
let lineNumber = 1;
for (const change of changes) {
const lines = change.value.split('\n');
// Remove last empty element if the value ends with newline
if (lines[lines.length - 1] === '') {
lines.pop();
}
for (const line of lines) {
result.push({
lineNumber: change.removed ? lineNumber : change.added ? -1 : lineNumber,
type: change.added ? 'insert' : change.removed ? 'delete' : 'equal',
value: line,
});
if (!change.added) {
lineNumber++;
}
}
}
return result;
};
/**
* Format line diff for console output in unified diff style with ANSI colors.
*/
export const formatLineDiffForConsole = (original: string, revision: string): string => {
const changes = plugins.diff.diffLines(original, revision);
let result = '';
for (const change of changes) {
const lines = change.value.split('\n');
// Remove last empty element if the value ends with newline
if (lines[lines.length - 1] === '') {
lines.pop();
}
for (const line of lines) {
if (change.removed) {
result += `${ANSI.red}- ${line}${ANSI.reset}\n`;
} else if (change.added) {
result += `${ANSI.green}+ ${line}${ANSI.reset}\n`;
} else {
result += `${ANSI.gray} ${line}${ANSI.reset}\n`;
}
}
}
return result;
};
/**
* Format line diff as HTML with styled divs.
*/
export const formatLineDiffAsHtml = (original: string, revision: string): string => {
const changes = plugins.diff.diffLines(original, revision);
let result = '<div class="smartdiff-lines">\n';
for (const change of changes) {
const lines = change.value.split('\n');
// Remove last empty element if the value ends with newline
if (lines[lines.length - 1] === '') {
lines.pop();
}
for (const line of lines) {
const escaped = escapeHtml(line);
if (change.removed) {
result += ` <div class="smartdiff-line smartdiff-delete"><span class="smartdiff-prefix">-</span>${escaped}</div>\n`;
} else if (change.added) {
result += ` <div class="smartdiff-line smartdiff-insert"><span class="smartdiff-prefix">+</span>${escaped}</div>\n`;
} else {
result += ` <div class="smartdiff-line smartdiff-equal"><span class="smartdiff-prefix"> </span>${escaped}</div>\n`;
}
}
}
result += '</div>';
return result;
};
// =============================================================================
// Unified Diff (Git-style)
// =============================================================================
/**
* Create a unified diff patch string (like git diff output).
*/
export const createUnifiedDiff = (
original: string,
revision: string,
options?: {
originalFileName?: string;
revisedFileName?: string;
context?: number;
}
): string => {
const opts = {
originalFileName: options?.originalFileName ?? 'original',
revisedFileName: options?.revisedFileName ?? 'revised',
context: options?.context ?? 3,
};
return plugins.diff.createTwoFilesPatch(
opts.originalFileName,
opts.revisedFileName,
original,
revision,
undefined,
undefined,
{ context: opts.context }
);
};
/**
* Format unified diff for console with ANSI colors.
*/
export const formatUnifiedDiffForConsole = (
original: string,
revision: string,
options?: {
originalFileName?: string;
revisedFileName?: string;
context?: number;
}
): string => {
const patch = createUnifiedDiff(original, revision, options);
const lines = patch.split('\n');
let result = '';
for (const line of lines) {
if (line.startsWith('---') || line.startsWith('+++')) {
result += `${ANSI.gray}${line}${ANSI.reset}\n`;
} else if (line.startsWith('-')) {
result += `${ANSI.red}${line}${ANSI.reset}\n`;
} else if (line.startsWith('+')) {
result += `${ANSI.green}${line}${ANSI.reset}\n`;
} else if (line.startsWith('@@')) {
result += `${ANSI.gray}${line}${ANSI.reset}\n`;
} else {
result += `${line}\n`;
}
}
return result.trimEnd();
};
// =============================================================================
// CSS Helper
// =============================================================================
/**
* Get default CSS styles for HTML diff output.
*/
export const getDefaultDiffCss = (): string => {
return `
.smartdiff-delete {
background-color: #ffebe9;
color: #82071e;
text-decoration: line-through;
}
.smartdiff-insert {
background-color: #dafbe1;
color: #116329;
}
.smartdiff-equal {
color: inherit;
}
.smartdiff-lines {
font-family: monospace;
white-space: pre;
}
.smartdiff-line {
padding: 2px 8px;
}
.smartdiff-line.smartdiff-delete {
background-color: #ffebe9;
text-decoration: none;
}
.smartdiff-line.smartdiff-insert {
background-color: #dafbe1;
}
.smartdiff-line.smartdiff-equal {
background-color: transparent;
}
.smartdiff-prefix {
user-select: none;
margin-right: 8px;
color: #6e7781;
}
`.trim();
};
// =============================================================================
// Utility Functions
// =============================================================================
/**
* Escape HTML special characters.
*/
function escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}

View File

@@ -1,2 +1,3 @@
const removeme = {};
export { removeme };
import * as diff from 'diff';
export { diff };

12
tsconfig.json Normal file
View File

@@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}