Full Code of kpdecker/jsdiff for AI

master af7393ac3404 cached
54 files
411.5 KB
121.6k tokens
171 symbols
1 requests
Download .txt
Showing preview only (430K chars total). Download the full file or copy to clipboard to get everything.
Repository: kpdecker/jsdiff
Branch: master
Commit: af7393ac3404
Files: 54
Total size: 411.5 KB

Directory structure:
gitextract_va69jomi/

├── .babelrc
├── .gitignore
├── .npmignore
├── .yarnrc.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── eslint.config.mjs
├── examples/
│   ├── node_example.js
│   └── web_example.html
├── karma.conf.js
├── package.json
├── release-notes.md
├── rollup.config.mjs
├── runtime.js
├── src/
│   ├── convert/
│   │   ├── dmp.ts
│   │   └── xml.ts
│   ├── diff/
│   │   ├── array.ts
│   │   ├── base.ts
│   │   ├── character.ts
│   │   ├── css.ts
│   │   ├── json.ts
│   │   ├── line.ts
│   │   ├── sentence.ts
│   │   └── word.ts
│   ├── index.ts
│   ├── patch/
│   │   ├── apply.ts
│   │   ├── create.ts
│   │   ├── line-endings.ts
│   │   ├── parse.ts
│   │   └── reverse.ts
│   ├── types.ts
│   └── util/
│       ├── array.ts
│       ├── distance-iterator.ts
│       ├── params.ts
│       └── string.ts
├── test/
│   ├── convert/
│   │   └── dmp.js
│   ├── diff/
│   │   ├── array.js
│   │   ├── character.js
│   │   ├── css.js
│   │   ├── json.js
│   │   ├── line.js
│   │   ├── sentence.js
│   │   └── word.js
│   ├── index.js
│   ├── patch/
│   │   ├── apply.js
│   │   ├── create.js
│   │   ├── line-endings.js
│   │   ├── parse.js
│   │   └── reverse.js
│   └── util/
│       └── string.js
├── test-d/
│   ├── diffCharsOverloads.test-d.ts
│   └── originalDefinitelyTypedTests.test-d.ts
└── tsconfig.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .babelrc
================================================
{
  "sourceMaps": "inline",
  "presets": ["@babel/preset-env"],
  "env": {
    "test": {
      "plugins": [
        "istanbul"
      ]
    }
  }
}


================================================
FILE: .gitignore
================================================
coverage
node_modules
libesm
libcjs
dist
.nyc_output
.vscode
.zed

# Per https://yarnpkg.com/getting-started/qa#which-files-should-be-gitignored:
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions


================================================
FILE: .npmignore
================================================
.babelrc
.eslint.config.mjs
.gitignore
.npmignore
.nyc_output
.vscode
.zed
test-d
components
coverage
examples
images
index.html
karma.conf.js
rollup.config.mjs
runtime.js
src
tasks
test
tsconfig.json
yarn-error.log
yarn.lock


================================================
FILE: .yarnrc.yml
================================================
nodeLinker: node-modules


================================================
FILE: CONTRIBUTING.md
================================================
## Building and testing

```
yarn
yarn test
```

To run tests in a *browser* (for instance to test compatibility with Firefox, with Safari, or with old browser versions), run `yarn karma start`, then open http://localhost:9876/ in the browser you want to test in. Results of the test run will appear in the terminal where `yarn karma start` is running.

If you notice any problems, please report them to the GitHub issue tracker at
[http://github.com/kpdecker/jsdiff/issues](http://github.com/kpdecker/jsdiff/issues).

## Releasing

Run a test in Firefox via the procedure above before releasing.

A full release may be completed by first updating the `"version"` property in package.json, then running the following:

```
yarn clean
yarn build
yarn publish
```

After releasing, remember to:
* commit the `package.json` change and push it to GitHub
* create a new version tag on GitHub
* update `diff.js` on the `gh-pages` branch to the latest built version from the `dist/` folder.


================================================
FILE: LICENSE
================================================
BSD 3-Clause License

Copyright (c) 2009-2015, Kevin Decker <kpdecker@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


================================================
FILE: README.md
================================================
# jsdiff

A JavaScript text differencing implementation. Try it out in the **[online demo](https://kpdecker.github.io/jsdiff)**.

Based on the algorithm proposed in
["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://www.xmailserver.org/diff2.pdf).

## Installation
```bash
npm install diff --save
```

## Getting started

### Imports

In an environment where you can use imports, everything you need can be imported directly from `diff`. e.g.

ESM:

```
import {diffChars, createPatch} from 'diff';
```

CommonJS

```
const {diffChars, createPatch} = require('diff');
```

If you want to serve jsdiff to a web page without using a module system, you can use `dist/diff.js` or `dist/diff.min.js`. These create a global called `Diff` that contains the entire JsDiff API as its properties.

### Usage

jsdiff's diff functions all take an old text and a new text and perform three steps:

1. Split both texts into arrays of "tokens". What constitutes a token varies; in `diffChars`, each character is a token, while in `diffLines`, each line is a token.

2. Find the smallest set of single-token *insertions* and *deletions* needed to transform the first array of tokens into the second.

   This step depends upon having some notion of a token from the old array being "equal" to one from the new array, and this notion of equality affects the results. Usually two tokens are equal if `===` considers them equal, but some of the diff functions use an alternative notion of equality or have options to configure it. For instance, by default `diffChars("Foo", "FOOD")` will require two deletions (`o`, `o`) and three insertions (`O`, `O`, `D`), but `diffChars("Foo", "FOOD", {ignoreCase: true})` will require just one insertion (of a `D`), since `ignoreCase` causes `o` and `O` to be considered equal.

3. Return an array representing the transformation computed in the previous step as a series of [change objects](#change-objects). The array is ordered from the start of the input to the end, and each change object represents *inserting* one or more tokens, *deleting* one or more tokens, or *keeping* one or more tokens.

## API

* `diffChars(oldStr, newStr[, options])` - diffs two blocks of text, treating each character as a token.

    ("Characters" here means Unicode code points - the elements you get when you loop over a string with a `for ... of ...` loop.)

    Returns a list of [change objects](#change-objects).

    Options
    * `ignoreCase`: If `true`, the uppercase and lowercase forms of a character are considered equal. Defaults to `false`.

* `diffWords(oldStr, newStr[, options])` - diffs two blocks of text, treating each word and each punctuation mark as a token. Whitespace is ignored when computing the diff (but preserved as far as possible in the final change objects).

    Returns a list of [change objects](#change-objects).

    Options
    * `ignoreCase`: Same as in `diffChars`. Defaults to false.
    * `intlSegmenter`: An optional [`Intl.Segmenter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter) object (which must have a `granularity` of `'word'`) for `diffWords` to use to split the text into words.

      By default, `diffWords` does not use an `Intl.Segmenter`, just some regexes for splitting text into words. This will tend to give worse results than `Intl.Segmenter` would, but ensures the results are consistent across environments; `Intl.Segmenter` behaviour is only loosely specced and the implementations in browsers could in principle change dramatically in future. If you want to use `diffWords` with an `Intl.Segmenter` but ensure it behaves the same whatever environment you run it in, use an `Intl.Segmenter` polyfill instead of the JavaScript engine's native `Intl.Segmenter` implementation.

      Using an `Intl.Segmenter` should allow better word-level diffing of non-English text than the default behaviour. For instance, `Intl.Segmenter`s can generally identify via built-in dictionaries which sequences of adjacent Chinese characters form words, allowing word-level diffing of Chinese. By specifying a language when instantiating the segmenter (e.g. `new Intl.Segmenter('sv', {granularity: 'word'})`) you can also support language-specific rules, like treating Swedish's colon separated contractions (like *k:a* for *kyrka*) as single words; by default this would be seen as two words separated by a colon.

* `diffWordsWithSpace(oldStr, newStr[, options])` - diffs two blocks of text, treating each word, punctuation mark, newline, or run of (non-newline) whitespace as a token.

* `diffLines(oldStr, newStr[, options])` - diffs two blocks of text, treating each line as a token.

    Options
    * `ignoreWhitespace`: `true` to ignore leading and trailing whitespace characters when checking if two lines are equal. Defaults to `false`.
    * `ignoreNewlineAtEof`: `true` to ignore a missing newline character at the end of the last line when comparing it to other lines. (By default, the line `'b\n'` in text `'a\nb\nc'` is not considered equal to the line `'b'` in text `'a\nb'`; this option makes them be considered equal.) Ignored if `ignoreWhitespace` or `newlineIsToken` are also true.
    * `stripTrailingCr`: `true` to remove all trailing CR (`\r`) characters before performing the diff. Defaults to `false`.
      This helps to get a useful diff when diffing UNIX text files against Windows text files.
    * `newlineIsToken`: `true` to treat the newline character at the end of each line as its own token. This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of `diffLines`; the default behavior with this option turned off is better suited for patches and other computer friendly output. Defaults to `false`.

    Note that while using `ignoreWhitespace` in combination with `newlineIsToken` is not an error, results may not be as expected. With `ignoreWhitespace: true` and `newlineIsToken: false`, changing a completely empty line to contain some spaces is treated as a non-change, but with `ignoreWhitespace: true` and `newlineIsToken: true`, it is treated as an insertion. This is because the content of a completely blank line is not a token at all in `newlineIsToken` mode.

    Returns a list of [change objects](#change-objects).

* `diffSentences(oldStr, newStr[, options])` - diffs two blocks of text, treating each sentence, and the whitespace between each pair of sentences, as a token. The characters `.`, `!`, and `?`, when followed by whitespace, are treated as marking the end of a sentence; nothing else besides the end of the string is considered to mark a sentence end.

  (For more sophisticated detection of sentence breaks, including support for non-English punctuation, consider instead tokenizing with an [`Intl.Segmenter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter) with `granularity: 'sentence'` and passing the result to `diffArrays`.)

    Returns a list of [change objects](#change-objects).

* `diffCss(oldStr, newStr[, options])` - diffs two blocks of text, comparing CSS tokens.

    Returns a list of [change objects](#change-objects).

* `diffJson(oldObj, newObj[, options])` - diffs two JSON-serializable objects by first serializing them to prettily-formatted JSON and then treating each line of the JSON as a token. Object properties are ordered alphabetically in the serialized JSON, so the order of properties in the objects being compared doesn't affect the result.

    Returns a list of [change objects](#change-objects).
    
    Options
    * `stringifyReplacer`: A custom replacer function. Operates similarly to the `replacer` parameter to [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter), but must be a function.
    *  `undefinedReplacement`: A value to replace `undefined` with. Ignored if a `stringifyReplacer` is provided.

* `diffArrays(oldArr, newArr[, options])` - diffs two arrays of tokens, comparing each item for strict equality (===).

    Options
    * `comparator`: `function(left, right)` for custom equality checks

    Returns a list of [change objects](#change-objects).

* `createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr[, oldHeader[, newHeader[, options]]])` - creates a unified diff patch by first computing a diff with `diffLines` and then serializing it to unified diff format.

    Parameters:
    * `oldFileName`: String to be output in the filename section of the patch for the removals
    * `newFileName`: String to be output in the filename section of the patch for the additions
    * `oldStr`: Original string value
    * `newStr`: New string value
    * `oldHeader`: Optional additional information to include in the old file header. Default: `undefined`.
    * `newHeader`: Optional additional information to include in the new file header. Default: `undefined`.
    * `options`: An object with options.
      - `context`: describes how many lines of context should be included. You can set this to `Number.MAX_SAFE_INTEGER` or `Infinity` to include the entire file content in one hunk.
      - `ignoreWhitespace`: Same as in `diffLines`. Defaults to `false`.
      - `stripTrailingCr`: Same as in `diffLines`. Defaults to `false`.
      - `headerOptions`: Configures the format of patch headers in the returned patch. (Note these are distinct from *hunk* headers, which are a mandatory part of the unified diff format and not configurable.) Has three subfields (all default to `true`):
        - `includeIndex`: whether to include a line like `Index: filename.txt` at the start of the patch header. (Even if this is `true`, this line will be omitted if `oldFileName` and `newFileName` are not identical.)
        - `includeUnderline`: whether to include `===================================================================`.
        - `includeFileHeaders`: whether to include two lines indicating the old and new filename, formatted like `--- old.txt` and `+++ new.txt`.

        Note further that jsdiff exports three top-level constants that can be used as `headerOptions` values, named `INCLUDE_HEADERS` (the default), `FILE_HEADERS_ONLY`, and `OMIT_HEADERS`.

        (Note that in the case where `includeIndex` and `includeFileHeaders` are both false, the `oldFileName` and `newFileName` parameters are ignored entirely.)

        The GNU `patch` util will accept patches produced with any configuration of these header options (and refers to patch headers as "leading garbage", which in typical usage it makes no attempt to parse or use in any way). However, other tools for working with unified diff format patches may be less liberal (and are not unambiguously wrong to be so, since the format has no real standard). Tinkering with the `headerOptions` setting thus provides a way to help make patches produced by jsdiff compatible with other tools.

* `createPatch(fileName, oldStr, newStr[, oldHeader[, newHeader[, options]]])` - creates a unified diff patch.

    Just like createTwoFilesPatch, but with oldFileName being equal to newFileName.

* `formatPatch(patch[, headerOptions])` - creates a unified diff patch.

    `patch` may be either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`). The optional `headerOptions` argument behaves the same as the `headerOptions` option of `createTwoFilesPatch`.

* `structuredPatch(oldFileName, newFileName, oldStr, newStr[, oldHeader[, newHeader[, options]]])` - returns an object with an array of hunk objects.

    This method is similar to createTwoFilesPatch, but returns a data structure
    suitable for further processing. Parameters are the same as createTwoFilesPatch. The data structure returned may look like this:

    ```js
    {
      oldFileName: 'oldfile', newFileName: 'newfile',
      oldHeader: 'header1', newHeader: 'header2',
      hunks: [{
        oldStart: 1, oldLines: 3, newStart: 1, newLines: 3,
        lines: [' line2', ' line3', '-line4', '+line5', '\\ No newline at end of file'],
      }]
    }
    ```

* `applyPatch(source, patch[, options])` - attempts to apply a unified diff patch.

    Hunks are applied first to last. `applyPatch` first tries to apply the first hunk at the line number specified in the hunk header, and with all context lines matching exactly. If that fails, it tries scanning backwards and forwards, one line at a time, to find a place to apply the hunk where the context lines match exactly. If that still fails, and `fuzzFactor` is greater than zero, it increments the maximum number of mismatches (missing, extra, or changed context lines) that there can be between the hunk context and a region where we are trying to apply the patch such that the hunk will still be considered to match. Regardless of `fuzzFactor`, lines to be deleted in the hunk *must* be present for a hunk to match, and the context lines *immediately* before and after an insertion must match exactly.

    Once a hunk is successfully fitted, the process begins again with the next hunk. Regardless of `fuzzFactor`, later hunks must be applied later in the file than earlier hunks.

    If a hunk cannot be successfully fitted *anywhere* with fewer than `fuzzFactor` mismatches, `applyPatch` fails and returns `false`.

    If a hunk is successfully fitted but not at the line number specified by the hunk header, all subsequent hunks have their target line number adjusted accordingly. (e.g. if the first hunk is applied 10 lines below where the hunk header said it should fit, `applyPatch` will *start* looking for somewhere to apply the second hunk 10 lines below where its hunk header says it goes.)

    If the patch was applied successfully, returns a string containing the patched text. If the patch could not be applied (because some hunks in the patch couldn't be fitted to the text in `source`), `applyPatch` returns false.

    `patch` may be a string diff or the output from the `parsePatch` or `structuredPatch` methods.

    The optional `options` object may have the following keys:

    - `fuzzFactor`: Maximum Levenshtein distance (in lines deleted, added, or subtituted) between the context shown in a patch hunk and the lines found in the file. Defaults to 0.
    - `autoConvertLineEndings`: If `true`, and if the file to be patched consistently uses different line endings to the patch (i.e. either the file always uses Unix line endings while the patch uses Windows ones, or vice versa), then `applyPatch` will behave as if the line endings in the patch were the same as those in the source file. (If `false`, the patch will usually fail to apply in such circumstances since lines deleted in the patch won't be considered to match those in the source file.) Defaults to `true`.
    - `compareLine(lineNumber, line, operation, patchContent)`: Callback used to compare to given lines to determine if they should be considered equal when patching. Defaults to strict equality but may be overridden to provide fuzzier comparison. Should return false if the lines should be rejected.

* `applyPatches(patch, options)` - applies one or more patches.

    `patch` may be either an array of structured patch objects, or a string representing a patch in unified diff format (which may patch one or more files).

    This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is:

    - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution.
    - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution.

    Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made.

* `parsePatch(diffStr)` - Parses a patch into structured data

    Return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. This parses to the same structure returned by `structuredPatch`.

* `reversePatch(patch)` - Returns a new structured patch which when applied will undo the original `patch`.

    `patch` may be either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`).

* `convertChangesToXML(changes)` - converts a list of change objects to a serialized XML format

* `convertChangesToDMP(changes)` - converts a list of change objects to the format returned by Google's [diff-match-patch](https://github.com/google/diff-match-patch) library

#### Universal `options`

Certain options can be provided in the `options` object of *any* method that calculates a diff (including `diffChars`, `diffLines` etc. as well as `structuredPatch`, `createPatch`, and `createTwoFilesPatch`):

* `callback`: if provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated. The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.

  (Note that if the ONLY option you want to provide is a callback, you can pass the callback function directly as the `options` parameter instead of passing an object with a `callback` property.)

* `maxEditLength`: a number specifying the maximum edit distance to consider between the old and new texts. You can use this to limit the computational cost of diffing large, very different texts by giving up early if the cost will be huge. This option can be passed either to diffing functions (`diffLines`, `diffChars`, etc) or to patch-creation function (`structuredPatch`, `createPatch`, etc), all of which will indicate that the max edit length was reached by returning `undefined` instead of whatever they'd normally return.

* `timeout`: a number of milliseconds after which the diffing algorithm will abort and return `undefined`. Supported by the same functions as `maxEditLength`.

* `oneChangePerToken`: if `true`, the array of change objects returned will contain one change object per token (e.g. one per line if calling `diffLines`), instead of runs of consecutive tokens that are all added / all removed / all conserved being combined into a single change object.

### Defining custom diffing behaviors

If you need behavior a little different to what any of the text diffing functions above offer, you can roll your own by customizing both the tokenization behavior used and the notion of equality used to determine if two tokens are equal.

The simplest way to customize tokenization behavior is to simply tokenize the texts you want to diff yourself, with your own code, then pass the arrays of tokens to `diffArrays`. For instance, if you wanted a semantically-aware diff of some code, you could try tokenizing it using a parser specific to the programming language the code is in, then passing the arrays of tokens to `diffArrays`.

To customize the notion of token equality used, use the `comparator` option to `diffArrays`.

For even more customisation of the diffing behavior, you can extend the `Diff()` class, override its `castInput`, `tokenize`, `removeEmpty`, `equals`, and `join` properties with your own functions, then call its `diff(oldString, newString[, options])` method. The methods you can override are used as follows:

* `castInput(value, options)`: used to transform the `oldString` and `newString` before any other steps in the diffing algorithm happen. For instance, `diffJson` uses `castInput` to serialize the objects being diffed to JSON. Defaults to a no-op.
* `tokenize(value, options)`: used to convert each of `oldString` and `newString` (after they've gone through `castInput`) to an array of tokens. Defaults to returning `value.split('')` (returning an array of individual characters).
* `removeEmpty(array)`: called on the arrays of tokens returned by `tokenize` and can be used to modify them. Defaults to stripping out falsey tokens, such as empty strings. `diffArrays` overrides this to simply return the `array`, which means that falsey values like empty strings can be handled like any other token by `diffArrays`.
* `equals(left, right, options)`: called to determine if two tokens (one from the old string, one from the new string) should be considered equal. Defaults to comparing them with `===`.
* `join(tokens)`: gets called with an array of consecutive tokens that have either all been added, all been removed, or are all common. Needs to join them into a single value that can be used as the `value` property of the [change object](#change-objects) for these tokens. Defaults to simply returning `tokens.join('')` (and therefore by default will error out if your tokens are not strings; differs that support non-string tokens like `diffArrays` should override it to be a no-op to fix this).
* `postProcess(changeObjects, options)`: gets called at the end of the algorithm with the [change objects](#change-objects) produced, and can do final cleanups on them. Defaults to simply returning `changeObjects` unchanged.

### Change Objects
Many of the methods above return change objects. These objects consist of the following fields:

* `value`: The concatenated content of all the tokens represented by this change object - i.e. generally the text that is either added, deleted, or common, as a single string. In cases where tokens are considered common but are non-identical (e.g. because an option like `ignoreCase` or a custom `comparator` was used), the value from the *new* string will be provided here.
* `added`: true if the value was inserted into the new string, otherwise false
* `removed`: true if the value was removed from the old string, otherwise false
* `count`: How many tokens (e.g. chars for `diffChars`, lines for `diffLines`) the value in the change object consists of

(Change objects where `added` and `removed` are both false represent content that is common to the old and new strings.)

## Examples

#### Basic example in Node

```js
require('colors');
const {diffChars} = require('diff');

const one = 'beep boop';
const other = 'beep boob blah';

const diff = diffChars(one, other);

diff.forEach((part) => {
  // green for additions, red for deletions
  let text = part.added ? part.value.bgGreen :
             part.removed ? part.value.bgRed :
                            part.value;
  process.stderr.write(text);
});

console.log();
```
Running the above program should yield

<img src="images/node_example.png" alt="Node Example">

#### Basic example in a web page

```html
<pre id="display"></pre>
<script src="diff.js"></script>
<script>
const one = 'beep boop',
    other = 'beep boob blah',
    color = '';
    
let span = null;

const diff = Diff.diffChars(one, other),
    display = document.getElementById('display'),
    fragment = document.createDocumentFragment();

diff.forEach((part) => {
  // green for additions, red for deletions
  // grey for common parts
  const color = part.added ? 'green' :
    part.removed ? 'red' : 'grey';
  span = document.createElement('span');
  span.style.color = color;
  span.appendChild(document
    .createTextNode(part.value));
  fragment.appendChild(span);
});

display.appendChild(fragment);
</script>
```

Open the above .html file in a browser and you should see

<img src="images/web_example.png" alt="Node Example">

#### Example of generating a patch from Node

The code below is roughly equivalent to the Unix command `diff -u file1.txt file2.txt > mydiff.patch`:

```
const {createTwoFilesPatch} = require('diff');
const file1Contents = fs.readFileSync("file1.txt").toString();
const file2Contents = fs.readFileSync("file2.txt").toString();
const patch = createTwoFilesPatch("file1.txt", "file2.txt", file1Contents, file2Contents);
fs.writeFileSync("mydiff.patch", patch);
```

#### Examples of parsing and applying a patch from Node

##### Applying a patch to a specified file

The code below is roughly equivalent to the Unix command `patch file1.txt mydiff.patch`:

```
const {applyPatch} = require('diff');
const file1Contents = fs.readFileSync("file1.txt").toString();
const patch = fs.readFileSync("mydiff.patch").toString();
const patchedFile = applyPatch(file1Contents, patch);
fs.writeFileSync("file1.txt", patchedFile);
```

##### Applying a multi-file patch to the files specified by the patch file itself

The code below is roughly equivalent to the Unix command `patch < mydiff.patch`:

```
const {applyPatches} = require('diff');
const patch = fs.readFileSync("mydiff.patch").toString();
applyPatches(patch, {
    loadFile: (patch, callback) => {
        let fileContents;
        try {
            fileContents = fs.readFileSync(patch.oldFileName).toString();
        } catch (e) {
            callback(`No such file: ${patch.oldFileName}`);
            return;
        }
        callback(undefined, fileContents);
    },
    patched: (patch, patchedContent, callback) => {
        if (patchedContent === false) {
            callback(`Failed to apply patch to ${patch.oldFileName}`)
            return;
        }
        fs.writeFileSync(patch.oldFileName, patchedContent);
        callback();
    },
    complete: (err) => {
        if (err) {
            console.log("Failed with error:", err);
        }
    }
});
```

## Compatibility

jsdiff should support all ES5 environments. If you find one that it doesn't support, please [open an issue](https://github.com/kpdecker/jsdiff/issues).

## TypeScript

As of version 8, JsDiff ships with type definitions. From version 8 onwards, you should not depend on the `@types/diff` package.

One tricky pattern pervades the type definitions and is worth explaining here. Most diff-generating and patch-generating functions (`diffChars`, `diffWords`, `structuredPatch`, etc) can be run in async mode (by providing a `callback` option), in abortable mode (by passing a `timeout` or `maxEditLength` property), or both. This is awkward for typing, because these modes have different call signatures:
  * in abortable mode, the result *might* be `undefined`, and
  * in async mode, the result (which *might* be allowed to be `undefined`, depending upon whether we're in abortable mode) is passed to the provide callback instead of being returned, and the return value is always `undefined`

Our type definitions handle this as best they can by declaring different types for multiple [overload signatures](https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads) for each such function - and also by declaring different types for abortable and nonabortable options objects. For instance, an object of type `DiffCharsOptionsAbortable` is valid to pass as the `options` argument to `diffChars` and represents an *abortable* call (whose result may be `undefined`) since it necessarily contains either the `timeout` or `maxEditLength` property.

This approach, while probably the least bad way available to add types to JsDiff without radically refactoring the library's API, does not yield perfect results. *As long as* TypeScript is able to statically determine the type of your options, and therefore which overload signature is appropriate, everything should work fine. This should always be the case if you are passing an object literal as the `options` argument and inlining the definition of any `callback` function within that literal. But in cases where TypeScript *cannot* manage to do this - as may often be the case if you, say, define an `options: any = {}` object, build up your options programmatically, and then pass the result to a JsDiff function - then it is likely to fail to match the correct overload signature (probably defaulting to assuming you are calling the function in non-abortable, non-async mode), potentially causing type errors. You can either ignore (e.g. with `@ts-expect-error`) any such errors, or try to avoid them by refactoring your code so that TypeScript can always statically determine the type of the options you pass.

## License

See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE).

## Deviations from the published Myers diff algorithm

jsdiff deviates from the published algorithm in a couple of ways that don't affect results but do affect performance:

* jsdiff keeps track of the diff for each diagonal using a linked list of change objects for each diagonal, rather than the historical array of furthest-reaching D-paths on each diagonal contemplated on page 8 of Myers's paper.
* jsdiff skips considering diagonals where the furthest-reaching D-path would go off the edge of the edit graph. This dramatically reduces the time cost (from quadratic to linear) in cases where the new text just appends or truncates content at the end of the old text.


================================================
FILE: eslint.config.mjs
================================================
// @ts-check

import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import globals from "globals";

export default tseslint.config(
  {
    ignores: [
      "**/*", // ignore everything...
      "!src/**/", "!src/**/*.ts", // ... except our TypeScript source files...
      "!test/**/", "!test/**/*.js", // ... and our tests
    ],
  },
  eslint.configs.recommended,
  tseslint.configs.recommended,
  {
    files: ['src/**/*.ts'],
    languageOptions: {
      parserOptions: {
        projectService: true,
        tsconfigRootDir: import.meta.dirname,
      },
    },
    extends: [tseslint.configs.recommendedTypeChecked],
    rules: {
      // Not sure if these actually serve a purpose, but they provide a way to enforce SOME of what
      // would be imposed by having "verbatimModuleSyntax": true in our tsconfig.json without
      // actually doing that.
      "@typescript-eslint/consistent-type-imports": 2,
      "@typescript-eslint/consistent-type-exports": 2,

      // Things from the recommendedTypeChecked shared config that are disabled simply because they
      // caused lots of errors in our existing code when tried. Plausibly useful to turn on if
      // possible and somebody fancies doing the work:
      "@typescript-eslint/no-unsafe-argument": 0,
      "@typescript-eslint/no-unsafe-assignment": 0,
      "@typescript-eslint/no-unsafe-call": 0,
      "@typescript-eslint/no-unsafe-member-access": 0,
      "@typescript-eslint/no-unsafe-return": 0,
    }
  },
  {
    languageOptions: {
      globals: {
        ...globals.browser,
      },
    },

    rules: {
      // Possible Errors //
      //-----------------//
      "comma-dangle": [2, "never"],
      "no-console": 1, // Allow for debugging
      "no-debugger": 1, // Allow for debugging
      "no-extra-parens": [2, "functions"],
      "no-extra-semi": 2,
      "no-negated-in-lhs": 2,
      "no-unreachable": 1, // Optimizer and coverage will handle/highlight this and can be useful for debugging

      // Best Practices //
      //----------------//
      curly: 2,
      "default-case": 1,
      "dot-notation": [2, {
        allowKeywords: false,
      }],
      "guard-for-in": 1,
      "no-alert": 2,
      "no-caller": 2,
      "no-div-regex": 1,
      "no-eval": 2,
      "no-extend-native": 2,
      "no-extra-bind": 2,
      "no-floating-decimal": 2,
      "no-implied-eval": 2,
      "no-iterator": 2,
      "no-labels": 2,
      "no-lone-blocks": 2,
      "no-multi-spaces": 2,
      "no-multi-str": 1,
      "no-native-reassign": 2,
      "no-new": 2,
      "no-new-func": 2,
      "no-new-wrappers": 2,
      "no-octal-escape": 2,
      "no-process-env": 2,
      "no-proto": 2,
      "no-return-assign": 2,
      "no-script-url": 2,
      "no-self-compare": 2,
      "no-sequences": 2,
      "no-throw-literal": 2,
      "no-unused-expressions": 2,
      "no-warning-comments": 1,
      radix: 2,
      "wrap-iife": 2,

      // Variables //
      //-----------//
      "no-catch-shadow": 2,
      "no-label-var": 2,
      "no-undef-init": 2,

      // Node.js //
      //---------//

      // Stylistic //
      //-----------//
      "brace-style": [2, "1tbs", {
        allowSingleLine: true,
      }],
      camelcase: 2,
      "comma-spacing": [2, {
        before: false,
        after: true,
      }],
      "comma-style": [2, "last"],
      "consistent-this": [1, "self"],
      "eol-last": 2,
      "func-style": [2, "declaration"],
      "key-spacing": [2, {
        beforeColon: false,
        afterColon: true,
      }],
      "new-cap": 2,
      "new-parens": 2,
      "no-array-constructor": 2,
      "no-lonely-if": 2,
      "no-mixed-spaces-and-tabs": 2,
      "no-nested-ternary": 1,
      "no-new-object": 2,
      "no-spaced-func": 2,
      "no-trailing-spaces": 2,
      "quote-props": [2, "as-needed", {
        keywords: true,
      }],
      quotes: [2, "single", "avoid-escape"],
      semi: 2,
      "semi-spacing": [2, {
        before: false,
        after: true,
      }],
      "space-before-blocks": [2, "always"],
      "space-before-function-paren": [2, {
        anonymous: "never",
        named: "never",
      }],
      "space-in-parens": [2, "never"],
      "space-infix-ops": 2,
      "space-unary-ops": 2,
      "spaced-comment": [2, "always"],
      "wrap-regex": 1,
      "no-var": 2,

      // Typescript //
      //------------//
      "@typescript-eslint/no-explicit-any": 0, // Very strict rule, incompatible with our code

      // We use these intentionally - e.g.
      //     export interface DiffCssOptions extends CommonDiffOptions {}
      // for the options argument to diffCss which currently takes no options beyond the ones
      // common to all diffFoo functions. Doing this allows consistency (one options interface per
      // diffFoo function) and future-proofs against the API having to change in future if we add a
      // non-common option to one of these functions.
      "@typescript-eslint/no-empty-object-type": [2, {allowInterfaces: 'with-single-extends'}],
    },
  },
  {
    files: ['test/**/*.js'],
    languageOptions: {
      globals: {
        ...globals.node,
        ...globals.mocha,
      },
    },
    rules: {
      "no-unused-expressions": 0, // Needs disabling to support Chai `.to.be.undefined` etc syntax
      "@typescript-eslint/no-unused-expressions": 0, // (as above)
    },
  }
);


================================================
FILE: examples/node_example.js
================================================
require('colors');
const {diffChars} = require('diff');

const one = 'beep boop';
const other = 'beep boob blah';

const diff = diffChars(one, other);

diff.forEach((part) => {
  // green for additions, red for deletions
  let text = part.added ? part.value.bgGreen :
             part.removed ? part.value.bgRed :
                            part.value;
  process.stderr.write(text);
});

console.log();


================================================
FILE: examples/web_example.html
================================================
<!-- If you want to try this example from within the jsdiff repo, run
     `yarn build` first to build ../dist/diff.js then open this HTML file in
     a browser. -->
<pre id="display"></pre>
<script src="../dist/diff.js"></script>
<script>
var one = 'beep boop',
    other = 'beep boob blah',
    color = '',
    span = null;

var diff = Diff.diffChars(one, other),
    display = document.getElementById('display'),
    fragment = document.createDocumentFragment();

diff.forEach(function(part){
  // green for additions, red for deletions
  // grey for common parts
  color = part.added ? 'green' :
    part.removed ? 'red' : 'grey';
  span = document.createElement('span');
  span.style.color = color;
  span.appendChild(document
    .createTextNode(part.value));
  fragment.appendChild(span);
});

display.appendChild(fragment);
</script>
<style>
  #result { word-wrap: break-word; }
</style>


================================================
FILE: karma.conf.js
================================================
export default function(config) {
  config.set({
    basePath: '',

    frameworks: ['mocha'],

    files: [
      'test/**/*.js'
    ],
    preprocessors: {
      'test/**/*.js': ['webpack', 'sourcemap']
    },

    webpack: {
      devtool: 'eval',
      module: {
        rules: [
          {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader'
          }
        ]
      }
    },

    reporters: ['mocha'],

    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    singleRun: false,
  });
};


================================================
FILE: package.json
================================================
{
  "name": "diff",
  "version": "8.0.3",
  "description": "A JavaScript text diff implementation.",
  "keywords": [
    "diff",
    "jsdiff",
    "compare",
    "patch",
    "text",
    "json",
    "css",
    "javascript"
  ],
  "maintainers": [
    "Kevin Decker <kpdecker@gmail.com> (http://incaseofstairs.com)",
    "Mark Amery <markrobertamery+jsdiff@gmail.com>"
  ],
  "bugs": {
    "email": "kpdecker@gmail.com",
    "url": "http://github.com/kpdecker/jsdiff/issues"
  },
  "license": "BSD-3-Clause",
  "repository": {
    "type": "git",
    "url": "https://github.com/kpdecker/jsdiff.git"
  },
  "engines": {
    "node": ">=0.3.1"
  },
  "main": "./libcjs/index.js",
  "module": "./libesm/index.js",
  "browser": "./dist/diff.js",
  "unpkg": "./dist/diff.js",
  "exports": {
    ".": {
      "import": {
        "types": "./libesm/index.d.ts",
        "default": "./libesm/index.js"
      },
      "require": {
        "types": "./libcjs/index.d.ts",
        "default": "./libcjs/index.js"
      }
    },
    "./package.json": "./package.json",
    "./lib/*.js": {
      "import": {
        "types": "./libesm/*.d.ts",
        "default": "./libesm/*.js"
      },
      "require": {
        "types": "./libcjs/*.d.ts",
        "default": "./libcjs/*.js"
      }
    },
    "./lib/": {
      "import": {
        "types": "./libesm/",
        "default": "./libesm/"
      },
      "require": {
        "types": "./libcjs/",
        "default": "./libcjs/"
      }
    }
  },
  "type": "module",
  "types": "libcjs/index.d.ts",
  "scripts": {
    "clean": "rm -rf libcjs/ libesm/ dist/ coverage/ .nyc_output/",
    "lint": "yarn eslint",
    "build": "yarn lint && yarn generate-esm && yarn generate-cjs && yarn check-types && yarn run-rollup && yarn run-uglify",
    "generate-cjs": "yarn tsc --module commonjs --outDir libcjs && node --eval \"fs.writeFileSync('libcjs/package.json', JSON.stringify({type:'commonjs',sideEffects:false}))\"",
    "generate-esm": "yarn tsc --module nodenext --outDir libesm --target es6 && node --eval \"fs.writeFileSync('libesm/package.json', JSON.stringify({type:'module',sideEffects:false}))\"",
    "check-types": "yarn run-tsd && yarn run-attw",
    "test": "nyc yarn _test",
    "_test": "yarn build && cross-env NODE_ENV=test yarn run-mocha",
    "run-attw": "yarn attw --pack --entrypoints . && yarn attw --pack --entrypoints lib/diff/word.js --profile node16",
    "run-tsd": "yarn tsd --typings libesm/ && yarn tsd --files test-d/",
    "run-rollup": "rollup -c rollup.config.mjs",
    "run-uglify": "uglifyjs dist/diff.js -c -o dist/diff.min.js",
    "run-mocha": "mocha --require ./runtime 'test/**/*.js'"
  },
  "devDependencies": {
    "@arethetypeswrong/cli": "^0.18.2",
    "@babel/core": "^7.29.0",
    "@babel/preset-env": "^7.29.0",
    "@babel/register": "^7.28.6",
    "@colors/colors": "^1.6.0",
    "@eslint/js": "^10.0.1",
    "babel-loader": "^10.0.0",
    "babel-plugin-istanbul": "^7.0.1",
    "chai": "^6.2.2",
    "cross-env": "^10.1.0",
    "eslint": "^10.0.2",
    "globals": "^17.4.0",
    "karma": "^6.4.4",
    "karma-mocha": "^2.0.1",
    "karma-mocha-reporter": "^2.2.5",
    "karma-sourcemap-loader": "^0.4.0",
    "karma-webpack": "^5.0.1",
    "mocha": "^11.7.5",
    "nyc": "^18.0.0",
    "rollup": "^4.59.0",
    "tsd": "^0.33.0",
    "typescript": "^5.9.3",
    "typescript-eslint": "^8.56.1",
    "uglify-js": "^3.19.3",
    "webpack": "^5.105.3",
    "webpack-dev-server": "^5.2.3"
  },
  "nyc": {
    "require": [
      "@babel/register"
    ],
    "reporter": [
      "lcov",
      "text"
    ],
    "sourceMap": false,
    "instrument": false,
    "check-coverage": true,
    "branches": 100,
    "lines": 100,
    "functions": 100,
    "statements": 100
  },
  "packageManager": "yarn@4.12.0"
}


================================================
FILE: release-notes.md
================================================
# Release Notes

## 8.0.4 (prerelease)

- [#667](https://github.com/kpdecker/jsdiff/pull/667) - **fix another bug in `diffWords` when used with an `Intl.Segmenter`**. If the text to be diffed included a combining mark after a whitespace character (i.e. roughly speaking, an accented space), `diffWords` would previously crash. Now this case is handled correctly.

## 8.0.3

- [#631](https://github.com/kpdecker/jsdiff/pull/631) - **fix support for using an `Intl.Segmenter` with `diffWords`**. This has been almost completely broken since the feature was added in v6.0.0, since it would outright crash on any text that featured two consecutive newlines between a pair of words (a very common case).
- [#635](https://github.com/kpdecker/jsdiff/pull/635) - **small tweaks to tokenization behaviour of `diffWords`** when used *without* an `Intl.Segmenter`. Specifically, the soft hyphen (U+00AD) is no longer considered to be a word break, and the multiplication and division signs (`×` and `÷`) are now treated as punctuation instead of as letters / word characters.
- [#641](https://github.com/kpdecker/jsdiff/pull/641) - **the format of file headers in `createPatch` etc. patches can now be customised somewhat**. It now takes a `headerOptions` option that can be used to disable the file headers entirely, or omit the `Index:` line and/or the underline. In particular, this was motivated by a request to make jsdiff patches compatible with react-diff-view, which they now are if produced with `headerOptions: FILE_HEADERS_ONLY`.
- [#647](https://github.com/kpdecker/jsdiff/pull/647) and [#649](https://github.com/kpdecker/jsdiff/pull/649) - **fix denial-of-service vulnerabilities in `parsePatch` whereby adversarial input could cause a memory-leaking infinite loop, typically crashing the calling process**. Also fixed ReDOS vulnerabilities whereby adversarially-crafted patch headers could take cubic time to parse. Now, `parsePatch` should reliably take linear time. (Handling of headers that include the line break characters `\r`, `\u2028`, or `\u2029` in non-trailing positions is also now more reasonable as side effect of the fix.)

## 8.0.2

- [#616](https://github.com/kpdecker/jsdiff/pull/616) **Restored compatibility of `diffSentences` with old Safari versions.** This was broken in 8.0.0 by the introduction of a regex with a [lookbehind assertion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion); these weren't supported in Safari prior to version 16.4.
- [#612](https://github.com/kpdecker/jsdiff/pull/612) **Improved tree shakeability** by marking the built CJS and ESM packages with `sideEffects: false`.

## 8.0.1

- [#610](https://github.com/kpdecker/jsdiff/pull/610) **Fixes types for `diffJson` which were broken by 8.0.0**. The new bundled types in 8.0.0 only allowed `diffJson` to be passed string arguments, but it should've been possible to pass either strings or objects (and now is). Thanks to Josh Kelley for the fix.

## 8.0.0

- [#580](https://github.com/kpdecker/jsdiff/pull/580) **Multiple tweaks to `diffSentences`**:
  * tokenization no longer takes quadratic time on pathological inputs (reported as a ReDOS vulnerability by Snyk); is now linear instead
  * the final sentence in the string is now handled the same by the tokenizer regardless of whether it has a trailing punctuation mark or not. (Previously, "foo. bar." tokenized to `["foo.", " ", "bar."]` but "foo. bar" tokenized to `["foo.", " bar"]` - i.e. whether the space between sentences was treated as a separate token depended upon whether the final sentence had trailing punctuation or not. This was arbitrary and surprising; it is no longer the case.)
  * in a string that starts with a sentence end, like "! hello.", the "!" is now treated as a separate sentence
  * the README now correctly documents the tokenization behaviour (it was wrong before)
- [#581](https://github.com/kpdecker/jsdiff/pull/581) - **fixed some regex operations used for tokenization in `diffWords` taking O(n^2) time** in pathological cases
- [#595](https://github.com/kpdecker/jsdiff/pull/595) - **fixed a crash in patch creation functions when handling a single hunk consisting of a very large number (e.g. >130k) of lines**. (This was caused by spreading indefinitely-large arrays to `.push()` using `.apply` or the spread operator and hitting the JS-implementation-specific limit on the maximum number of arguments to a function, as shown at https://stackoverflow.com/a/56809779/1709587; thus the exact threshold to hit the error will depend on the environment in which you were running JsDiff.)
- [#596](https://github.com/kpdecker/jsdiff/pull/596) - **removed the `merge` function**. Previously JsDiff included an undocumented function called `merge` that was meant to, in some sense, merge patches. It had at least a couple of serious bugs that could lead to it returning unambiguously wrong results, and it was difficult to simply "fix" because it was [unclear precisely what it was meant to do](https://github.com/kpdecker/jsdiff/issues/181#issuecomment-2198319542). For now, the fix is to remove it entirely.
- [#591](https://github.com/kpdecker/jsdiff/pull/591) - JsDiff's source code has been rewritten in TypeScript. This change entails the following changes for end users:
  * **the `diff` package on npm now includes its own TypeScript type definitions**. Users who previously used the `@types/diff` npm package from DefinitelyTyped should remove that dependency when upgrading JsDiff to v8.

    Note that the transition from the DefinitelyTyped types to JsDiff's own type definitions includes multiple fixes and also removes many exported types previously used for `options` arguments to diffing and patch-generation functions. (There are now different exported options types for abortable calls - ones with a `timeout` or `maxEditLength` that may give a result of `undefined` - and non-abortable calls.) See the TypeScript section of the README for some usage tips.

  * **The `Diff` object is now a class**. Custom extensions of `Diff`, as described in the "Defining custom diffing behaviors" section of the README, can therefore now be done by writing a `class CustomDiff extends Diff` and overriding methods, instead of the old way based on prototype inheritance. (I *think* code that did things the old way should still work, though!)

  * **`diff/lib/index.es6.js` and `diff/lib/index.mjs` no longer exist, and the ESM version of the library is no longer bundled into a single file.**

  * **The `ignoreWhitespace` option for `diffWords` is no longer included in the type declarations**. The effect of passing `ignoreWhitespace: true` has always been to make `diffWords` just call `diffWordsWithSpace` instead, which was confusing, because that behaviour doesn't seem properly described as "ignoring" whitespace at all. The property remains available to non-TypeScript applications for the sake of backwards compatibility, but TypeScript applications will now see a type error if they try to pass `ignoreWhitespace: true` to `diffWords` and should change their code to call `diffWordsWithSpace` instead.

  * JsDiff no longer purports to support ES3 environments. (I'm pretty sure it never truly did, despite claiming to in its README, since even the 1.0.0 release used `Array.map` which was added in ES5.)
- [#601](https://github.com/kpdecker/jsdiff/pull/601) - **`diffJson`'s `stringifyReplacer` option behaves more like `JSON.stringify`'s `replacer` argument now.** In particular:
  * Each key/value pair now gets passed through the replacer once instead of twice
  * The `key` passed to the replacer when the top-level object is passed in as `value` is now `""` (previously, was `undefined`), and the `key` passed with an array element is the array index as a string, like `"0"` or `"1"` (previously was whatever the key for the entire array was). Both the new behaviours match that of `JSON.stringify`.
- [#602](https://github.com/kpdecker/jsdiff/pull/602) - **diffing functions now consistently return `undefined` when called in async mode** (i.e. with a callback). Previously, there was an odd quirk where they would return `true` if the strings being diffed were equal and `undefined` otherwise.

## 7.0.0

Just a single (breaking) bugfix, undoing a behaviour change introduced accidentally in 6.0.0:

- [#554](https://github.com/kpdecker/jsdiff/pull/554) **`diffWords` treats numbers and underscores as word characters again.** This behaviour was broken in v6.0.0.

## 6.0.0

This is a release containing many, *many* breaking changes. The objective of this release was to carry out a mass fix, in one go, of all the open bugs and design problems that required breaking changes to fix. A substantial, but exhaustive, changelog is below.

[Commits](https://github.com/kpdecker/jsdiff/compare/v5.2.0...v6.0.0)

- [#497](https://github.com/kpdecker/jsdiff/pull/497) **`diffWords` behavior has been radically changed.** Previously, even with `ignoreWhitespace: true`, runs of whitespace were tokens, which led to unhelpful and unintuitive diffing behavior in typical texts. Specifically, even when two texts contained overlapping passages, `diffWords` would sometimes choose to delete all the words from the old text and insert them anew in their new positions in order to avoid having to delete or insert whitespace tokens. Whitespace sequences are no longer tokens as of this release, which affects both the generated diffs and the `count`s.

  Runs of whitespace are still tokens in `diffWordsWithSpace`.

  As part of the changes to `diffWords`, **a new `.postProcess` method has been added on the base `Diff` type**, which can be overridden in custom `Diff` implementations.

  **`diffLines` with `ignoreWhitespace: true` will no longer ignore the insertion or deletion of entire extra lines of whitespace at the end of the text**. Previously, these would not show up as insertions or deletions, as a side effect of a hack in the base diffing algorithm meant to help ignore whitespace in `diffWords`. More generally, **the undocumented special handling in the core algorithm for ignored terminals has been removed entirely.** (This special case behavior used to rewrite the final two change objects in a scenario where the final change object was an addition or deletion and its `value` was treated as equal to the empty string when compared using the diff object's `.equals` method.)

- [#500](https://github.com/kpdecker/jsdiff/pull/500) **`diffChars` now diffs Unicode code points** instead of UTF-16 code units.
- [#508](https://github.com/kpdecker/jsdiff/pull/508) **`parsePatch` now always runs in what was previously "strict" mode; the undocumented `strict` option has been removed.** Previously, by default, `parsePatch` (and other patch functions that use it under the hood to parse patches) would accept a patch where the line counts in the headers were inconsistent with the actual patch content - e.g. where a hunk started with the header `@@ -1,3 +1,6 @@`, indicating that the content below spanned 3 lines in the old file and 6 lines in the new file, but then the actual content below the header consisted of some different number of lines, say 10 lines of context, 5 deletions, and 1 insertion. Actually trying to work with these patches using `applyPatch` or `merge`, however, would produce incorrect results instead of just ignoring the incorrect headers, making this "feature" more of a trap than something actually useful. It's been ripped out, and now we are always "strict" and will reject patches where the line counts in the headers aren't consistent with the actual patch content.
- [#435](https://github.com/kpdecker/jsdiff/pull/435) **Fix `parsePatch` handling of control characters.** `parsePatch` used to interpret various unusual control characters - namely vertical tabs, form feeds, lone carriage returns without a line feed, and EBCDIC NELs - as line breaks when parsing a patch file. This was inconsistent with the behavior of both JsDiff's own `diffLines` method and also the Unix `diff` and `patch` utils, which all simply treat those control characters as ordinary characters. The result of this discrepancy was that some well-formed patches - produced either by `diff` or by JsDiff itself and handled properly by the `patch` util - would be wrongly parsed by `parsePatch`, with the effect that it would disregard the remainder of a hunk after encountering one of these control characters.
- [#439](https://github.com/kpdecker/jsdiff/pull/439) **Prefer diffs that order deletions before insertions.** When faced with a choice between two diffs with an equal total edit distance, the Myers diff algorithm generally prefers one that does deletions before insertions rather than insertions before deletions. For instance, when diffing `abcd` against `acbd`, it will prefer a diff that says to delete the `b` and then insert a new `b` after the `c`, over a diff that says to insert a `c` before the `b` and then delete the existing `c`. JsDiff deviated from the published Myers algorithm in a way that led to it having the opposite preference in many cases, including that example. This is now fixed, meaning diffs output by JsDiff will more accurately reflect what the published Myers diff algorithm would output.
- [#455](https://github.com/kpdecker/jsdiff/pull/455) **The `added` and `removed` properties of change objects are now guaranteed to be set to a boolean value.** (Previously, they would be set to `undefined` or omitted entirely instead of setting them to false.)
- [#464](https://github.com/kpdecker/jsdiff/pull/464) Specifying `{maxEditLength: 0}` now sets a max edit length of 0 instead of no maximum.
- [#460](https://github.com/kpdecker/jsdiff/pull/460) **Added `oneChangePerToken` option.**
- [#467](https://github.com/kpdecker/jsdiff/pull/467) **Consistent ordering of arguments to `comparator(left, right)`.** Values from the old array will now consistently be passed as the first argument (`left`) and values from the new array as the second argument (`right`). Previously this was almost (but not quite) always the other way round.
- [#480](https://github.com/kpdecker/jsdiff/pull/480) **Passing `maxEditLength` to `createPatch` & `createTwoFilesPatch` now works properly** (i.e. returns undefined if the max edit distance is exceeded; previous behavior was to crash with a `TypeError` if the edit distance was exceeded).
- [#486](https://github.com/kpdecker/jsdiff/pull/486) **The `ignoreWhitespace` option of `diffLines` behaves more sensibly now.** `value`s in returned change objects now include leading/trailing whitespace even when `ignoreWhitespace` is used, just like how with `ignoreCase` the `value`s still reflect the case of one of the original texts instead of being all-lowercase. `ignoreWhitespace` is also now compatible with `newlineIsToken`. Finally, **`diffTrimmedLines` is deprecated** (and removed from the docs) in favour of using `diffLines` with `ignoreWhitespace: true`; the two are, and always have been, equivalent.
- [#490](https://github.com/kpdecker/jsdiff/pull/490) **When calling diffing functions in async mode by passing a `callback` option, the diff result will now be passed as the *first* argument to the callback instead of the second.** (Previously, the first argument was never used at all and would always have value `undefined`.)
- [#489](https://github.com/kpdecker/jsdiff/pull/489) **`this.options` no longer exists on `Diff` objects.** Instead, `options` is now passed as an argument to methods that rely on options, like `equals(left, right, options)`. This fixes a race condition in async mode, where diffing behaviour could be changed mid-execution if a concurrent usage of the same `Diff` instances overwrote its `options`.
- [#518](https://github.com/kpdecker/jsdiff/pull/518) **`linedelimiters` no longer exists** on patch objects; instead, when a patch with Windows-style CRLF line endings is parsed, **the lines in `lines` will end with `\r`**. There is now a **new `autoConvertLineEndings` option, on by default**, which makes it so that when a patch with Windows-style line endings is applied to a source file with Unix style line endings, the patch gets autoconverted to use Unix-style line endings, and when a patch with Unix-style line endings is applied to a source file with Windows-style line endings, it gets autoconverted to use Windows-style line endings.
- [#521](https://github.com/kpdecker/jsdiff/pull/521) **the `callback` option is now supported by `structuredPatch`, `createPatch`, and `createTwoFilesPatch`**
- [#529](https://github.com/kpdecker/jsdiff/pull/529) **`parsePatch` can now parse patches where lines starting with `--` or `++` are deleted/inserted**; previously, there were edge cases where the parser would choke on valid patches or give wrong results.
- [#530](https://github.com/kpdecker/jsdiff/pull/530) **Added `ignoreNewlineAtEof` option to `diffLines`**
- [#533](https://github.com/kpdecker/jsdiff/pull/533) **`applyPatch` uses an entirely new algorithm for fuzzy matching.** Differences between the old and new algorithm are as follows:
  * The `fuzzFactor` now indicates the maximum [*Levenshtein* distance](https://en.wikipedia.org/wiki/Levenshtein_distance) that there can be between the context shown in a hunk and the actual file content at a location where we try to apply the hunk. (Previously, it represented a maximum [*Hamming* distance](https://en.wikipedia.org/wiki/Hamming_distance), meaning that a single insertion or deletion in the source file could stop a hunk from applying even with a high `fuzzFactor`.)
  * A hunk containing a deletion can now only be applied in a context where the line to be deleted actually appears verbatim. (Previously, as long as enough context lines in the hunk matched, `applyPatch` would apply the hunk anyway and delete a completely different line.)
  * The context line immediately before and immediately after an insertion must match exactly between the hunk and the file for a hunk to apply. (Previously this was not required.)
- [#535](https://github.com/kpdecker/jsdiff/pull/535) **A bug in patch generation functions is now fixed** that would sometimes previously cause `\ No newline at end of file` to appear in the wrong place in the generated patch, resulting in the patch being invalid. **These invalid patches can also no longer be applied successfully with `applyPatch`.** (It was already the case that tools other than jsdiff, like GNU `patch`, would consider them malformed and refuse to apply them; versions of jsdiff with this fix now do the same thing if you ask them to apply a malformed patch emitted by jsdiff v5.)
- [#535](https://github.com/kpdecker/jsdiff/pull/535) **Passing `newlineIsToken: true` to *patch*-generation functions is no longer allowed.** (Passing it to `diffLines` is still supported - it's only functions like `createPatch` where passing `newlineIsToken` is now an error.) Allowing it to be passed never really made sense, since in cases where the option had any effect on the output at all, the effect tended to be causing a garbled patch to be created that couldn't actually be applied to the source file.
- [#539](https://github.com/kpdecker/jsdiff/pull/539) **`diffWords` now takes an optional `intlSegmenter` option** which should be an `Intl.Segmenter` with word-level granularity. This provides better tokenization of text into words than the default behaviour, even for English but especially for some other languages for which the default behaviour is poor.

## v5.2.2 - January 2026

Only change from 5.2.0 is a backport of the fix to https://github.com/kpdecker/jsdiff/security/advisories/GHSA-73rr-hh4g-fpgx.

## v5.2.1 (deprecated)

Accidental release - do not use.

## v5.2.0

[Commits](https://github.com/kpdecker/jsdiff/compare/v5.1.0...v5.2.0)

- [#411](https://github.com/kpdecker/jsdiff/pull/411) Big performance improvement. Previously an O(n) array-copying operation inside the innermost loop of jsdiff's base diffing code increased the overall worst-case time complexity of computing a diff from O(n²) to O(n³). This is now fixed, bringing the worst-case time complexity down to what it theoretically should be for a Myers diff implementation.
- [#448](https://github.com/kpdecker/jsdiff/pull/448) Performance improvement. Diagonals whose furthest-reaching D-path would go off the edge of the edit graph are now skipped, rather than being pointlessly considered as called for by the original Myers diff algorithm. This dramatically speeds up computing diffs where the new text just appends or truncates content at the end of the old text.
- [#351](https://github.com/kpdecker/jsdiff/issues/351) Importing from the lib folder - e.g. `require("diff/lib/diff/word.js")` - will work again now. This had been broken for users on the latest version of Node since Node 17.5.0, which changed how Node interprets the `exports` property in jsdiff's `package.json` file.
- [#344](https://github.com/kpdecker/jsdiff/issues/344) `diffLines`, `createTwoFilesPatch`, and other patch-creation methods now take an optional `stripTrailingCr: true` option which causes Windows-style `\r\n` line endings to be replaced with Unix-style `\n` line endings before calculating the diff, just like GNU `diff`'s `--strip-trailing-cr` flag.
- [#451](https://github.com/kpdecker/jsdiff/pull/451) Added `diff.formatPatch`.
- [#450](https://github.com/kpdecker/jsdiff/pull/450) Added `diff.reversePatch`.
- [#478](https://github.com/kpdecker/jsdiff/pull/478) Added `timeout` option.

## v5.1.0

- [#365](https://github.com/kpdecker/jsdiff/issues/365) Allow early termination to limit execution time with degenerate cases

[Commits](https://github.com/kpdecker/jsdiff/compare/v5.0.0...v5.1.0)

## v5.0.0

- Breaking: UMD export renamed from `JsDiff` to `Diff`.
- Breaking: Newlines separated into separate tokens for word diff.
- Breaking: Unified diffs now match ["quirks"](https://www.artima.com/weblogs/viewpost.jsp?thread=164293)

[Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.1...v5.0.0)

## v4.0.4 - January 2026

Only change from 4.0.2 is a backport of the fix to https://github.com/kpdecker/jsdiff/security/advisories/GHSA-73rr-hh4g-fpgx.

## v4.0.3 (deprecated)

Accidental release - do not use.

## v4.0.2

No meaningful changes from v4.0.1 - just removed some cruft that shouldn't've been published.

## v4.0.1 - January 6th, 2019

- Fix main reference path - b826104

[Commits](https://github.com/kpdecker/jsdiff/compare/v4.0.0...v4.0.1)

## v4.0.0 - January 5th, 2019

- [#94](https://github.com/kpdecker/jsdiff/issues/94) - Missing "No newline at end of file" when comparing two texts that do not end in newlines ([@federicotdn](https://api.github.com/users/federicotdn))
- [#227](https://github.com/kpdecker/jsdiff/issues/227) - Licence
- [#199](https://github.com/kpdecker/jsdiff/issues/199) - Import statement for jsdiff
- [#159](https://github.com/kpdecker/jsdiff/issues/159) - applyPatch affecting wrong line number with with new lines
- [#8](https://github.com/kpdecker/jsdiff/issues/8) - A new state "replace"
- Drop ie9 from karma targets - 79c31bd
- Upgrade deps. Convert from webpack to rollup - 2c1a29c
- Make ()[]"' as word boundaries between each other - f27b899
- jsdiff: Replaced phantomJS by chrome - ec3114e
- Add yarn.lock to .npmignore - 29466d8

Compatibility notes:

- Bower and Component packages no longer supported

[Commits](https://github.com/kpdecker/jsdiff/compare/v3.5.0...v4.0.0)

## v3.5.1 - January 2026

Only change from 3.5.0 is a backport of the fix to https://github.com/kpdecker/jsdiff/security/advisories/GHSA-73rr-hh4g-fpgx.

## v3.5.0 - March 4th, 2018

- Omit redundant slice in join method of diffArrays - 1023590
- Support patches with empty lines - fb0f208
- Accept a custom JSON replacer function for JSON diffing - 69c7f0a
- Optimize parch header parser - 2aec429
- Fix typos - e89c832

[Commits](https://github.com/kpdecker/jsdiff/compare/v3.4.0...v3.5.0)

## v3.4.0 - October 7th, 2017

- [#183](https://github.com/kpdecker/jsdiff/issues/183) - Feature request: ability to specify a custom equality checker for `diffArrays`
- [#173](https://github.com/kpdecker/jsdiff/issues/173) - Bug: diffArrays gives wrong result on array of booleans
- [#158](https://github.com/kpdecker/jsdiff/issues/158) - diffArrays will not compare the empty string in array?
- comparator for custom equality checks - 30e141e
- count oldLines and newLines when there are conflicts - 53bf384
- Fix: diffArrays can compare falsey items - 9e24284
- Docs: Replace grunt with npm test - 00e2f94

[Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.1...v3.4.0)

## v3.3.1 - September 3rd, 2017

- [#141](https://github.com/kpdecker/jsdiff/issues/141) - Cannot apply patch because my file delimiter is "/r/n" instead of "/n"
- [#192](https://github.com/kpdecker/jsdiff/pull/192) - Fix: Bad merge when adding new files (#189)
- correct spelling mistake - 21fa478

[Commits](https://github.com/kpdecker/jsdiff/compare/v3.3.0...v3.3.1)

## v3.3.0 - July 5th, 2017

- [#114](https://github.com/kpdecker/jsdiff/issues/114) - /patch/merge not exported
- Gracefully accept invalid newStart in hunks, same as patch(1) does. - d8a3635
- Use regex rather than starts/ends with for parsePatch - 6cab62c
- Add browser flag - e64f674
- refactor: simplified code a bit more - 8f8e0f2
- refactor: simplified code a bit - b094a6f
- fix: some corrections re ignoreCase option - 3c78fd0
- ignoreCase option - 3cbfbb5
- Sanitize filename while parsing patches - 2fe8129
- Added better installation methods - aced50b
- Simple export of functionality - 8690f31

[Commits](https://github.com/kpdecker/jsdiff/compare/v3.2.0...v3.3.0)

## v3.2.0 - December 26th, 2016

- [#156](https://github.com/kpdecker/jsdiff/pull/156) - Add `undefinedReplacement` option to `diffJson` ([@ewnd9](https://api.github.com/users/ewnd9))
- [#154](https://github.com/kpdecker/jsdiff/pull/154) - Add `examples` and `images` to `.npmignore`. ([@wtgtybhertgeghgtwtg](https://api.github.com/users/wtgtybhertgeghgtwtg))
- [#153](https://github.com/kpdecker/jsdiff/pull/153) - feat(structuredPatch): Pass options to diffLines ([@Kiougar](https://api.github.com/users/Kiougar))

[Commits](https://github.com/kpdecker/jsdiff/compare/v3.1.0...v3.2.0)

## v3.1.0 - November 27th, 2016

- [#146](https://github.com/kpdecker/jsdiff/pull/146) - JsDiff.diffArrays to compare arrays ([@wvanderdeijl](https://api.github.com/users/wvanderdeijl))
- [#144](https://github.com/kpdecker/jsdiff/pull/144) - Split file using all possible line delimiter instead of hard-coded "/n" and join lines back using the original delimiters ([@soulbeing](https://api.github.com/users/soulbeing))

[Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.1...v3.1.0)

## v3.0.1 - October 9th, 2016

- [#139](https://github.com/kpdecker/jsdiff/pull/139) - Make README.md look nicer in npmjs.com ([@takenspc](https://api.github.com/users/takenspc))
- [#135](https://github.com/kpdecker/jsdiff/issues/135) - parsePatch combines patches from multiple files into a single IUniDiff when there is no "Index" line ([@ramya-rao-a](https://api.github.com/users/ramya-rao-a))
- [#124](https://github.com/kpdecker/jsdiff/issues/124) - IE7/IE8 failure since 2.0.0 ([@boneskull](https://api.github.com/users/boneskull))

[Commits](https://github.com/kpdecker/jsdiff/compare/v3.0.0...v3.0.1)

## v3.0.0 - August 23rd, 2016

- [#130](https://github.com/kpdecker/jsdiff/pull/130) - Add callback argument to applyPatches `patched` option ([@piranna](https://api.github.com/users/piranna))
- [#120](https://github.com/kpdecker/jsdiff/pull/120) - Correctly handle file names containing spaces ([@adius](https://api.github.com/users/adius))
- [#119](https://github.com/kpdecker/jsdiff/pull/119) - Do single reflow ([@wifiextender](https://api.github.com/users/wifiextender))
- [#117](https://github.com/kpdecker/jsdiff/pull/117) - Make more usable with long strings. ([@abnbgist](https://api.github.com/users/abnbgist))

Compatibility notes:

- applyPatches patch callback now is async and requires the callback be called to continue operation

[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.3...v3.0.0)

## v2.2.3 - May 31st, 2016

- [#118](https://github.com/kpdecker/jsdiff/pull/118) - Add a fix for applying 0-length destination patches ([@chaaz](https://api.github.com/users/chaaz))
- [#115](https://github.com/kpdecker/jsdiff/pull/115) - Fixed grammar in README ([@krizalys](https://api.github.com/users/krizalys))
- [#113](https://github.com/kpdecker/jsdiff/pull/113) - fix typo ([@vmazare](https://api.github.com/users/vmazare))

[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.2...v2.2.3)

## v2.2.2 - March 13th, 2016

- [#102](https://github.com/kpdecker/jsdiff/issues/102) - diffJson with dates, returns empty curly braces ([@dr-dimitru](https://api.github.com/users/dr-dimitru))
- [#97](https://github.com/kpdecker/jsdiff/issues/97) - Whitespaces & diffWords ([@faiwer](https://api.github.com/users/faiwer))
- [#92](https://github.com/kpdecker/jsdiff/pull/92) - Fixes typo in the readme ([@bg451](https://api.github.com/users/bg451))

[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.1...v2.2.2)

## v2.2.1 - November 12th, 2015

- [#89](https://github.com/kpdecker/jsdiff/pull/89) - add in display selector to readme ([@FranDias](https://api.github.com/users/FranDias))
- [#88](https://github.com/kpdecker/jsdiff/pull/88) - Split diffs based on file headers instead of 'Index:' metadata ([@piranna](https://api.github.com/users/piranna))

[Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.1)

## v2.2.0 - October 29th, 2015

- [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath -> applyPatch ([@fluxxu](https://api.github.com/users/fluxxu))
- [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna))
  [Commits](https://github.com/kpdecker/jsdiff/compare/v2.2.0...v2.2.0)

## v2.2.0 - October 29th, 2015

- [#80](https://github.com/kpdecker/jsdiff/pull/80) - Fix a typo: applyPath -> applyPatch ([@fluxxu](https://api.github.com/users/fluxxu))
- [#83](https://github.com/kpdecker/jsdiff/pull/83) - Add basic fuzzy matching to applyPatch ([@piranna](https://github.com/piranna))
  [Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.3...v2.2.0)

## v2.1.3 - September 30th, 2015

- [#78](https://github.com/kpdecker/jsdiff/pull/78) - fix: error throwing when apply patch to empty string ([@21paradox](https://api.github.com/users/21paradox))

[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.2...v2.1.3)

## v2.1.2 - September 23rd, 2015

- [#76](https://github.com/kpdecker/jsdiff/issues/76) - diff headers give error ([@piranna](https://api.github.com/users/piranna))

[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.1...v2.1.2)

## v2.1.1 - September 9th, 2015

- [#73](https://github.com/kpdecker/jsdiff/issues/73) - Is applyPatches() exposed in the API? ([@davidparsson](https://api.github.com/users/davidparsson))

[Commits](https://github.com/kpdecker/jsdiff/compare/v2.1.0...v2.1.1)

## v2.1.0 - August 27th, 2015

- [#72](https://github.com/kpdecker/jsdiff/issues/72) - Consider using options object API for flag permutations ([@kpdecker](https://api.github.com/users/kpdecker))
- [#70](https://github.com/kpdecker/jsdiff/issues/70) - diffWords treats \n at the end as significant whitespace ([@nesQuick](https://api.github.com/users/nesQuick))
- [#69](https://github.com/kpdecker/jsdiff/issues/69) - Missing count ([@wfalkwallace](https://api.github.com/users/wfalkwallace))
- [#68](https://github.com/kpdecker/jsdiff/issues/68) - diffLines seems broken ([@wfalkwallace](https://api.github.com/users/wfalkwallace))
- [#60](https://github.com/kpdecker/jsdiff/issues/60) - Support multiple diff hunks ([@piranna](https://api.github.com/users/piranna))
- [#54](https://github.com/kpdecker/jsdiff/issues/54) - Feature Request: 3-way merge ([@mog422](https://api.github.com/users/mog422))
- [#42](https://github.com/kpdecker/jsdiff/issues/42) - Fuzz factor for applyPatch ([@stuartpb](https://api.github.com/users/stuartpb))
- Move whitespace ignore out of equals method - 542063c
- Include source maps in babel output - 7f7ab21
- Merge diff/line and diff/patch implementations - 1597705
- Drop map utility method - 1ddc939
- Documentation for parsePatch and applyPatches - 27c4b77

Compatibility notes:

- The undocumented ignoreWhitespace flag has been removed from the Diff equality check directly. This implementation may be copied to diff utilities if dependencies existed on this functionality.

[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.2...v2.1.0)

## v2.0.2 - August 8th, 2015

- [#67](https://github.com/kpdecker/jsdiff/issues/67) - cannot require from npm module in node ([@commenthol](https://api.github.com/users/commenthol))
- Convert to chai since we don’t support IE8 - a96bbad

[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.1...v2.0.2)

## v2.0.1 - August 7th, 2015

- Add release build at proper step - 57542fd

[Commits](https://github.com/kpdecker/jsdiff/compare/v2.0.0...v2.0.1)

## v2.0.0 - August 7th, 2015

- [#66](https://github.com/kpdecker/jsdiff/issues/66) - Add karma and sauce tests ([@kpdecker](https://api.github.com/users/kpdecker))
- [#65](https://github.com/kpdecker/jsdiff/issues/65) - Create component repository for bower ([@kpdecker](https://api.github.com/users/kpdecker))
- [#64](https://github.com/kpdecker/jsdiff/issues/64) - Automatically call removeEmpty for all tokenizer calls ([@kpdecker](https://api.github.com/users/kpdecker))
- [#62](https://github.com/kpdecker/jsdiff/pull/62) - Allow access to structured object representation of patch data ([@bittrance](https://api.github.com/users/bittrance))
- [#61](https://github.com/kpdecker/jsdiff/pull/61) - Use svg instead of png to get better image quality ([@PeterDaveHello](https://api.github.com/users/PeterDaveHello))
- [#29](https://github.com/kpdecker/jsdiff/issues/29) - word tokenizer works only for 7 bit ascii ([@plasmagunman](https://api.github.com/users/plasmagunman))

Compatibility notes:

- `this.removeEmpty` is now called automatically for all instances. If this is not desired, this may be overridden on a per instance basis.
- The library has been refactored to use some ES6 features. The external APIs should remain the same, but bower projects that directly referenced the repository will now have to point to the [components/jsdiff](https://github.com/components/jsdiff) repository.

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.4.0...v2.0.0)

## v1.4.0 - May 6th, 2015

- [#57](https://github.com/kpdecker/jsdiff/issues/57) - createPatch -> applyPatch failed. ([@mog422](https://api.github.com/users/mog422))
- [#56](https://github.com/kpdecker/jsdiff/pull/56) - Two files patch ([@rgeissert](https://api.github.com/users/rgeissert))
- [#14](https://github.com/kpdecker/jsdiff/issues/14) - Flip added and removed order? ([@jakesandlund](https://api.github.com/users/jakesandlund))

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.2...v1.4.0)

## v1.3.2 - March 30th, 2015

- [#53](https://github.com/kpdecker/jsdiff/pull/53) - Updated README.MD with Bower installation instructions ([@ofbriggs](https://api.github.com/users/ofbriggs))
- [#49](https://github.com/kpdecker/jsdiff/issues/49) - Cannot read property 'oldlines' of undefined ([@nwtn](https://api.github.com/users/nwtn))
- [#44](https://github.com/kpdecker/jsdiff/issues/44) - invalid-meta jsdiff is missing "main" entry in bower.json

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.1...v1.3.2)

## v1.3.1 - March 13th, 2015

- [#52](https://github.com/kpdecker/jsdiff/pull/52) - Fix for #51 Wrong result of JsDiff.diffLines ([@felicienfrancois](https://api.github.com/users/felicienfrancois))

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.3.0...v1.3.1)

## v1.3.0 - March 2nd, 2015

- [#47](https://github.com/kpdecker/jsdiff/pull/47) - Adding Diff Trimmed Lines ([@JamesGould123](https://api.github.com/users/JamesGould123))

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.2...v1.3.0)

## v1.2.2 - January 26th, 2015

- [#45](https://github.com/kpdecker/jsdiff/pull/45) - Fix AMD module loading ([@pedrocarrico](https://api.github.com/users/pedrocarrico))
- [#43](https://github.com/kpdecker/jsdiff/pull/43) - added a bower file ([@nbrustein](https://api.github.com/users/nbrustein))

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.1...v1.2.2)

## v1.2.1 - December 26th, 2014

- [#41](https://github.com/kpdecker/jsdiff/pull/41) - change condition of using node export system. ([@ironhee](https://api.github.com/users/ironhee))

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.2.0...v1.2.1)

## v1.2.0 - November 29th, 2014

- [#37](https://github.com/kpdecker/jsdiff/pull/37) - Add support for sentences. ([@vmariano](https://api.github.com/users/vmariano))
- [#28](https://github.com/kpdecker/jsdiff/pull/28) - Implemented diffJson ([@papandreou](https://api.github.com/users/papandreou))
- [#27](https://github.com/kpdecker/jsdiff/issues/27) - Slow to execute over diffs with a large number of changes ([@termi](https://api.github.com/users/termi))
- Allow for optional async diffing - 19385b9
- Fix diffChars implementation - eaa44ed

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.1.0...v1.2.0)

## v1.1.0 - November 25th, 2014

- [#33](https://github.com/kpdecker/jsdiff/pull/33) - AMD and global exports ([@ovcharik](https://api.github.com/users/ovcharik))
- [#32](https://github.com/kpdecker/jsdiff/pull/32) - Add support for component ([@vmariano](https://api.github.com/users/vmariano))
- [#31](https://github.com/kpdecker/jsdiff/pull/31) - Don't rely on Array.prototype.map ([@papandreou](https://api.github.com/users/papandreou))

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.8...v1.1.0)

## v1.0.8 - December 22nd, 2013

- [#24](https://github.com/kpdecker/jsdiff/pull/24) - Handle windows newlines on non windows machines. ([@benogle](https://api.github.com/users/benogle))
- [#23](https://github.com/kpdecker/jsdiff/pull/23) - Prettied up the API formatting a little, and added basic node and web examples ([@airportyh](https://api.github.com/users/airportyh))

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.7...v1.0.8)

## v1.0.7 - September 11th, 2013

- [#22](https://github.com/kpdecker/jsdiff/pull/22) - Added variant of WordDiff that doesn't ignore whitespace differences ([@papandreou](https://api.github.com/users/papandreou)

- Add 0.10 to travis tests - 243a526

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.6...v1.0.7)

## v1.0.6 - August 30th, 2013

- [#19](https://github.com/kpdecker/jsdiff/pull/19) - Explicitly define contents of npm package ([@sindresorhus](https://api.github.com/users/sindresorhus)

[Commits](https://github.com/kpdecker/jsdiff/compare/v1.0.5...v1.0.6)


================================================
FILE: rollup.config.mjs
================================================
import pkg from './package.json' with { type: 'json' };

export default [
  // browser-friendly UMD build
  {
    input: 'libesm/index.js',
    output: [
      {
        name: 'Diff',
        format: 'umd',
        file: "./dist/diff.js"
      }
    ]
  }
];


================================================
FILE: runtime.js
================================================
require('@babel/register')({
  ignore: ['libcjs', 'libesm', 'node_modules']
});


================================================
FILE: src/convert/dmp.ts
================================================
import type {ChangeObject} from '../types.js';

type DmpOperation = 1 | 0 | -1;

/**
 * converts a list of change objects to the format returned by Google's [diff-match-patch](https://github.com/google/diff-match-patch) library
 */
export function convertChangesToDMP<ValueT>(changes: ChangeObject<ValueT>[]): [DmpOperation, ValueT][] {
  const ret: [DmpOperation, ValueT][] = [];
  let change,
      operation: DmpOperation;
  for (let i = 0; i < changes.length; i++) {
    change = changes[i];
    if (change.added) {
      operation = 1;
    } else if (change.removed) {
      operation = -1;
    } else {
      operation = 0;
    }

    ret.push([operation, change.value]);
  }
  return ret;
}


================================================
FILE: src/convert/xml.ts
================================================
import type {ChangeObject} from '../types.js';

/**
 * converts a list of change objects to a serialized XML format
 */
export function convertChangesToXML(changes: ChangeObject<string>[]): string {
  const ret = [];
  for (let i = 0; i < changes.length; i++) {
    const change = changes[i];
    if (change.added) {
      ret.push('<ins>');
    } else if (change.removed) {
      ret.push('<del>');
    }

    ret.push(escapeHTML(change.value));

    if (change.added) {
      ret.push('</ins>');
    } else if (change.removed) {
      ret.push('</del>');
    }
  }
  return ret.join('');
}

function escapeHTML(s: string): string {
  let n = s;
  n = n.replace(/&/g, '&amp;');
  n = n.replace(/</g, '&lt;');
  n = n.replace(/>/g, '&gt;');
  n = n.replace(/"/g, '&quot;');

  return n;
}


================================================
FILE: src/diff/array.ts
================================================
import Diff from './base.js';
import type {ChangeObject, DiffArraysOptionsNonabortable, CallbackOptionNonabortable, DiffArraysOptionsAbortable, DiffCallbackNonabortable, CallbackOptionAbortable} from '../types.js';

class ArrayDiff<T> extends Diff<T, Array<T>> {
  tokenize(value: Array<T>) {
    return value.slice();
  }

  join(value: Array<T>) {
    return value;
  }

  removeEmpty(value: Array<T>) {
    return value;
  }
}

export const arrayDiff = new ArrayDiff();

/**
 * diffs two arrays of tokens, comparing each item for strict equality (===).
 * @returns a list of change objects.
 */
export function diffArrays<T>(
  oldArr: T[],
  newArr: T[],
  options: DiffCallbackNonabortable<T[]>
): undefined;
export function diffArrays<T>(
  oldArr: T[],
  newArr: T[],
  options: DiffArraysOptionsAbortable<T> & CallbackOptionAbortable<T[]>
): undefined
export function diffArrays<T>(
  oldArr: T[],
  newArr: T[],
  options: DiffArraysOptionsNonabortable<T> & CallbackOptionNonabortable<T[]>
): undefined
export function diffArrays<T>(
  oldArr: T[],
  newArr: T[],
  options: DiffArraysOptionsAbortable<T>
): ChangeObject<T[]>[] | undefined
export function diffArrays<T>(
  oldArr: T[],
  newArr: T[],
  options?: DiffArraysOptionsNonabortable<T>
): ChangeObject<T[]>[]
export function diffArrays<T>(
  oldArr: T[],
  newArr: T[],
  options?: any
): undefined | ChangeObject<T[]>[] {
  return arrayDiff.diff(oldArr, newArr, options);
}


================================================
FILE: src/diff/base.ts
================================================
import type {ChangeObject, AllDiffOptions, AbortableDiffOptions, DiffCallbackNonabortable, CallbackOptionAbortable, CallbackOptionNonabortable, DiffCallbackAbortable, TimeoutOption, MaxEditLengthOption} from '../types.js';

/**
 * Like a ChangeObject, but with no value and an extra `previousComponent` property.
 * A linked list of these (linked via `.previousComponent`) is used internally in the code below to
 * keep track of the state of the diffing algorithm, but gets converted to an array of
 * ChangeObjects before being returned to the caller.
 */
interface DraftChangeObject {
    added: boolean;
    removed: boolean;
    count: number;
    previousComponent?: DraftChangeObject;

    // Only added in buildValues:
    value?: any;
}

interface Path {
  oldPos: number;
  lastComponent: DraftChangeObject | undefined
}

export default class Diff<
  TokenT,
  ValueT extends Iterable<TokenT> = Iterable<TokenT>,
  InputValueT = ValueT
> {
  diff(
    oldStr: InputValueT,
    newStr: InputValueT,
    options: DiffCallbackNonabortable<ValueT>
  ): undefined;
  diff(
    oldStr: InputValueT,
    newStr: InputValueT,
    options: AllDiffOptions & AbortableDiffOptions & CallbackOptionAbortable<ValueT>
  ): undefined
  diff(
    oldStr: InputValueT,
    newStr: InputValueT,
    options: AllDiffOptions & CallbackOptionNonabortable<ValueT>
  ): undefined
  diff(
    oldStr: InputValueT,
    newStr: InputValueT,
    options: AllDiffOptions & AbortableDiffOptions
  ): ChangeObject<ValueT>[] | undefined
  diff(
    oldStr: InputValueT,
    newStr: InputValueT,
    options?: AllDiffOptions
  ): ChangeObject<ValueT>[]
  diff(
    oldStr: InputValueT,
    newStr: InputValueT,
    // Type below is not accurate/complete - see above for full possibilities - but it compiles
    options: DiffCallbackNonabortable<ValueT> | AllDiffOptions & Partial<CallbackOptionNonabortable<ValueT>> = {}
  ): ChangeObject<ValueT>[] | undefined {
    let callback: DiffCallbackAbortable<ValueT> | DiffCallbackNonabortable<ValueT> | undefined;
    if (typeof options === 'function') {
      callback = options;
      options = {};
    } else if ('callback' in options) {
      callback = options.callback;
    }
    // Allow subclasses to massage the input prior to running
    const oldString = this.castInput(oldStr, options);
    const newString = this.castInput(newStr, options);

    const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
    const newTokens = this.removeEmpty(this.tokenize(newString, options));

    return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
  }

  private diffWithOptionsObj(
    oldTokens: TokenT[],
    newTokens: TokenT[],
    options: AllDiffOptions & Partial<TimeoutOption> & Partial<MaxEditLengthOption>,
    callback: DiffCallbackAbortable<ValueT> | DiffCallbackNonabortable<ValueT> | undefined
  ): ChangeObject<ValueT>[] | undefined {
    const done = (value: ChangeObject<ValueT>[]) => {
      value = this.postProcess(value, options);
      if (callback) {
        setTimeout(function() { callback(value); }, 0);
        return undefined;
      } else {
        return value;
      }
    };

    const newLen = newTokens.length, oldLen = oldTokens.length;
    let editLength = 1;
    let maxEditLength = newLen + oldLen;
    if(options.maxEditLength != null) {
      maxEditLength = Math.min(maxEditLength, options.maxEditLength);
    }
    const maxExecutionTime = options.timeout ?? Infinity;
    const abortAfterTimestamp = Date.now() + maxExecutionTime;

    const bestPath: Path[] = [{ oldPos: -1, lastComponent: undefined }];

    // Seed editLength = 0, i.e. the content starts with the same values
    let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
    if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
      // Identity per the equality and tokenizer
      return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
    }

    // Once we hit the right edge of the edit graph on some diagonal k, we can
    // definitely reach the end of the edit graph in no more than k edits, so
    // there's no point in considering any moves to diagonal k+1 any more (from
    // which we're guaranteed to need at least k+1 more edits).
    // Similarly, once we've reached the bottom of the edit graph, there's no
    // point considering moves to lower diagonals.
    // We record this fact by setting minDiagonalToConsider and
    // maxDiagonalToConsider to some finite value once we've hit the edge of
    // the edit graph.
    // This optimization is not faithful to the original algorithm presented in
    // Myers's paper, which instead pointlessly extends D-paths off the end of
    // the edit graph - see page 7 of Myers's paper which notes this point
    // explicitly and illustrates it with a diagram. This has major performance
    // implications for some common scenarios. For instance, to compute a diff
    // where the new text simply appends d characters on the end of the
    // original text of length n, the true Myers algorithm will take O(n+d^2)
    // time while this optimization needs only O(n+d) time.
    let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;

    // Main worker method. checks all permutations of a given edit length for acceptance.
    const execEditLength = () => {
      for (
        let diagonalPath = Math.max(minDiagonalToConsider, -editLength);
        diagonalPath <= Math.min(maxDiagonalToConsider, editLength);
        diagonalPath += 2
      ) {
        let basePath;
        const removePath = bestPath[diagonalPath - 1],
              addPath = bestPath[diagonalPath + 1];
        if (removePath) {
          // No one else is going to attempt to use this value, clear it
          // @ts-expect-error - perf optimisation. This type-violating value will never be read.
          bestPath[diagonalPath - 1] = undefined;
        }

        let canAdd = false;
        if (addPath) {
          // what newPos will be after we do an insertion:
          const addPathNewPos = addPath.oldPos - diagonalPath;
          canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
        }

        const canRemove = removePath && removePath.oldPos + 1 < oldLen;
        if (!canAdd && !canRemove) {
          // If this path is a terminal then prune
          // @ts-expect-error - perf optimisation. This type-violating value will never be read.
          bestPath[diagonalPath] = undefined;
          continue;
        }

        // Select the diagonal that we want to branch from. We select the prior
        // path whose position in the old string is the farthest from the origin
        // and does not pass the bounds of the diff graph
        if (!canRemove || (canAdd && removePath.oldPos < addPath.oldPos)) {
          basePath = this.addToPath(addPath, true, false, 0, options);
        } else {
          basePath = this.addToPath(removePath, false, true, 1, options);
        }

        newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);

        if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
          // If we have hit the end of both strings, then we are done
          return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
        } else {
          bestPath[diagonalPath] = basePath;
          if (basePath.oldPos + 1 >= oldLen) {
            maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
          }
          if (newPos + 1 >= newLen) {
            minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
          }
        }
      }

      editLength++;
    };

    // Performs the length of edit iteration. Is a bit fugly as this has to support the
    // sync and async mode which is never fun. Loops over execEditLength until a value
    // is produced, or until the edit length exceeds options.maxEditLength (if given),
    // in which case it will return undefined.
    if (callback) {
      (function exec() {
        setTimeout(function() {
          if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
            return (callback as DiffCallbackAbortable<ValueT>)(undefined);
          }

          if (!execEditLength()) {
            exec();
          }
        }, 0);
      }());
    } else {
      while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
        const ret = execEditLength();
        if (ret) {
          return ret as ChangeObject<ValueT>[];
        }
      }
    }
  }

  private addToPath(
    path: Path,
    added: boolean,
    removed: boolean,
    oldPosInc: number,
    options: AllDiffOptions
  ): Path {
    const last = path.lastComponent;
    if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
      return {
        oldPos: path.oldPos + oldPosInc,
        lastComponent: {count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent }
      };
    } else {
      return {
        oldPos: path.oldPos + oldPosInc,
        lastComponent: {count: 1, added: added, removed: removed, previousComponent: last }
      };
    }
  }

  private extractCommon(
    basePath: Path,
    newTokens: TokenT[],
    oldTokens: TokenT[],
    diagonalPath: number,
    options: AllDiffOptions
  ): number {
    const newLen = newTokens.length,
          oldLen = oldTokens.length;
    let oldPos = basePath.oldPos,
        newPos = oldPos - diagonalPath,
        commonCount = 0;

    while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
      newPos++;
      oldPos++;
      commonCount++;
      if (options.oneChangePerToken) {
        basePath.lastComponent = {count: 1, previousComponent: basePath.lastComponent, added: false, removed: false};
      }
    }

    if (commonCount && !options.oneChangePerToken) {
      basePath.lastComponent = {count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false};
    }

    basePath.oldPos = oldPos;
    return newPos;
  }

  equals(left: TokenT, right: TokenT, options: AllDiffOptions): boolean {
    if (options.comparator) {
      return options.comparator(left, right);
    } else {
      return left === right
        || (!!options.ignoreCase && (left as string).toLowerCase() === (right as string).toLowerCase());
    }
  }

  removeEmpty(array: TokenT[]): TokenT[] {
    const ret: TokenT[] = [];
    for (let i = 0; i < array.length; i++) {
      if (array[i]) {
        ret.push(array[i]);
      }
    }
    return ret;
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  castInput(value: InputValueT, options: AllDiffOptions): ValueT {
    return value as unknown as ValueT;
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  tokenize(value: ValueT, options: AllDiffOptions): TokenT[] {
    return Array.from(value);
  }

  join(chars: TokenT[]): ValueT {
    // Assumes ValueT is string, which is the case for most subclasses.
    // When it's false, e.g. in diffArrays, this method needs to be overridden (e.g. with a no-op)
    // Yes, the casts are verbose and ugly, because this pattern - of having the base class SORT OF
    // assume tokens and values are strings, but not completely - is weird and janky.
    return (chars as string[]).join('') as unknown as ValueT;
  }

  postProcess(
    changeObjects: ChangeObject<ValueT>[],
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    options: AllDiffOptions
  ): ChangeObject<ValueT>[] {
    return changeObjects;
  }

  get useLongestToken(): boolean {
    return false;
  }

  private buildValues(
    lastComponent: DraftChangeObject | undefined,
    newTokens: TokenT[],
    oldTokens: TokenT[]
  ): ChangeObject<ValueT>[] {
    // First we convert our linked list of components in reverse order to an
    // array in the right order:
    const components: DraftChangeObject[] = [];
    let nextComponent;
    while (lastComponent) {
      components.push(lastComponent);
      nextComponent = lastComponent.previousComponent;
      delete lastComponent.previousComponent;
      lastComponent = nextComponent;
    }
    components.reverse();

    const componentLen = components.length;
    let componentPos = 0,
        newPos = 0,
        oldPos = 0;

    for (; componentPos < componentLen; componentPos++) {
      const component = components[componentPos];
      if (!component.removed) {
        if (!component.added && this.useLongestToken) {
          let value = newTokens.slice(newPos, newPos + component.count);
          value = value.map(function(value, i) {
            const oldValue = oldTokens[oldPos + i];
            return (oldValue as string).length > (value as string).length ? oldValue : value;
          });

          component.value = this.join(value);
        } else {
          component.value = this.join(newTokens.slice(newPos, newPos + component.count));
        }
        newPos += component.count;

        // Common case
        if (!component.added) {
          oldPos += component.count;
        }
      } else {
        component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
        oldPos += component.count;
      }
    }

    return components as ChangeObject<ValueT>[];
  }
}



================================================
FILE: src/diff/character.ts
================================================
import Diff from './base.js';
import type { ChangeObject, CallbackOptionAbortable, CallbackOptionNonabortable, DiffCallbackNonabortable, DiffCharsOptionsAbortable, DiffCharsOptionsNonabortable} from '../types.js';

class CharacterDiff extends Diff<string, string> {}

export const characterDiff = new CharacterDiff();

/**
 * diffs two blocks of text, treating each character as a token.
 *
 * ("Characters" here means Unicode code points - the elements you get when you loop over a string with a `for ... of ...` loop.)
 *
 * @returns a list of change objects.
 */
export function diffChars(
  oldStr: string,
  newStr: string,
  options: DiffCallbackNonabortable<string>
): undefined;
export function diffChars(
  oldStr: string,
  newStr: string,
  options: DiffCharsOptionsAbortable & CallbackOptionAbortable<string>
): undefined
export function diffChars(
  oldStr: string,
  newStr: string,
  options: DiffCharsOptionsNonabortable & CallbackOptionNonabortable<string>
): undefined
export function diffChars(
  oldStr: string,
  newStr: string,
  options: DiffCharsOptionsAbortable
): ChangeObject<string>[] | undefined
export function diffChars(
  oldStr: string,
  newStr: string,
  options?: DiffCharsOptionsNonabortable
): ChangeObject<string>[]
export function diffChars(
  oldStr: string,
  newStr: string,
  options?: any
): undefined | ChangeObject<string>[] {
  return characterDiff.diff(oldStr, newStr, options);
}


================================================
FILE: src/diff/css.ts
================================================
import Diff from './base.js';
import type { ChangeObject, CallbackOptionAbortable, CallbackOptionNonabortable, DiffCallbackNonabortable, DiffCssOptionsAbortable, DiffCssOptionsNonabortable} from '../types.js';

class CssDiff extends Diff<string, string> {
  tokenize(value: string) {
    return value.split(/([{}:;,]|\s+)/);
  }
}

export const cssDiff = new CssDiff();

/**
 * diffs two blocks of text, comparing CSS tokens.
 *
 * @returns a list of change objects.
 */
export function diffCss(
  oldStr: string,
  newStr: string,
  options: DiffCallbackNonabortable<string>
): undefined;
export function diffCss(
  oldStr: string,
  newStr: string,
  options: DiffCssOptionsAbortable & CallbackOptionAbortable<string>
): undefined
export function diffCss(
  oldStr: string,
  newStr: string,
  options: DiffCssOptionsNonabortable & CallbackOptionNonabortable<string>
): undefined
export function diffCss(
  oldStr: string,
  newStr: string,
  options: DiffCssOptionsAbortable
): ChangeObject<string>[] | undefined
export function diffCss(
  oldStr: string,
  newStr: string,
  options?: DiffCssOptionsNonabortable
): ChangeObject<string>[]
export function diffCss(oldStr: string, newStr: string, options?: any): undefined | ChangeObject<string>[] {
  return cssDiff.diff(oldStr, newStr, options);
}


================================================
FILE: src/diff/json.ts
================================================
import Diff from './base.js';
import type { ChangeObject, CallbackOptionAbortable, CallbackOptionNonabortable, DiffCallbackNonabortable, DiffJsonOptionsAbortable, DiffJsonOptionsNonabortable} from '../types.js';
import { tokenize } from './line.js';

class JsonDiff extends Diff<string, string, string | object> {
  get useLongestToken() {
    // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
    // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
    return true;
  }

  tokenize = tokenize;

  castInput(value: string | object, options: DiffJsonOptionsNonabortable | DiffJsonOptionsAbortable) {
    const {undefinedReplacement, stringifyReplacer = (k, v) => typeof v === 'undefined' ? undefinedReplacement : v} = options;

    return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), null, '  ');
  }

  equals(left: string, right: string, options: DiffJsonOptionsNonabortable | DiffJsonOptionsAbortable) {
    return super.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'), options);
  }
}

export const jsonDiff = new JsonDiff();

/**
 * diffs two JSON-serializable objects by first serializing them to prettily-formatted JSON and then treating each line of the JSON as a token.
 * Object properties are ordered alphabetically in the serialized JSON, so the order of properties in the objects being compared doesn't affect the result.
 *
 * @returns a list of change objects.
 */
export function diffJson(
  oldStr: string | object,
  newStr: string | object,
  options: DiffCallbackNonabortable<string>
): undefined;
export function diffJson(
  oldStr: string | object,
  newStr: string | object,
  options: DiffJsonOptionsAbortable & CallbackOptionAbortable<string>
): undefined
export function diffJson(
  oldStr: string | object,
  newStr: string | object,
  options: DiffJsonOptionsNonabortable & CallbackOptionNonabortable<string>
): undefined
export function diffJson(
  oldStr: string | object,
  newStr: string | object,
  options: DiffJsonOptionsAbortable
): ChangeObject<string>[] | undefined
export function diffJson(
  oldStr: string | object,
  newStr: string | object,
  options?: DiffJsonOptionsNonabortable
): ChangeObject<string>[]
export function diffJson(oldStr: string | object, newStr: string | object, options?: any): undefined | ChangeObject<string>[] {
  return jsonDiff.diff(oldStr, newStr, options);
}


// This function handles the presence of circular references by bailing out when encountering an
// object that is already on the "stack" of items being processed. Accepts an optional replacer
export function canonicalize(
  obj: any,
  stack: Array<any> | null, replacementStack: Array<any> | null,
  replacer: (k: string, v: any) => any,
  key?: string
) {
  stack = stack || [];
  replacementStack = replacementStack || [];

  if (replacer) {
    obj = replacer(key === undefined ? '' : key, obj);
  }

  let i;

  for (i = 0; i < stack.length; i += 1) {
    if (stack[i] === obj) {
      return replacementStack[i];
    }
  }

  let canonicalizedObj: any;

  if ('[object Array]' === Object.prototype.toString.call(obj)) {
    stack.push(obj);
    canonicalizedObj = new Array(obj.length);
    replacementStack.push(canonicalizedObj);
    for (i = 0; i < obj.length; i += 1) {
      canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, String(i));
    }
    stack.pop();
    replacementStack.pop();
    return canonicalizedObj;
  }

  if (obj && obj.toJSON) {
    obj = obj.toJSON();
  }

  if (typeof obj === 'object' && obj !== null) {
    stack.push(obj);
    canonicalizedObj = {};
    replacementStack.push(canonicalizedObj);
    const sortedKeys = [];
    let key;
    for (key in obj) {
      /* istanbul ignore else */
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        sortedKeys.push(key);
      }
    }
    sortedKeys.sort();
    for (i = 0; i < sortedKeys.length; i += 1) {
      key = sortedKeys[i];
      canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack, replacer, key);
    }
    stack.pop();
    replacementStack.pop();
  } else {
    canonicalizedObj = obj;
  }
  return canonicalizedObj;
}


================================================
FILE: src/diff/line.ts
================================================
import Diff from './base.js';
import type { ChangeObject, CallbackOptionAbortable, CallbackOptionNonabortable, DiffCallbackNonabortable, DiffLinesOptionsAbortable, DiffLinesOptionsNonabortable} from '../types.js';
import {generateOptions} from '../util/params.js';

class LineDiff extends Diff<string, string> {
  tokenize = tokenize;

  equals(left: string, right: string, options: DiffLinesOptionsAbortable | DiffLinesOptionsNonabortable) {
    // If we're ignoring whitespace, we need to normalise lines by stripping
    // whitespace before checking equality. (This has an annoying interaction
    // with newlineIsToken that requires special handling: if newlines get their
    // own token, then we DON'T want to trim the *newline* tokens down to empty
    // strings, since this would cause us to treat whitespace-only line content
    // as equal to a separator between lines, which would be weird and
    // inconsistent with the documented behavior of the options.)
    if (options.ignoreWhitespace) {
      if (!options.newlineIsToken || !left.includes('\n')) {
        left = left.trim();
      }
      if (!options.newlineIsToken || !right.includes('\n')) {
        right = right.trim();
      }
    } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
      if (left.endsWith('\n')) {
        left = left.slice(0, -1);
      }
      if (right.endsWith('\n')) {
        right = right.slice(0, -1);
      }
    }
    return super.equals(left, right, options);
  }
}

export const lineDiff = new LineDiff();

/**
 * diffs two blocks of text, treating each line as a token.
 * @returns a list of change objects.
 */
export function diffLines(
  oldStr: string,
  newStr: string,
  options: DiffCallbackNonabortable<string>
): undefined;
export function diffLines(
  oldStr: string,
  newStr: string,
  options: DiffLinesOptionsAbortable & CallbackOptionAbortable<string>
): undefined
export function diffLines(
  oldStr: string,
  newStr: string,
  options: DiffLinesOptionsNonabortable & CallbackOptionNonabortable<string>
): undefined
export function diffLines(
  oldStr: string,
  newStr: string,
  options: DiffLinesOptionsAbortable
): ChangeObject<string>[] | undefined
export function diffLines(
  oldStr: string,
  newStr: string,
  options?: DiffLinesOptionsNonabortable
): ChangeObject<string>[]
export function diffLines(oldStr: string, newStr: string, options?: any): undefined | ChangeObject<string>[] {
  return lineDiff.diff(oldStr, newStr, options);
}

// Kept for backwards compatibility. This is a rather arbitrary wrapper method
// that just calls `diffLines` with `ignoreWhitespace: true`. It's confusing to
// have two ways to do exactly the same thing in the API, so we no longer
// document this one (library users should explicitly use `diffLines` with
// `ignoreWhitespace: true` instead) but we keep it around to maintain
// compatibility with code that used old versions.
export function diffTrimmedLines(
  oldStr: string,
  newStr: string,
  options: DiffCallbackNonabortable<string>
): undefined;
export function diffTrimmedLines(
  oldStr: string,
  newStr: string,
  options: DiffLinesOptionsAbortable & CallbackOptionAbortable<string>
): undefined
export function diffTrimmedLines(
  oldStr: string,
  newStr: string,
  options: DiffLinesOptionsNonabortable & CallbackOptionNonabortable<string>
): undefined
export function diffTrimmedLines(
  oldStr: string,
  newStr: string,
  options: DiffLinesOptionsAbortable
): ChangeObject<string>[] | undefined
export function diffTrimmedLines(
  oldStr: string,
  newStr: string,
  options?: DiffLinesOptionsNonabortable
): ChangeObject<string>[]
export function diffTrimmedLines(oldStr: string, newStr: string, options?: any): undefined | ChangeObject<string>[] {
  options = generateOptions(options, {ignoreWhitespace: true});
  return lineDiff.diff(oldStr, newStr, options);
}

// Exported standalone so it can be used from jsonDiff too.
export function tokenize(value: string, options: DiffLinesOptionsAbortable | DiffLinesOptionsNonabortable) {
  if(options.stripTrailingCr) {
    // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior
    value = value.replace(/\r\n/g, '\n');
  }

  const retLines = [],
      linesAndNewlines = value.split(/(\n|\r\n)/);

  // Ignore the final empty token that occurs if the string ends with a new line
  if (!linesAndNewlines[linesAndNewlines.length - 1]) {
    linesAndNewlines.pop();
  }

  // Merge the content and line separators into single tokens
  for (let i = 0; i < linesAndNewlines.length; i++) {
    const line = linesAndNewlines[i];

    if (i % 2 && !options.newlineIsToken) {
      retLines[retLines.length - 1] += line;
    } else {
      retLines.push(line);
    }
  }

  return retLines;
}


================================================
FILE: src/diff/sentence.ts
================================================
import Diff from './base.js';
import type {
  ChangeObject,
  CallbackOptionAbortable,
  CallbackOptionNonabortable,
  DiffCallbackNonabortable,
  DiffSentencesOptionsAbortable,
  DiffSentencesOptionsNonabortable
} from '../types.js';

function isSentenceEndPunct(char: string) {
  return char == '.' || char == '!' || char == '?';
}

class SentenceDiff extends Diff<string, string> {
  tokenize(value: string) {
    // If in future we drop support for environments that don't support lookbehinds, we can replace
    // this entire function with:
    //     return value.split(/(?<=[.!?])(\s+|$)/);
    // but until then, for similar reasons to the trailingWs function in string.ts, we are forced
    // to do this verbosely "by hand" instead of using a regex.
    const result = [];
    let tokenStartI = 0;
    for (let i = 0; i < value.length; i++) {
      if (i == value.length - 1) {
        result.push(value.slice(tokenStartI));
        break;
      }

      if (isSentenceEndPunct(value[i]) && value[i + 1].match(/\s/)) {
        // We've hit a sentence break - i.e. a punctuation mark followed by whitespace.
        // We now want to push TWO tokens to the result:
        // 1. the sentence
        result.push(value.slice(tokenStartI, i + 1));

        // 2. the whitespace
        i = tokenStartI = i + 1;
        while (value[i + 1]?.match(/\s/)) {
          i++;
        }
        result.push(value.slice(tokenStartI, i + 1));

        // Then the next token (a sentence) starts on the character after the whitespace.
        // (It's okay if this is off the end of the string - then the outer loop will terminate
        // here anyway.)
        tokenStartI = i + 1;
      }
    }

    return result;
  }
}

export const sentenceDiff = new SentenceDiff();

/**
 * diffs two blocks of text, treating each sentence, and the whitespace between each pair of sentences, as a token.
 * The characters `.`, `!`, and `?`, when followed by whitespace, are treated as marking the end of a sentence; nothing else besides the end of the string is considered to mark a sentence end.
 *
 * (For more sophisticated detection of sentence breaks, including support for non-English punctuation, consider instead tokenizing with an [`Intl.Segmenter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter) with `granularity: 'sentence'` and passing the result to `diffArrays`.)
 *
 * @returns a list of change objects.
 */
export function diffSentences(
  oldStr: string,
  newStr: string,
  options: DiffCallbackNonabortable<string>
): undefined;
export function diffSentences(
  oldStr: string,
  newStr: string,
  options: DiffSentencesOptionsAbortable & CallbackOptionAbortable<string>
): undefined
export function diffSentences(
  oldStr: string,
  newStr: string,
  options: DiffSentencesOptionsNonabortable & CallbackOptionNonabortable<string>
): undefined
export function diffSentences(
  oldStr: string,
  newStr: string,
  options: DiffSentencesOptionsAbortable
): ChangeObject<string>[] | undefined
export function diffSentences(
  oldStr: string,
  newStr: string,
  options?: DiffSentencesOptionsNonabortable
): ChangeObject<string>[]
export function diffSentences(oldStr: string, newStr: string, options?: any): undefined | ChangeObject<string>[] {
  return sentenceDiff.diff(oldStr, newStr, options);
}


================================================
FILE: src/diff/word.ts
================================================
import Diff from './base.js';
import type { ChangeObject, CallbackOptionAbortable, CallbackOptionNonabortable, DiffCallbackNonabortable, DiffWordsOptionsAbortable, DiffWordsOptionsNonabortable} from '../types.js';
import { longestCommonPrefix, longestCommonSuffix, replacePrefix, replaceSuffix, removePrefix, removeSuffix, maximumOverlap, leadingWs, trailingWs, leadingAndTrailingWs, segment } from '../util/string.js';

// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode
//
// Chars/ranges counted as "word" characters by this regex are as follows:
//
// + U+00AD  Soft hyphen
// + 00C0–00FF (letters with diacritics from the Latin-1 Supplement), except:
//   - U+00D7  × Multiplication sign
//   - U+00F7  ÷ Division sign
// + Latin Extended-A, 0100–017F
// + Latin Extended-B, 0180–024F
// + IPA Extensions, 0250–02AF
// + Spacing Modifier Letters, 02B0–02FF, except:
//   - U+02C7  ˇ &#711;  Caron
//   - U+02D8  ˘ &#728;  Breve
//   - U+02D9  ˙ &#729;  Dot Above
//   - U+02DA  ˚ &#730;  Ring Above
//   - U+02DB  ˛ &#731;  Ogonek
//   - U+02DC  ˜ &#732;  Small Tilde
//   - U+02DD  ˝ &#733;  Double Acute Accent
// + Latin Extended Additional, 1E00–1EFF
const extendedWordChars = 'a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}';

// Each token is one of the following:
// - A punctuation mark plus the surrounding whitespace
// - A word plus the surrounding whitespace
// - Pure whitespace (but only in the special case where the entire text
//   is just whitespace)
//
// We have to include surrounding whitespace in the tokens because the two
// alternative approaches produce horribly broken results:
// * If we just discard the whitespace, we can't fully reproduce the original
//   text from the sequence of tokens and any attempt to render the diff will
//   get the whitespace wrong.
// * If we have separate tokens for whitespace, then in a typical text every
//   second token will be a single space character. But this often results in
//   the optimal diff between two texts being a perverse one that preserves
//   the spaces between words but deletes and reinserts actual common words.
//   See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640
//   for an example.
//
// Keeping the surrounding whitespace of course has implications for .equals
// and .join, not just .tokenize.

// This regex does NOT fully implement the tokenization rules described above.
// Instead, it gives runs of whitespace their own "token". The tokenize method
// then handles stitching whitespace tokens onto adjacent word or punctuation
// tokens.
const tokenizeIncludingWhitespace = new RegExp(`[${extendedWordChars}]+|\\s+|[^${extendedWordChars}]`, 'ug');


class WordDiff extends Diff<string, string> {
  equals(left: string, right: string, options: DiffWordsOptionsAbortable | DiffWordsOptionsNonabortable) {
    if (options.ignoreCase) {
      left = left.toLowerCase();
      right = right.toLowerCase();
    }

    return left.trim() === right.trim();
  }

  tokenize(value: string, options: DiffWordsOptionsAbortable | DiffWordsOptionsNonabortable = {}) {
    let parts;
    if (options.intlSegmenter) {
      const segmenter: Intl.Segmenter = options.intlSegmenter;
      if (segmenter.resolvedOptions().granularity != 'word') {
        throw new Error('The segmenter passed must have a granularity of "word"');
      }
      // We want `parts` to be an array whose elements alternate between being
      // pure whitespace and being pure non-whitespace. This is ALMOST what the
      // segments returned by a word-based Intl.Segmenter already look like,
      // but not quite - see explanation in the docs of our custom segment()
      // function.
      parts = segment(value, segmenter);
    } else {
      parts = value.match(tokenizeIncludingWhitespace) || [];
    }
    const tokens: string[] = [];
    let prevPart: string | null = null;
    parts.forEach(part => {
      if ((/\s/).test(part)) {
        if (prevPart == null) {
          tokens.push(part);
        } else {
          tokens.push(tokens.pop() + part);
        }
      } else if (prevPart != null && (/\s/).test(prevPart)) {
        if (tokens[tokens.length - 1] == prevPart) {
          tokens.push(tokens.pop() + part);
        } else {
          tokens.push(prevPart + part);
        }
      } else {
        tokens.push(part);
      }

      prevPart = part;
    });
    return tokens;
  }

  join(tokens: string[]) {
    // Tokens being joined here will always have appeared consecutively in the
    // same text, so we can simply strip off the leading whitespace from all the
    // tokens except the first (and except any whitespace-only tokens - but such
    // a token will always be the first and only token anyway) and then join them
    // and the whitespace around words and punctuation will end up correct.
    return tokens.map((token, i) => {
      if (i == 0) {
        return token;
      } else {
        return token.replace((/^\s+/), '');
      }
    }).join('');
  }

  postProcess(changes: ChangeObject<string>[], options: any) {
    if (!changes || options.oneChangePerToken) {
      return changes;
    }

    let lastKeep: ChangeObject<string> | null = null;
    // Change objects representing any insertion or deletion since the last
    // "keep" change object. There can be at most one of each.
    let insertion: ChangeObject<string> | null = null;
    let deletion: ChangeObject<string> | null = null;
    changes.forEach(change => {
      if (change.added) {
        insertion = change;
      } else if (change.removed) {
        deletion = change;
      } else {
        if (insertion || deletion) { // May be false at start of text
          dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change, options.intlSegmenter);
        }
        lastKeep = change;
        insertion = null;
        deletion = null;
      }
    });
    if (insertion || deletion) {
      dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null, options.intlSegmenter);
    }
    return changes;
  }
}

export const wordDiff = new WordDiff();

/**
 * diffs two blocks of text, treating each word and each punctuation mark as a token.
 * Whitespace is ignored when computing the diff (but preserved as far as possible in the final change objects).
 *
 * @returns a list of change objects.
 */
export function diffWords(
  oldStr: string,
  newStr: string,
  options: DiffCallbackNonabortable<string>
): undefined;
export function diffWords(
  oldStr: string,
  newStr: string,
  options: DiffWordsOptionsAbortable & CallbackOptionAbortable<string>
): undefined
export function diffWords(
  oldStr: string,
  newStr: string,
  options: DiffWordsOptionsNonabortable & CallbackOptionNonabortable<string>
): undefined
export function diffWords(
  oldStr: string,
  newStr: string,
  options: DiffWordsOptionsAbortable
): ChangeObject<string>[] | undefined
export function diffWords(
  oldStr: string,
  newStr: string,
  options?: DiffWordsOptionsNonabortable
): ChangeObject<string>[]
export function diffWords(oldStr: string, newStr: string, options?: any): undefined | ChangeObject<string>[] {
  // This option has never been documented and never will be (it's clearer to
  // just call `diffWordsWithSpace` directly if you need that behavior), but
  // has existed in jsdiff for a long time, so we retain support for it here
  // for the sake of backwards compatibility.
  if (options?.ignoreWhitespace != null && !options.ignoreWhitespace) {
    return diffWordsWithSpace(oldStr, newStr, options);
  }

  return wordDiff.diff(oldStr, newStr, options);
}

function dedupeWhitespaceInChangeObjects(
  startKeep: ChangeObject<string> | null,
  deletion: ChangeObject<string> | null,
  insertion: ChangeObject<string> | null,
  endKeep: ChangeObject<string> | null,
  segmenter?: Intl.Segmenter
) {
  // Before returning, we tidy up the leading and trailing whitespace of the
  // change objects to eliminate cases where trailing whitespace in one object
  // is repeated as leading whitespace in the next.
  // Below are examples of the outcomes we want here to explain the code.
  // I=insert, K=keep, D=delete
  // 1. diffing 'foo bar baz' vs 'foo baz'
  //    Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'
  //    After cleanup, we want:   K:'foo ' D:'bar ' K:'baz'
  //
  // 2. Diffing 'foo bar baz' vs 'foo qux baz'
  //    Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz'
  //    After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz'
  //
  // 3. Diffing 'foo\nbar baz' vs 'foo baz'
  //    Prior to cleanup, we have K:'foo ' D:'\nbar ' K:' baz'
  //    After cleanup, we want K'foo' D:'\nbar' K:' baz'
  //
  // 4. Diffing 'foo baz' vs 'foo\nbar baz'
  //    Prior to cleanup, we have K:'foo\n' I:'\nbar ' K:' baz'
  //    After cleanup, we ideally want K'foo' I:'\nbar' K:' baz'
  //    but don't actually manage this currently (the pre-cleanup change
  //    objects don't contain enough information to make it possible).
  //
  // 5. Diffing 'foo   bar baz' vs 'foo  baz'
  //    Prior to cleanup, we have K:'foo  ' D:'   bar ' K:'  baz'
  //    After cleanup, we want K:'foo  ' D:' bar ' K:'baz'
  //
  // Our handling is unavoidably imperfect in the case where there's a single
  // indel between keeps and the whitespace has changed. For instance, consider
  // diffing 'foo\tbar\nbaz' vs 'foo baz'. Unless we create an extra change
  // object to represent the insertion of the space character (which isn't even
  // a token), we have no way to avoid losing information about the texts'
  // original whitespace in the result we return. Still, we do our best to
  // output something that will look sensible if we e.g. print it with
  // insertions in green and deletions in red.

  // Between two "keep" change objects (or before the first or after the last
  // change object), we can have either:
  // * A "delete" followed by an "insert"
  // * Just an "insert"
  // * Just a "delete"
  // We handle the three cases separately.
  if (deletion && insertion) {
    const [oldWsPrefix, oldWsSuffix] = leadingAndTrailingWs(deletion.value, segmenter);
    const [newWsPrefix, newWsSuffix] = leadingAndTrailingWs(insertion.value, segmenter);

    if (startKeep) {
      const commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix);
      startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix);
      deletion.value = removePrefix(deletion.value, commonWsPrefix);
      insertion.value = removePrefix(insertion.value, commonWsPrefix);
    }
    if (endKeep) {
      const commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix);
      endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix);
      deletion.value = removeSuffix(deletion.value, commonWsSuffix);
      insertion.value = removeSuffix(insertion.value, commonWsSuffix);
    }
  } else if (insertion) {
    // The whitespaces all reflect what was in the new text rather than
    // the old, so we essentially have no information about whitespace
    // insertion or deletion. We just want to dedupe the whitespace.
    // We do that by having each change object keep its trailing
    // whitespace and deleting duplicate leading whitespace where
    // present.
    if (startKeep) {
      const ws = leadingWs(insertion.value, segmenter);
      insertion.value = insertion.value.substring(ws.length);
    }
    if (endKeep) {
      const ws = leadingWs(endKeep.value, segmenter);
      endKeep.value = endKeep.value.substring(ws.length);
    }
  // otherwise we've got a deletion and no insertion
  } else if (startKeep && endKeep) {
    const newWsFull = leadingWs(endKeep.value, segmenter),
        [delWsStart, delWsEnd] = leadingAndTrailingWs(deletion!.value, segmenter);

    // Any whitespace that comes straight after startKeep in both the old and
    // new texts, assign to startKeep and remove from the deletion.
    const newWsStart = longestCommonPrefix(newWsFull, delWsStart);
    deletion!.value = removePrefix(deletion!.value, newWsStart);

    // Any whitespace that comes straight before endKeep in both the old and
    // new texts, and hasn't already been assigned to startKeep, assign to
    // endKeep and remove from the deletion.
    const newWsEnd = longestCommonSuffix(
      removePrefix(newWsFull, newWsStart),
      delWsEnd
    );
    deletion!.value = removeSuffix(deletion!.value, newWsEnd);
    endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd);

    // If there's any whitespace from the new text that HASN'T already been
    // assigned, assign it to the start:
    startKeep.value = replaceSuffix(
      startKeep.value,
      newWsFull,
      newWsFull.slice(0, newWsFull.length - newWsEnd.length)
    );
  } else if (endKeep) {
    // We are at the start of the text. Preserve all the whitespace on
    // endKeep, and just remove whitespace from the end of deletion to the
    // extent that it overlaps with the start of endKeep.
    const endKeepWsPrefix = leadingWs(endKeep.value, segmenter);
    const deletionWsSuffix = trailingWs(deletion!.value, segmenter);
    const overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);
    deletion!.value = removeSuffix(deletion!.value, overlap);
  } else if (startKeep) {
    // We are at the END of the text. Preserve all the whitespace on
    // startKeep, and just remove whitespace from the start of deletion to
    // the extent that it overlaps with the end of startKeep.
    const startKeepWsSuffix = trailingWs(startKeep.value, segmenter);
    const deletionWsPrefix = leadingWs(deletion!.value, segmenter);
    const overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix);
    deletion!.value = removePrefix(deletion!.value, overlap);
  }
}


class WordsWithSpaceDiff extends Diff<string, string> {
  tokenize(value: string) {
    // Slightly different to the tokenizeIncludingWhitespace regex used above in
    // that this one treats each individual newline as a distinct token, rather
    // than merging them into other surrounding whitespace. This was requested
    // in https://github.com/kpdecker/jsdiff/issues/180 &
    //    https://github.com/kpdecker/jsdiff/issues/211
    const regex = new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`, 'ug');
    return value.match(regex) || [];
  }
}

export const wordsWithSpaceDiff = new WordsWithSpaceDiff();

/**
 * diffs two blocks of text, treating each word, punctuation mark, newline, or run of (non-newline) whitespace as a token.
 * @returns a list of change objects
 */
export function diffWordsWithSpace(
  oldStr: string,
  newStr: string,
  options: DiffCallbackNonabortable<string>
): undefined;
export function diffWordsWithSpace(
  oldStr: string,
  newStr: string,
  options: DiffWordsOptionsAbortable & CallbackOptionAbortable<string>
): undefined
export function diffWordsWithSpace(
  oldStr: string,
  newStr: string,
  options: DiffWordsOptionsNonabortable & CallbackOptionNonabortable<string>
): undefined
export function diffWordsWithSpace(
  oldStr: string,
  newStr: string,
  options: DiffWordsOptionsAbortable
): ChangeObject<string>[] | undefined
export function diffWordsWithSpace(
  oldStr: string,
  newStr: string,
  options?: DiffWordsOptionsNonabortable
): ChangeObject<string>[]
export function diffWordsWithSpace(oldStr: string, newStr: string, options?: any): undefined | ChangeObject<string>[] {
  return wordsWithSpaceDiff.diff(oldStr, newStr, options);
}


================================================
FILE: src/index.ts
================================================
/* See LICENSE file for terms of use */

/*
 * Text diff implementation.
 *
 * This library supports the following APIs:
 * Diff.diffChars: Character by character diff
 * Diff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
 * Diff.diffLines: Line based diff
 *
 * Diff.diffCss: Diff targeted at CSS content
 *
 * These methods are based on the implementation proposed in
 * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
 * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
 */
import Diff from './diff/base.js';
import {diffChars, characterDiff} from './diff/character.js';
import {diffWords, diffWordsWithSpace, wordDiff, wordsWithSpaceDiff} from './diff/word.js';
import {diffLines, diffTrimmedLines, lineDiff} from './diff/line.js';
import {diffSentences, sentenceDiff} from './diff/sentence.js';

import {diffCss, cssDiff} from './diff/css.js';
import {diffJson, canonicalize, jsonDiff} from './diff/json.js';

import {diffArrays, arrayDiff} from './diff/array.js';

import {applyPatch, applyPatches} from './patch/apply.js';
import type {ApplyPatchOptions, ApplyPatchesOptions} from './patch/apply.js';
import {parsePatch} from './patch/parse.js';
import {reversePatch} from './patch/reverse.js';
import {
  structuredPatch,
  createTwoFilesPatch,
  createPatch,
  formatPatch,
  INCLUDE_HEADERS,
  FILE_HEADERS_ONLY,
  OMIT_HEADERS
} from './patch/create.js';
import type {
  StructuredPatchOptionsAbortable,
  StructuredPatchOptionsNonabortable,
  CreatePatchOptionsAbortable,
  CreatePatchOptionsNonabortable,
  HeaderOptions
} from './patch/create.js';

import {convertChangesToDMP} from './convert/dmp.js';
import {convertChangesToXML} from './convert/xml.js';
import type {
  ChangeObject,
  Change,
  ArrayChange,
  DiffArraysOptionsAbortable,
  DiffArraysOptionsNonabortable,
  DiffCharsOptionsAbortable,
  DiffCharsOptionsNonabortable,
  DiffLinesOptionsAbortable,
  DiffLinesOptionsNonabortable,
  DiffWordsOptionsAbortable,
  DiffWordsOptionsNonabortable,
  DiffSentencesOptionsAbortable,
  DiffSentencesOptionsNonabortable,
  DiffJsonOptionsAbortable,
  DiffJsonOptionsNonabortable,
  DiffCssOptionsAbortable,
  DiffCssOptionsNonabortable,
  StructuredPatch,
  StructuredPatchHunk
} from './types.js';

export {
  Diff,

  diffChars,
  characterDiff,
  diffWords,
  wordDiff,
  diffWordsWithSpace,
  wordsWithSpaceDiff,
  diffLines,
  lineDiff,
  diffTrimmedLines,
  diffSentences,
  sentenceDiff,
  diffCss,
  cssDiff,
  diffJson,
  jsonDiff,
  diffArrays,
  arrayDiff,

  structuredPatch,
  createTwoFilesPatch,
  createPatch,
  formatPatch,
  INCLUDE_HEADERS,
  FILE_HEADERS_ONLY,
  OMIT_HEADERS,
  applyPatch,
  applyPatches,
  parsePatch,
  reversePatch,
  convertChangesToDMP,
  convertChangesToXML,
  canonicalize
};

export type {
  ChangeObject,
  Change,
  ArrayChange,
  DiffArraysOptionsAbortable,
  DiffArraysOptionsNonabortable,
  DiffCharsOptionsAbortable,
  DiffCharsOptionsNonabortable,
  DiffLinesOptionsAbortable,
  DiffLinesOptionsNonabortable,
  DiffWordsOptionsAbortable,
  DiffWordsOptionsNonabortable,
  DiffSentencesOptionsAbortable,
  DiffSentencesOptionsNonabortable,
  DiffJsonOptionsAbortable,
  DiffJsonOptionsNonabortable,
  DiffCssOptionsAbortable,
  DiffCssOptionsNonabortable,
  StructuredPatch,
  StructuredPatchHunk,

  ApplyPatchOptions,
  ApplyPatchesOptions,

  StructuredPatchOptionsAbortable,
  StructuredPatchOptionsNonabortable,
  CreatePatchOptionsAbortable,
  CreatePatchOptionsNonabortable,
  HeaderOptions
};


================================================
FILE: src/patch/apply.ts
================================================
import {hasOnlyWinLineEndings, hasOnlyUnixLineEndings} from '../util/string.js';
import {isWin, isUnix, unixToWin, winToUnix} from './line-endings.js';
import {parsePatch} from './parse.js';
import distanceIterator from '../util/distance-iterator.js';
import type { StructuredPatch } from '../types.js';

export interface ApplyPatchOptions {
  /**
   * Maximum Levenshtein distance (in lines deleted, added, or subtituted) between the context shown in a patch hunk and the lines found in the file.
   * @default 0
   */
  fuzzFactor?: number,
  /**
   * If `true`, and if the file to be patched consistently uses different line endings to the patch (i.e. either the file always uses Unix line endings while the patch uses Windows ones, or vice versa), then `applyPatch` will behave as if the line endings in the patch were the same as those in the source file.
   * (If `false`, the patch will usually fail to apply in such circumstances since lines deleted in the patch won't be considered to match those in the source file.)
   * @default true
   */
  autoConvertLineEndings?: boolean,
  /**
   * Callback used to compare to given lines to determine if they should be considered equal when patching.
   * Defaults to strict equality but may be overridden to provide fuzzier comparison.
   * Should return false if the lines should be rejected.
   */
  compareLine?: (lineNumber: number, line: string, operation: string, patchContent: string) => boolean,
}

interface ApplyHunkReturnType {
  patchedLines: string[];
  oldLineLastI: number;
}

/**
 * attempts to apply a unified diff patch.
 *
 * Hunks are applied first to last.
 * `applyPatch` first tries to apply the first hunk at the line number specified in the hunk header, and with all context lines matching exactly.
 * If that fails, it tries scanning backwards and forwards, one line at a time, to find a place to apply the hunk where the context lines match exactly.
 * If that still fails, and `fuzzFactor` is greater than zero, it increments the maximum number of mismatches (missing, extra, or changed context lines) that there can be between the hunk context and a region where we are trying to apply the patch such that the hunk will still be considered to match.
 * Regardless of `fuzzFactor`, lines to be deleted in the hunk *must* be present for a hunk to match, and the context lines *immediately* before and after an insertion must match exactly.
 *
 * Once a hunk is successfully fitted, the process begins again with the next hunk.
 * Regardless of `fuzzFactor`, later hunks must be applied later in the file than earlier hunks.
 *
 * If a hunk cannot be successfully fitted *anywhere* with fewer than `fuzzFactor` mismatches, `applyPatch` fails and returns `false`.
 *
 * If a hunk is successfully fitted but not at the line number specified by the hunk header, all subsequent hunks have their target line number adjusted accordingly.
 * (e.g. if the first hunk is applied 10 lines below where the hunk header said it should fit, `applyPatch` will *start* looking for somewhere to apply the second hunk 10 lines below where its hunk header says it goes.)
 *
 * If the patch was applied successfully, returns a string containing the patched text.
 * If the patch could not be applied (because some hunks in the patch couldn't be fitted to the text in `source`), `applyPatch` returns false.
 *
 * @param patch a string diff or the output from the `parsePatch` or `structuredPatch` methods.
 */
export function applyPatch(
  source: string,
  patch: string | StructuredPatch | [StructuredPatch],
  options: ApplyPatchOptions = {}
): string | false {
  let patches: StructuredPatch[];
  if (typeof patch === 'string') {
    patches = parsePatch(patch);
  } else if (Array.isArray(patch)) {
    patches = patch;
  } else {
    patches = [patch];
  }

  if (patches.length > 1) {
    throw new Error('applyPatch only works with a single input.');
  }

  return applyStructuredPatch(source, patches[0], options);
}

function applyStructuredPatch(
  source: string,
  patch: StructuredPatch,
  options: ApplyPatchOptions = {}
): string | false {
  if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) {
    if (hasOnlyWinLineEndings(source) && isUnix(patch)) {
      patch = unixToWin(patch);
    } else if (hasOnlyUnixLineEndings(source) && isWin(patch)) {
      patch = winToUnix(patch);
    }
  }

  // Apply the diff to the input
  const lines = source.split('\n'),
        hunks = patch.hunks,
        compareLine = options.compareLine || ((lineNumber, line, operation, patchContent) => line === patchContent),
        fuzzFactor = options.fuzzFactor || 0;
  let minLine = 0;

  if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) {
    throw new Error('fuzzFactor must be a non-negative integer');
  }

  // Special case for empty patch.
  if (!hunks.length) {
    return source;
  }

  // Before anything else, handle EOFNL insertion/removal. If the patch tells us to make a change
  // to the EOFNL that is redundant/impossible - i.e. to remove a newline that's not there, or add a
  // newline that already exists - then we either return false and fail to apply the patch (if
  // fuzzFactor is 0) or simply ignore the problem and do nothing (if fuzzFactor is >0).
  // If we do need to remove/add a newline at EOF, this will always be in the final hunk:
  let prevLine = '',
      removeEOFNL = false,
      addEOFNL = false;
  for (let i = 0; i < hunks[hunks.length - 1].lines.length; i++) {
    const line = hunks[hunks.length - 1].lines[i];
    if (line[0] == '\\') {
      if (prevLine[0] == '+') {
        removeEOFNL = true;
      } else if (prevLine[0] == '-') {
        addEOFNL = true;
      }
    }
    prevLine = line;
  }
  if (removeEOFNL) {
    if (addEOFNL) {
      // This means the final line gets changed but doesn't have a trailing newline in either the
      // original or patched version. In that case, we do nothing if fuzzFactor > 0, and if
      // fuzzFactor is 0, we simply validate that the source file has no trailing newline.
      if (!fuzzFactor && lines[lines.length - 1] == '') {
        return false;
      }
    } else if (lines[lines.length - 1] == '') {
      lines.pop();
    } else if (!fuzzFactor) {
      return false;
    }
  } else if (addEOFNL) {
    if (lines[lines.length - 1] != '') {
      lines.push('');
    } else if (!fuzzFactor) {
      return false;
    }
  }

  /**
   * Checks if the hunk can be made to fit at the provided location with at most `maxErrors`
   * insertions, substitutions, or deletions, while ensuring also that:
   * - lines deleted in the hunk match exactly, and
   * - wherever an insertion operation or block of insertion operations appears in the hunk, the
   *   immediately preceding and following lines of context match exactly
   *
   * `toPos` should be set such that lines[toPos] is meant to match hunkLines[0].
   *
   * If the hunk can be applied, returns an object with properties `oldLineLastI` and
   * `replacementLines`. Otherwise, returns null.
   */
  function applyHunk(
    hunkLines: string[],
    toPos: number,
    maxErrors: number,
    hunkLinesI: number = 0,
    lastContextLineMatched: boolean = true,
    patchedLines: string[] = [],
    patchedLinesLength: number = 0
  ): ApplyHunkReturnType | null {
    let nConsecutiveOldContextLines = 0;
    let nextContextLineMustMatch = false;
    for (; hunkLinesI < hunkLines.length; hunkLinesI++) {
      const hunkLine = hunkLines[hunkLinesI],
          operation = (hunkLine.length > 0 ? hunkLine[0] : ' '),
          content = (hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine);

      if (operation === '-') {
        if (compareLine(toPos + 1, lines[toPos], operation, content)) {
          toPos++;
          nConsecutiveOldContextLines = 0;
        } else {
          if (!maxErrors || lines[toPos] == null) {
            return null;
          }
          patchedLines[patchedLinesLength] = lines[toPos];
          return applyHunk(
            hunkLines,
            toPos + 1,
            maxErrors - 1,
            hunkLinesI,
            false,
            patchedLines,
            patchedLinesLength + 1
          );
        }
      }

      if (operation === '+') {
        if (!lastContextLineMatched) {
          return null;
        }
        patchedLines[patchedLinesLength] = content;
        patchedLinesLength++;
        nConsecutiveOldContextLines = 0;
        nextContextLineMustMatch = true;
      }

      if (operation === ' ') {
        nConsecutiveOldContextLines++;
        patchedLines[patchedLinesLength] = lines[toPos];
        if (compareLine(toPos + 1, lines[toPos], operation, content)) {
          patchedLinesLength++;
          lastContextLineMatched = true;
          nextContextLineMustMatch = false;
          toPos++;
        } else {
          if (nextContextLineMustMatch || !maxErrors) {
            return null;
          }

          // Consider 3 possibilities in sequence:
          // 1. lines contains a *substitution* not included in the patch context, or
          // 2. lines contains an *insertion* not included in the patch context, or
          // 3. lines contains a *deletion* not included in the patch context
          // The first two options are of course only possible if the line from lines is non-null -
          // i.e. only option 3 is possible if we've overrun the end of the old file.
          return (
            lines[toPos] && (
              applyHunk(
                hunkLines,
                toPos + 1,
                maxErrors - 1,
                hunkLinesI + 1,
                false,
                patchedLines,
                patchedLinesLength + 1
              ) || applyHunk(
                hunkLines,
                toPos + 1,
                maxErrors - 1,
                hunkLinesI,
                false,
                patchedLines,
                patchedLinesLength + 1
              )
            ) || applyHunk(
              hunkLines,
              toPos,
              maxErrors - 1,
              hunkLinesI + 1,
              false,
              patchedLines,
              patchedLinesLength
            )
          );
        }
      }
    }

    // Before returning, trim any unmodified context lines off the end of patchedLines and reduce
    // toPos (and thus oldLineLastI) accordingly. This allows later hunks to be applied to a region
    // that starts in this hunk's trailing context.
    patchedLinesLength -= nConsecutiveOldContextLines;
    toPos -= nConsecutiveOldContextLines;
    patchedLines.length = patchedLinesLength;
    return {
      patchedLines,
      oldLineLastI: toPos - 1
    };
  }

  const resultLines: string[] = [];

  // Search best fit offsets for each hunk based on the previous ones
  let prevHunkOffset = 0;
  for (let i = 0; i < hunks.length; i++) {
    const hunk = hunks[i];
    let hunkResult;
    const maxLine = lines.length - hunk.oldLines + fuzzFactor;
    let toPos: number | undefined;
    for (let maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) {
      toPos = hunk.oldStart + prevHunkOffset - 1;
      const iterator = distanceIterator(toPos, minLine, maxLine);
      for (; toPos !== undefined; toPos = iterator()) {
        hunkResult = applyHunk(hunk.lines, toPos, maxErrors);
        if (hunkResult) {
          break;
        }
      }
      if (hunkResult) {
        break;
      }
    }

    if (!hunkResult) {
      return false;
    }

    // Copy everything from the end of where we applied the last hunk to the start of this hunk
    for (let i = minLine; i < toPos!; i++) {
      resultLines.push(lines[i]);
    }

    // Add the lines produced by applying the hunk:
    for (let i = 0; i < hunkResult.patchedLines.length; i++) {
      const line = hunkResult.patchedLines[i];
      resultLines.push(line);
    }

    // Set lower text limit to end of the current hunk, so next ones don't try
    // to fit over already patched text
    minLine = hunkResult.oldLineLastI + 1;

    // Note the offset between where the patch said the hunk should've applied and where we
    // applied it, so we can adjust future hunks accordingly:
    prevHunkOffset = toPos! + 1 - hunk.oldStart;
  }

  // Copy over the rest of the lines from the old text
  for (let i = minLine; i < lines.length; i++) {
    resultLines.push(lines[i]);
  }

  return resultLines.join('\n');
}

export interface ApplyPatchesOptions extends ApplyPatchOptions {
  loadFile: (index: StructuredPatch, callback: (err: any, data: string) => void) => void,
  patched: (index: StructuredPatch, content: string | false, callback: (err: any) => void) => void,
  complete: (err?: any) => void,
}

/**
 * applies one or more patches.
 *
 * `patch` may be either an array of structured patch objects, or a string representing a patch in unified diff format (which may patch one or more files).
 *
 * This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is:
 *
 * - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution.
 * - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution.
 *
 * Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made.
 */
export function applyPatches(uniDiff: string | StructuredPatch[], options: ApplyPatchesOptions): void {
  const spDiff: StructuredPatch[] = typeof uniDiff === 'string' ? parsePatch(uniDiff) : uniDiff;

  let currentIndex = 0;
  function processIndex(): void {
    const index = spDiff[currentIndex++];
    if (!index) {
      return options.complete();
    }

    options.loadFile(index, function(err: any, data: string) {
      if (err) {
        return options.complete(err);
      }

      const updatedContent = applyPatch(data, index, options);
      options.patched(index, updatedContent, function(err: any) {
        if (err) {
          return options.complete(err);
        }

        processIndex();
      });
    });
  }
  processIndex();
}


================================================
FILE: src/patch/create.ts
================================================
import {diffLines} from '../diff/line.js';
import type { StructuredPatch, DiffLinesOptionsAbortable, DiffLinesOptionsNonabortable, AbortableDiffOptions, ChangeObject } from '../types.js';

type StructuredPatchCallbackAbortable = (patch: StructuredPatch | undefined) => void;
type StructuredPatchCallbackNonabortable = (patch: StructuredPatch) => void;

export interface HeaderOptions {
  includeIndex: boolean;
  includeUnderline: boolean;
  includeFileHeaders: boolean;
}

export const INCLUDE_HEADERS = {
  includeIndex: true,
  includeUnderline: true,
  includeFileHeaders: true
};
export const FILE_HEADERS_ONLY = {
  includeIndex: false,
  includeUnderline: false,
  includeFileHeaders: true
};
export const OMIT_HEADERS = {
  includeIndex: false,
  includeUnderline: false,
  includeFileHeaders: false
};

interface _StructuredPatchOptionsAbortable extends Pick<DiffLinesOptionsAbortable, 'ignoreWhitespace' | 'stripTrailingCr'> {
  /**
   * describes how many lines of context should be included.
   * You can set this to `Number.MAX_SAFE_INTEGER` or `Infinity` to include the entire file content in one hunk.
   * @default 4
   */
  context?: number,
  callback?: StructuredPatchCallbackAbortable,
}
export type StructuredPatchOptionsAbortable = _StructuredPatchOptionsAbortable & AbortableDiffOptions;
export interface StructuredPatchOptionsNonabortable extends Pick<DiffLinesOptionsNonabortable, 'ignoreWhitespace' | 'stripTrailingCr'> {
  context?: number,
  callback?: StructuredPatchCallbackNonabortable,
}
interface StructuredPatchCallbackOptionAbortable {
  /**
   * If provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated.
   * The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.
   */
  callback: StructuredPatchCallbackAbortable;
}
interface StructuredPatchCallbackOptionNonabortable {
  /**
   * If provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated.
   * The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.
   */
  callback: StructuredPatchCallbackNonabortable;
}

// Purely an implementation detail of diffLinesResultToPatch, which mutates the result of diffLines
// for convenience of implementation
interface ChangeObjectPlusLines extends Partial<ChangeObject<string>> {
  value: string;
  lines?: string[];
}

/**
 * returns an object with an array of hunk objects.
 *
 * This method is similar to createTwoFilesPatch, but returns a data structure suitable for further processing.
 * @param oldFileName String to be output in the filename section of the patch for the removals
 * @param newFileName String to be output in the filename section of the patch for the additions
 * @param oldStr Original string value
 * @param newStr New string value
 * @param oldHeader Optional additional information to include in the old file header.
 * @param newHeader Optional additional information to include in the new file header.
 */
export function structuredPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: StructuredPatchCallbackNonabortable
): undefined;
export function structuredPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: StructuredPatchOptionsAbortable & StructuredPatchCallbackOptionAbortable
): undefined
export function structuredPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: StructuredPatchOptionsNonabortable & StructuredPatchCallbackOptionNonabortable
): undefined
export function structuredPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: StructuredPatchOptionsAbortable
): StructuredPatch | undefined
export function structuredPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader?: string,
  newHeader?: string,
  options?: StructuredPatchOptionsNonabortable
): StructuredPatch
export function structuredPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader?: string,
  newHeader?: string,
  options?: StructuredPatchOptionsAbortable | StructuredPatchOptionsNonabortable | StructuredPatchCallbackNonabortable
): StructuredPatch | undefined {
  let optionsObj: StructuredPatchOptionsAbortable | StructuredPatchOptionsNonabortable;
  if (!options) {
    optionsObj = {};
  } else if (typeof options === 'function') {
    optionsObj = {callback: options};
  } else {
    optionsObj = options;
  }


  if (typeof optionsObj.context === 'undefined') {
    optionsObj.context = 4;
  }

  // We copy this into its own variable to placate TypeScript, which thinks
  // optionsObj.context might be undefined in the callbacks below.
  const context = optionsObj.context;

  // @ts-expect-error (runtime check for something that is correctly a static type error)
  if (optionsObj.newlineIsToken) {
    throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions');
  }

  if (!optionsObj.callback) {
    return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj as any));
  } else {
    const {callback} = optionsObj;
    diffLines(
      oldStr,
      newStr,
      {
        ...optionsObj,
        callback: (diff) => {
          const patch = diffLinesResultToPatch(diff);
          // TypeScript is unhappy without the cast because it does not understand that `patch` may
          // be undefined here only if `callback` is StructuredPatchCallbackAbortable:
          (callback as any)(patch);
        }
      }
    );
  }

  function diffLinesResultToPatch(diff: ChangeObjectPlusLines[] | undefined) {
    // STEP 1: Build up the patch with no "\ No newline at end of file" lines and with the arrays
    //         of lines containing trailing newline characters. We'll tidy up later...

    if(!diff) {
      return;
    }

    diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier

    function contextLines(lines: string[]) {
      return lines.map(function(entry) { return ' ' + entry; });
    }

    const hunks = [];
    let oldRangeStart = 0, newRangeStart = 0, curRange: string[] = [],
        oldLine = 1, newLine = 1;
    for (let i = 0; i < diff.length; i++) {
      const current = diff[i],
            lines = current.lines || splitLines(current.value);
      current.lines = lines;

      if (current.added || current.removed) {
        // If we have previous context, start with that
        if (!oldRangeStart) {
          const prev = diff[i - 1];
          oldRangeStart = oldLine;
          newRangeStart = newLine;

          if (prev) {
            curRange = context > 0 ? contextLines(prev.lines!.slice(-context)) : [];
            oldRangeStart -= curRange.length;
            newRangeStart -= curRange.length;
          }
        }

        // Output our changes
        for (const line of lines) {
          curRange.push((current.added ? '+' : '-') + line);
        }

        // Track the updated file position
        if (current.added) {
          newLine += lines.length;
        } else {
          oldLine += lines.length;
        }
      } else {
        // Identical context lines. Track line changes
        if (oldRangeStart) {
          // Close out any changes that have been output (or join overlapping)
          if (lines.length <= context * 2 && i < diff.length - 2) {
            // Overlapping
            for (const line of contextLines(lines)) {
              curRange.push(line);
            }
          } else {
            // end the range and output
            const contextSize = Math.min(lines.length, context);
            for (const line of contextLines(lines.slice(0, contextSize))) {
              curRange.push(line);
            }

            const hunk = {
              oldStart: oldRangeStart,
              oldLines: (oldLine - oldRangeStart + contextSize),
              newStart: newRangeStart,
              newLines: (newLine - newRangeStart + contextSize),
              lines: curRange
            };
            hunks.push(hunk);

            oldRangeStart = 0;
            newRangeStart = 0;
            curRange = [];
          }
        }
        oldLine += lines.length;
        newLine += lines.length;
      }
    }

    // Step 2: eliminate the trailing `\n` from each line of each hunk, and, where needed, add
    //         "\ No newline at end of file".
    for (const hunk of hunks) {
      for (let i = 0; i < hunk.lines.length; i++) {
        if (hunk.lines[i].endsWith('\n')) {
          hunk.lines[i] = hunk.lines[i].slice(0, -1);
        } else {
          hunk.lines.splice(i + 1, 0, '\\ No newline at end of file');
          i++; // Skip the line we just added, then continue iterating
        }
      }
    }

    return {
      oldFileName: oldFileName, newFileName: newFileName,
      oldHeader: oldHeader, newHeader: newHeader,
      hunks: hunks
    };
  }
}

/**
 * creates a unified diff patch.
 * @param patch either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`)
 */
export function formatPatch(patch: StructuredPatch | StructuredPatch[], headerOptions?: HeaderOptions): string {
  if (!headerOptions) {
    headerOptions = INCLUDE_HEADERS;
  }
  if (Array.isArray(patch)) {
    if (patch.length > 1 && !headerOptions.includeFileHeaders) {
      throw new Error(
        'Cannot omit file headers on a multi-file patch. '
        + '(The result would be unparseable; how would a tool trying to apply '
        + 'the patch know which changes are to which file?)'
      );
    }
    return patch.map(p => formatPatch(p, headerOptions)).join('\n');
  }

  const ret = [];
  if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) {
    ret.push('Index: ' + patch.oldFileName);
  }
  if (headerOptions.includeUnderline) {
    ret.push('===================================================================');
  }
  if (headerOptions.includeFileHeaders) {
    ret.push('--- ' + patch.oldFileName + (typeof patch.oldHeader === 'undefined' ? '' : '\t' + patch.oldHeader));
    ret.push('+++ ' + patch.newFileName + (typeof patch.newHeader === 'undefined' ? '' : '\t' + patch.newHeader));
  }

  for (let i = 0; i < patch.hunks.length; i++) {
    const hunk = patch.hunks[i];
    // Unified Diff Format quirk: If the chunk size is 0,
    // the first number is one lower than one would expect.
    // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
    if (hunk.oldLines === 0) {
      hunk.oldStart -= 1;
    }
    if (hunk.newLines === 0) {
      hunk.newStart -= 1;
    }
    ret.push(
      '@@ -' + hunk.oldStart + ',' + hunk.oldLines
      + ' +' + hunk.newStart + ',' + hunk.newLines
      + ' @@'
    );
    for (const line of hunk.lines) {
      ret.push(line);
    }
  }

  return ret.join('\n') + '\n';
}

type CreatePatchCallbackAbortable = (patch: string | undefined) => void;
type CreatePatchCallbackNonabortable = (patch: string) => void;

interface _CreatePatchOptionsAbortable extends Pick<DiffLinesOptionsAbortable, 'ignoreWhitespace' | 'stripTrailingCr'> {
  context?: number,
  callback?: CreatePatchCallbackAbortable,
  headerOptions?: HeaderOptions,
}
export type CreatePatchOptionsAbortable = _CreatePatchOptionsAbortable & AbortableDiffOptions;
export interface CreatePatchOptionsNonabortable extends Pick<DiffLinesOptionsNonabortable, 'ignoreWhitespace' | 'stripTrailingCr'> {
  context?: number,
  callback?: CreatePatchCallbackNonabortable,
  headerOptions?: HeaderOptions,
}
interface CreatePatchCallbackOptionAbortable {
  callback: CreatePatchCallbackAbortable;
}
interface CreatePatchCallbackOptionNonabortable {
  callback: CreatePatchCallbackNonabortable;
}

/**
 * creates a unified diff patch by first computing a diff with `diffLines` and then serializing it to unified diff format.
 * @param oldFileName String to be output in the filename section of the patch for the removals
 * @param newFileName String to be output in the filename section of the patch for the additions
 * @param oldStr Original string value
 * @param newStr New string value
 * @param oldHeader Optional additional information to include in the old file header.
 * @param newHeader Optional additional information to include in the new file header.
 */
export function createTwoFilesPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: CreatePatchCallbackNonabortable
): undefined;
export function createTwoFilesPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: CreatePatchOptionsAbortable & CreatePatchCallbackOptionAbortable
): undefined
export function createTwoFilesPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: CreatePatchOptionsNonabortable & CreatePatchCallbackOptionNonabortable
): undefined
export function createTwoFilesPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: CreatePatchOptionsAbortable
): string | undefined
export function createTwoFilesPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader?: string,
  newHeader?: string,
  options?: CreatePatchOptionsNonabortable
): string
export function createTwoFilesPatch(
  oldFileName: string,
  newFileName: string,
  oldStr: string,
  newStr: string,
  oldHeader?: string,
  newHeader?: string,
  options?: CreatePatchOptionsAbortable | CreatePatchOptionsNonabortable | CreatePatchCallbackNonabortable
): string | undefined {
  if (typeof options === 'function') {
    options = {callback: options};
  }

  if (!options?.callback) {
    const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options as any);
    if (!patchObj) {
      return;
    }
    return formatPatch(patchObj, options?.headerOptions);
  } else {
    const {callback} = options;
    structuredPatch(
      oldFileName,
      newFileName,
      oldStr,
      newStr,
      oldHeader,
      newHeader,
      {
        ...options,
        callback: patchObj => {
          if (!patchObj) {
            (callback as CreatePatchCallbackAbortable)(undefined);
          } else {
            callback(formatPatch(patchObj, options.headerOptions));
          }
        }
      }
    );
  }
}

/**
 * creates a unified diff patch.
 *
 * Just like createTwoFilesPatch, but with oldFileName being equal to newFileName.
 * @param fileName String to be output in the filename section of the patch
 * @param oldStr Original string value
 * @param newStr New string value
 * @param oldHeader Optional additional information to include in the old file header.
 * @param newHeader Optional additional information to include in the new file header.
 */
export function createPatch(
  fileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: CreatePatchCallbackNonabortable
): undefined;
export function createPatch(
  fileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: CreatePatchOptionsAbortable & CreatePatchCallbackOptionAbortable
): undefined
export function createPatch(
  fileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: CreatePatchOptionsNonabortable & CreatePatchCallbackOptionNonabortable
): undefined
export function createPatch(
  fileName: string,
  oldStr: string,
  newStr: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  options: CreatePatchOptionsAbortable
): string | undefined
export function createPatch(
  fileName: string,
  oldStr: string,
  newStr: string,
  oldHeader?: string,
  newHeader?: string,
  options?: CreatePatchOptionsNonabortable
): string
export function createPatch(
  fileName: string,
  oldStr: string,
  newStr: string,
  oldHeader?: string,
  newHeader?: string,
  options?: CreatePatchOptionsAbortable | CreatePatchOptionsNonabortable | CreatePatchCallbackNonabortable
): string | undefined {
  return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options as any);
}

/**
 * Split `text` into an array of lines, including the trailing newline character (where present)
 */
function splitLines(text: string): string[] {
  const hasTrailingNl = text.endsWith('\n');
  const result = text.split('\n').map(line => line + '\n');
  if (hasTrailingNl) {
    result.pop();
  } else {
    result.push(
      (result.pop() as string).slice(0, -1)
    );
  }
  return result;
}


================================================
FILE: src/patch/line-endings.ts
================================================
import type { StructuredPatch } from '../types.js';

export function unixToWin(patch: StructuredPatch): StructuredPatch;
export function unixToWin(patches: StructuredPatch[]): StructuredPatch[];
export function unixToWin(patch: StructuredPatch | StructuredPatch[]): StructuredPatch | StructuredPatch[];
export function unixToWin(patch: StructuredPatch | StructuredPatch[]): StructuredPatch | StructuredPatch[] {
  if (Array.isArray(patch)) {
    // It would be cleaner if instead of the line below we could just write
    //     return patch.map(unixToWin)
    // but mysteriously TypeScript (v5.7.3 at the time of writing) does not like this and it will
    // refuse to compile, thinking that unixToWin could then return StructuredPatch[][] and the
    // result would be incompatible with the overload signatures.
    // See bug report at https://github.com/microsoft/TypeScript/issues/61398.
    return patch.map(p => unixToWin(p));
  }

  return {
    ...patch,
    hunks: patch.hunks.map(hunk => ({
      ...hunk,
      lines: hunk.lines.map(
        (line, i) =>
          (line.startsWith('\\') || line.endsWith('\r') || hunk.lines[i + 1]?.startsWith('\\'))
            ? line
            : line + '\r'
      )
    }))
  };
}

export function winToUnix(patch: StructuredPatch): StructuredPatch;
export function winToUnix(patches: StructuredPatch[]): StructuredPatch[];
export function winToUnix(patch: StructuredPatch | StructuredPatch[]): StructuredPatch | StructuredPatch[];
export function winToUnix(patch: StructuredPatch | StructuredPatch[]): StructuredPatch | StructuredPatch[] {
  if (Array.isArray(patch)) {
    // (See comment above equivalent line in unixToWin)
    return patch.map(p => winToUnix(p));
  }

  return {
    ...patch,
    hunks: patch.hunks.map(hunk => ({
      ...hunk,
      lines: hunk.lines.map(line => line.endsWith('\r') ? line.substring(0, line.length - 1) : line)
    }))
  };
}

/**
 * Returns true if the patch consistently uses Unix line endings (or only involves one line and has
 * no line endings).
 */
export function isUnix(patch: StructuredPatch | StructuredPatch[]): boolean {
  if (!Array.isArray(patch)) { patch = [patch]; }
  return !patch.some(
    index => index.hunks.some(
      hunk => hunk.lines.some(
        line => !line.startsWith('\\') && line.endsWith('\r')
      )
    )
  );
}

/**
 * Returns true if the patch uses Windows line endings and only Windows line endings.
 */
export function isWin(patch: StructuredPatch | StructuredPatch[]): boolean {
  if (!Array.isArray(patch)) { patch = [patch]; }
  return patch.some(index => index.hunks.some(hunk => hunk.lines.some(line => line.endsWith('\r'))))
    && patch.every(
      index => index.hunks.every(
        hunk => hunk.lines.every(
          (line, i) => line.startsWith('\\') || line.endsWith('\r') || hunk.lines[i + 1]?.startsWith('\\')
        )
      )
    );
}


================================================
FILE: src/patch/parse.ts
================================================
import type { StructuredPatch } from '../types.js';

/**
 * Parses a patch into structured data, in the same structure returned by `structuredPatch`.
 *
 * @return a JSON object representation of the a patch, suitable for use with the `applyPatch` method.
 */
export function parsePatch(uniDiff: string): StructuredPatch[] {
  const diffstr = uniDiff.split(/\n/),
        list: Partial<StructuredPatch>[] = [];
  let i = 0;

  function parseIndex() {
    const index: Partial<StructuredPatch> = {};
    list.push(index);

    // Parse diff metadata
    while (i < diffstr.length) {
      const line = diffstr[i];

      // File header found, end parsing diff metadata
      if ((/^(---|\+\+\+|@@)\s/).test(line)) {
        break;
      }

      // Try to parse the line as a diff header, like
      //     Index: README.md
      // or
      //     diff -r 9117c6561b0b -r 273ce12ad8f1 .hgignore
      // or
      //     Index: something with multiple words
      // and extract the filename (or whatever else is used as an index name)
      // from the end (i.e. 'README.md', '.hgignore', or
      // 'something with multiple words' in the examples above).
      //
      // TODO: It seems awkward that we indiscriminately trim off trailing
      //       whitespace here. Theoretically, couldn't that be meaningful -
      //       e.g. if the patch represents a diff of a file whose name ends
      //       with a space? Seems wrong to nuke it.
      //       But this behaviour has been around since v2.2.1 in 2015, so if
      //       it's going to change, it should be done cautiously and in a new
      //       major release, for backwards-compat reasons.
      //       -- ExplodingCabbage
      const headerMatch = (/^(?:Index:|diff(?: -r \w+)+)\s+/).exec(line);
      if (headerMatch) {
        index.index = line.substring(headerMatch[0].length).trim();
      }

      i++;
    }

    // Parse file headers if they are defined. Unified diff requires them, but
    // there's no technical issues to have an isolated hunk without file header
    parseFileHeader(index);
    parseFileHeader(index);

    // Parse hunks
    index.hunks = [];

    while (i < diffstr.length) {
      const line = diffstr[i];
      if ((/^(Index:\s|diff\s|---\s|\+\+\+\s|===================================================================)/).test(line)) {
        break;
      } else if ((/^@@/).test(line)) {
        index.hunks.push(parseHunk());
      } else if (line) {
        throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(line));
      } else {
        i++;
      }
    }
  }

  // Parses the --- and +++ headers, if none are found, no lines
  // are consumed.
  function parseFileHeader(index: Partial<StructuredPatch>) {
    const fileHeaderMatch = (/^(---|\+\+\+)\s+/).exec(diffstr[i]);
    if (fileHeaderMatch) {
      const prefix = fileHeaderMatch[1],
            data = diffstr[i].substring(3).trim().split('\t', 2),
            header = (data[1] || '').trim();
      let fileName = data[0].replace(/\\\\/g, '\\');
      if (fileName.startsWith('"') && fileName.endsWith('"')) {
        fileName = fileName.substr(1, fileName.length - 2);
      }
      if (prefix === '---') {
        index.oldFileName = fileName;
        index.oldHeader = header;
      } else {
        index.newFileName = fileName;
        index.newHeader = header;
      }

      i++;
    }
  }

  // Parses a hunk
  // This assumes that we are at the start of a hunk.
  function parseHunk() {
    const chunkHeaderIndex = i,
        chunkHeaderLine = diffstr[i++],
        chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);

    const hunk = {
      oldStart: +chunkHeader[1],
      oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],
      newStart: +chunkHeader[3],
      newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],
      lines: [] as string[]
    };

    // Unified Diff Format quirk: If the chunk size is 0,
    // the first number is one lower than one would expect.
    // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
    if (hunk.oldLines === 0) {
      hunk.oldStart += 1;
    }
    if (hunk.newLines === 0) {
      hunk.newStart += 1;
    }

    let addCount = 0,
        removeCount = 0;
    for (
      ;
      i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || diffstr[i]?.startsWith('\\'));
      i++
    ) {
      const operation = (diffstr[i].length == 0 && i != (diffstr.length - 1)) ? ' ' : diffstr[i][0];
      if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
        hunk.lines.push(diffstr[i]);

        if (operation === '+') {
          addCount++;
        } else if (operation === '-') {
          removeCount++;
        } else if (operation === ' ') {
          addCount++;
          removeCount++;
        }
      } else {
        throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`);
      }
    }

    // Handle the empty block count case
    if (!addCount && hunk.newLines === 1) {
      hunk.newLines = 0;
    }
    if (!removeCount && hunk.oldLines === 1) {
      hunk.oldLines = 0;
    }

    // Perform sanity checking
    if (addCount !== hunk.newLines) {
      throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
    }
    if (removeCount !== hunk.oldLines) {
      throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
    }

    return hunk;
  }

  while (i < diffstr.length) {
    parseIndex();
  }

  return list as StructuredPatch[];
}


================================================
FILE: src/patch/reverse.ts
================================================
import type { StructuredPatch } from '../types.js';

/**
 * @param patch either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`).
 * @returns a new structured patch which when applied will undo the original `patch`.
 */
export function reversePatch(structuredPatch: StructuredPatch): StructuredPatch;
export function reversePatch(structuredPatch: StructuredPatch[]): StructuredPatch[];
export function reversePatch(structuredPatch: StructuredPatch | StructuredPatch[]): StructuredPatch | StructuredPatch[];
export function reversePatch(structuredPatch: StructuredPatch | StructuredPatch[]): StructuredPatch | StructuredPatch[] {
  if (Array.isArray(structuredPatch)) {
    // (See comment in unixToWin for why we need the pointless-looking anonymous function here)
    return structuredPatch.map(patch => reversePatch(patch)).reverse();
  }

  return {
    ...structuredPatch,
    oldFileName: structuredPatch.newFileName,
    oldHeader: structuredPatch.newHeader,
    newFileName: structuredPatch.oldFileName,
    newHeader: structuredPatch.oldHeader,
    hunks: structuredPatch.hunks.map(hunk => {
      return {
        oldLines: hunk.newLines,
        oldStart: hunk.newStart,
        newLines: hunk.oldLines,
        newStart: hunk.oldStart,
        lines: hunk.lines.map(l => {
          if (l.startsWith('-')) { return `+${l.slice(1)}`; }
          if (l.startsWith('+')) { return `-${l.slice(1)}`; }
          return l;
        })
      };
    })
  };
}


================================================
FILE: src/types.ts
================================================
export interface ChangeObject<ValueT> {
  /**
   * The concatenated content of all the tokens represented by this change object - i.e. generally the text that is either added, deleted, or common, as a single string.
   * In cases where tokens are considered common but are non-identical (e.g. because an option like `ignoreCase` or a custom `comparator` was used), the value from the *new* string will be provided here.
   */
  value: ValueT;
  /**
   * true if the value was inserted into the new string, otherwise false
   */
  added: boolean;
  /**
   * true if the value was removed from the old string, otherwise false
   */
  removed: boolean;
  /**
   * How many tokens (e.g. chars for `diffChars`, lines for `diffLines`) the value in the change object consists of
   */
  count: number;
}

// Name "Change" is used here for consistency with the previous type definitions from
// DefinitelyTyped. I would *guess* this is probably the single most common type for people to
// explicitly reference by name in their own code, so keeping its name consistent is valuable even
// though the names of many other types are inconsistent with the old DefinitelyTyped names.
export type Change = ChangeObject<string>;
export type ArrayChange<T> = ChangeObject<T[]>;

export interface CommonDiffOptions {
  /**
   * If `true`, the array of change objects returned will contain one change object per token (e.g. one per line if calling `diffLines`), instead of runs of consecutive tokens that are all added / all removed / all conserved being combined into a single change object.
   */
  oneChangePerToken?: boolean,
}

export interface TimeoutOption {
  /**
   * A number of milliseconds after which the diffing algorithm will abort and return `undefined`.
   * Supported by the same functions as `maxEditLength`.
   */
  timeout: number;
}

export interface MaxEditLengthOption {
  /**
   * A number specifying the maximum edit distance to consider between the old and new texts.
   * You can use this to limit the computational cost of diffing large, very different texts by giving up early if the cost will be huge.
   * This option can be passed either to diffing functions (`diffLines`, `diffChars`, etc) or to patch-creation function (`structuredPatch`, `createPatch`, etc), all of which will indicate that the max edit length was reached by returning `undefined` instead of whatever they'd normally return.
   */
  maxEditLength: number;
}

export type AbortableDiffOptions = TimeoutOption | MaxEditLengthOption;

export type DiffCallbackNonabortable<T> = (result: ChangeObject<T>[]) => void;
export type DiffCallbackAbortable<T> = (result: ChangeObject<T>[] | undefined) => void;

export interface CallbackOptionNonabortable<T> {
  /**
   * If provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated.
   * The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.
   */
  callback: DiffCallbackNonabortable<T>
}
export interface CallbackOptionAbortable<T> {
  /**
   * If provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated.
   * The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.
   */
  callback: DiffCallbackAbortable<T>
}

interface DiffArraysOptions<T> extends CommonDiffOptions {
  comparator?: (a: T, b: T) => boolean,
}
export interface DiffArraysOptionsNonabortable<T> extends DiffArraysOptions<T> {
  /**
   * If provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated.
   * The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.
   */
  callback?: DiffCallbackNonabortable<T[]>
}
export type DiffArraysOptionsAbortable<T> = DiffArraysOptions<T> & AbortableDiffOptions & Partial<CallbackOptionAbortable<T[]>>


interface DiffCharsOptions extends CommonDiffOptions {
  /**
   * If `true`, the uppercase and lowercase forms of a character are considered equal.
   * @default false
   */
  ignoreCase?: boolean;
}
export interface DiffCharsOptionsNonabortable extends DiffCharsOptions {
  /**
   * If provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated.
   * The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.
   */
  callback?: DiffCallbackNonabortable<string>
}
export type DiffCharsOptionsAbortable = DiffCharsOptions & AbortableDiffOptions & Partial<CallbackOptionAbortable<string>>

interface DiffLinesOptions extends CommonDiffOptions {
  /**
   * `true` to remove all trailing CR (`\r`) characters before performing the diff.
   * This helps to get a useful diff when diffing UNIX text files against Windows text files.
   * @default false
   */
  stripTrailingCr?: boolean,
  /**
   * `true` to treat the newline character at the end of each line as its own token.
   * This allows for changes to the newline structure to occur independently of the line content and to be treated as such.
   * In general this is the more human friendly form of `diffLines`; the default behavior with this option turned off is better suited for patches and other computer friendly output.
   *
   * Note that while using `ignoreWhitespace` in combination with `newlineIsToken` is not an error, results may not be as expected.
   * With `ignoreWhitespace: true` and `newlineIsToken: false`, changing a completely empty line to contain some spaces is treated as a non-change, but with `ignoreWhitespace: true` and `newlineIsToken: true`, it is treated as an insertion.
   * This is because the content of a completely blank line is not a token at all in `newlineIsToken` mode.
   *
   * @default false
   */
  newlineIsToken?: boolean,
  /**
   * `true` to ignore a missing newline character at the end of the last line when comparing it to other lines.
   * (By default, the line `'b\n'` in text `'a\nb\nc'` is not considered equal to the line `'b'` in text `'a\nb'`; this option makes them be considered equal.)
   * Ignored if `ignoreWhitespace` or `newlineIsToken` are also true.
   * @default false
   */
  ignoreNewlineAtEof?: boolean,
  /**
   * `true` to ignore leading and trailing whitespace characters when checking if two lines are equal.
   * @default false
   */
  ignoreWhitespace?: boolean,
}
export interface DiffLinesOptionsNonabortable extends DiffLinesOptions {
  /**
   * If provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated.
   * The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.
   */
  callback?: DiffCallbackNonabortable<string>
}
export type DiffLinesOptionsAbortable = DiffLinesOptions & AbortableDiffOptions & Partial<CallbackOptionAbortable<string>>


interface DiffWordsOptions extends CommonDiffOptions {
  /**
   * Same as in `diffChars`.
   * @default false
   */
  ignoreCase?: boolean

  /**
   * An optional [`Intl.Segmenter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter) object (which must have a `granularity` of `'word'`) for `diffWords` to use to split the text into words.
   *
   * Note that this is (deliberately) incorrectly typed as `any` to avoid users whose `lib` & `target` settings in tsconfig.json are older than es2022 getting type errors when they build about `Intl.Segmenter` not existing.
   * This is kind of ugly, since it makes the type declarations worse for users who genuinely use this feature, but seemed worth it to avoid the majority of the library's users (who probably do not use this particular option) getting confusing errors and being forced to change their `lib` to es2022 (even if their own code doesn't use any es2022 functions).
   *
   * By default, `diffWords` does not use an `Intl.Segmenter`, just some regexes for splitting text into words. This will tend to give worse results than `Intl.Segmenter` would, but ensures the results are consistent across environments; `Intl.Segmenter` behaviour is only loosely specced and the implementations in browsers could in principle change dramatically in future. If you want to use `diffWords` with an `Intl.Segmenter` but ensure it behaves the same whatever environment you run it in, use an `Intl.Segmenter` polyfill instead of the JavaScript engine's native `Intl.Segmenter` implementation.
   *
   * Using an `Intl.Segmenter` should allow better word-level diffing of non-English text than the default behaviour. For instance, `Intl.Segmenter`s can generally identify via built-in dictionaries which sequences of adjacent Chinese characters form words, allowing word-level diffing of Chinese. By specifying a language when instantiating the segmenter (e.g. `new Intl.Segmenter('sv', {granularity: 'word'})`) you can also support language-specific rules, like treating Swedish's colon separated contractions (like *k:a* for *kyrka*) as single words; by default this would be seen as two words separated by a colon.
   */
  intlSegmenter?: any,
}
export interface DiffWordsOptionsNonabortable extends DiffWordsOptions {
  /**
   * If provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated.
   * The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.
   */
  callback?: DiffCallbackNonabortable<string>
}
export type DiffWordsOptionsAbortable = DiffWordsOptions & AbortableDiffOptions & Partial<CallbackOptionAbortable<string>>


interface DiffSentencesOptions extends CommonDiffOptions {}
export interface DiffSentencesOptionsNonabortable extends DiffSentencesOptions {
  /**
   * If provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated.
   * The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.
   */
  callback?: DiffCallbackNonabortable<string>
}
export type DiffSentencesOptionsAbortable = DiffSentencesOptions & AbortableDiffOptions & Partial<CallbackOptionAbortable<string>>


interface DiffJsonOptions extends CommonDiffOptions {
  /**
   * A value to replace `undefined` with. Ignored if a `stringifyReplacer` is provided.
   */
  undefinedReplacement?: any,
  /**
   * A custom replacer function.
   * Operates similarly to the `replacer` parameter to [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter), but must be a function.
   */
  stringifyReplacer?: (k: string, v: any) => any,
}
export interface DiffJsonOptionsNonabortable extends DiffJsonOptions {
  /**
   * If provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated.
   * The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.
   */
  callback?: DiffCallbackNonabortable<string>
}
export type DiffJsonOptionsAbortable = DiffJsonOptions & AbortableDiffOptions & Partial<CallbackOptionAbortable<string>>


interface DiffCssOptions extends CommonDiffOptions {}
export interface DiffCssOptionsNonabortable extends DiffCssOptions {
  /**
   * If provided, the diff will be computed in async mode to avoid blocking the event loop while the diff is calculated.
   * The value of the `callback` option should be a function and will be passed the computed diff or patch as its first argument.
   */
  callback?: DiffCallbackNonabortable<string>
}
export type DiffCssOptionsAbortable = DiffCssOptions & AbortableDiffOptions & Partial<CallbackOptionAbortable<string>>


/**
 * Note that this contains the union of ALL options accepted by any of the built-in diffing
 * functions. The README notes which options are usable which functions. Using an option with a
 * diffing function that doesn't support it might yield unreasonable results.
 */
export type AllDiffOptions =
  DiffArraysOptions<unknown> &
  DiffCharsOptions &
  DiffWordsOptions &
  DiffLinesOptions &
  DiffJsonOptions;

export interface StructuredPatch {
  oldFileName: string,
  newFileName: string,
  oldHeader: string | undefined,
  newHeader: string | undefined,
  hunks: StructuredPatchHunk[],
  index?: string,
}

export interface StructuredPatchHunk {
  oldStart: number,
  oldLines: number,
  newStart: number,
  newLines: number,
  lines: string[],
}


================================================
FILE: src/util/array.ts
================================================
export function arrayEqual(a: any[], b: any[]): boolean {
  if (a.length !== b.length) {
    return false;
  }

  return arrayStartsWith(a, b);
}

export function arrayStartsWith(array: any[], start: any[]): boolean {
  if (start.length > array.length) {
    return false;
  }

  for (let i = 0; i < start.length; i++) {
    if (start[i] !== array[i]) {
      return false;
    }
  }

  return true;
}


================================================
FILE: src/util/distance-iterator.ts
================================================
// Iterator that traverses in the range of [min, max], stepping
// by distance from a given start position. I.e. for [0, 4], with
// start of 2, this will iterate 2, 3, 1, 4, 0.
export default function(start: number, minLine: number, maxLine: number): () => number | undefined {
  let wantForward = true,
      backwardExhausted = false,
      forwardExhausted = false,
      localOffset = 1;

  return function iterator(): number | undefined {
    if (wantForward && !forwardExhausted) {
      if (backwardExhausted) {
        localOffset++;
      } else {
        wantForward = false;
      }

      // Check if trying to fit beyond text length, and if not, check it fits
      // after offset location (or desired location on first iteration)
      if (start + localOffset <= maxLine) {
        return start + localOffset;
      }

      forwardExhausted = true;
    }

    if (!backwardExhausted) {
      if (!forwardExhausted) {
        wantForward = true;
      }

      // Check if trying to fit before text beginning, and if not, check it fits
      // before offset location
      if (minLine <= start - localOffset) {
        return start - localOffset++;
      }

      backwardExhausted = true;
      return iterator();
    }

    // We tried to fit hunk before text beginning and beyond text length, then
    // hunk can't fit on the text. Return undefined
    return undefined;
  };
}


================================================
FILE: src/util/params.ts
================================================
export function generateOptions(
  options: {[key: string]: any} | ((_: unknown) => void),
  defaults: any
): object {
  if (typeof options === 'function') {
    defaults.callback = options;
  } else if (options) {
    for (const name in options) {
      /* istanbul ignore else */
      if (Object.prototype.hasOwnProperty.call(options, name)) {
        defaults[name] = options[name];
      }
    }
  }
  return defaults;
}


================================================
FILE: src/util/string.ts
================================================
export function longestCommonPrefix(str1: string, str2: string): string {
  let i;
  for (i = 0; i < str1.length && i < str2.length; i++) {
    if (str1[i] != str2[i]) {
      return str1.slice(0, i);
    }
  }
  return str1.slice(0, i);
}

export function longestCommonSuffix(str1: string, str2: string): string {
  let i;

  // Unlike longestCommonPrefix, we need a special case to handle all scenarios
  // where we return the empty string since str1.slice(-0) will return the
  // entire string.
  if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {
    return '';
  }

  for (i = 0; i < str1.length && i < str2.length; i++) {
    if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) {
      return str1.slice(-i);
    }
  }
  return str1.slice(-i);
}

export function replacePrefix(string: string, oldPrefix: string, newPrefix: string): string {
  if (string.slice(0, oldPrefix.length) != oldPrefix) {
    throw Error(`string ${JSON.stringify(string)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`);
  }
  return newPrefix + string.slice(oldPrefix.length);
}

export function replaceSuffix(string: string, oldSuffix: string, newSuffix: string): string {
  if (!oldSuffix) {
    return string + newSuffix;
  }

  if (string.slice(-oldSuffix.length) != oldSuffix) {
    throw Error(`string ${JSON.stringify(string)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`);
  }
  return string.slice(0, -oldSuffix.length) + newSuffix;
}

export function removePrefix(string: string, oldPrefix: string): string {
  return replacePrefix(string, oldPrefix, '');
}

export function removeSuffix(string: string, oldSuffix: string): string {
  return replaceSuffix(string, oldSuffix, '');
}

export function maximumOverlap(string1: string, string2: string): string {
  return string2.slice(0, overlapCount(string1, string2));
}

// Nicked from https://stackoverflow.com/a/60422853/1709587
function overlapCount(a: string, b: string): number {
  // Deal with cases where the strings differ in length
  let startA = 0;
  if (a.length > b.length) { startA = a.length - b.length; }
  let endB = b.length;
  if (a.length < b.length) { endB = a.length; }
  // Create a back-reference for each index
  //   that should be followed in case of a mismatch.
  //   We only need B to make these references:
  const map = Array(endB);
  let k = 0; // Index that lags behind j
  map[0] = 0;
  for (let j = 1; j < endB; j++) {
      if (b[j] == b[k]) {
          map[j] = map[k]; // skip over the same character (optional optimisation)
      } else {
          map[j] = k;
      }
      while (k > 0 && b[j] != b[k]) { k = map[k]; }
      if (b[j] == b[k]) { k++; }
  }
  // Phase 2: use these references while iterating over A
  k = 0;
  for (let i = startA; i < a.length; i++) {
      while (k > 0 && a[i] != b[k]) { k = map[k]; }
      if (a[i] == b[k]) { k++; }
  }
  return k;
}


/**
 * Returns true if the string consistently uses Windows line endings.
 */
export function hasOnlyWinLineEndings(string: string): boolean {
  return string.includes('\r\n') && !string.startsWith('\n') && !string.match(/[^\r]\n/);
}

/**
 * Returns true if the string consistently uses Unix line endings.
 */
export function hasOnlyUnixLineEndings(string: string): boolean {
  return !string.includes('\r\n') && string.includes('\n');
}

/**
 * Split a string into segments using a word segmenter, merging consecutive
 * segments if they are both whitespace segments. Whitespace segments can
 * appear adjacent to one another for two reasons:
 * - newlines always get their own segment
 * - where a diacritic is attached to a whitespace character in the text, the
 *   segment ends after the diacritic, so e.g. " \u0300 " becomes two segments.
 * This function therefore runs the segmenter's .segment() method and then
 * merges consecutive segments of whitespace into a single part.
 */
export function segment(string: string, segmenter: Intl.Segmenter): string[] {
  const parts = [];
  for (const segmentObj of Array.from(segmenter.segment(string))) {
    const segment = segmentObj.segment;
    if (parts.length && (/\s/).test(parts[parts.length - 1]) && (/\s/).test(segment)) {
      parts[parts.length - 1] += segment;
    } else {
      parts.push(segment);
    }
  }
  return parts;
}

// The functions below take a `segmenter` argument so that, when called from
// diffWords when it is using a segmenter, they can use a notion of what
// constitutes "whitespace" that is consistent with the segmenter.
//
// USUALLY this will be identical to the result of the non-segmenter-based
// logic, but it differs in at least one case: when whitespace characters are
// modified by diacritics. A word segmenter considers these diacritics to be
// part of the whitespace, whereas our non-segmenter-based logic does not.
//
// Because the segmenter-based approach necessarily requires segmenting the
// entire string, we offer a leadingAndTrailingWs function to allow getting the
// whitespace prefix AND whitespace suffix with a single call to the segmenter,
// for efficiency's sake.

export function trailingWs(string: string, segmenter?: Intl.Segmenter): string {
  if (segmenter) {
    return leadingAndTrailingWs(string, segmenter)[1];
  }

  // Yes, this looks overcomplicated and dumb - why not replace the whole function with
  //     retu
Download .txt
gitextract_va69jomi/

├── .babelrc
├── .gitignore
├── .npmignore
├── .yarnrc.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── eslint.config.mjs
├── examples/
│   ├── node_example.js
│   └── web_example.html
├── karma.conf.js
├── package.json
├── release-notes.md
├── rollup.config.mjs
├── runtime.js
├── src/
│   ├── convert/
│   │   ├── dmp.ts
│   │   └── xml.ts
│   ├── diff/
│   │   ├── array.ts
│   │   ├── base.ts
│   │   ├── character.ts
│   │   ├── css.ts
│   │   ├── json.ts
│   │   ├── line.ts
│   │   ├── sentence.ts
│   │   └── word.ts
│   ├── index.ts
│   ├── patch/
│   │   ├── apply.ts
│   │   ├── create.ts
│   │   ├── line-endings.ts
│   │   ├── parse.ts
│   │   └── reverse.ts
│   ├── types.ts
│   └── util/
│       ├── array.ts
│       ├── distance-iterator.ts
│       ├── params.ts
│       └── string.ts
├── test/
│   ├── convert/
│   │   └── dmp.js
│   ├── diff/
│   │   ├── array.js
│   │   ├── character.js
│   │   ├── css.js
│   │   ├── json.js
│   │   ├── line.js
│   │   ├── sentence.js
│   │   └── word.js
│   ├── index.js
│   ├── patch/
│   │   ├── apply.js
│   │   ├── create.js
│   │   ├── line-endings.js
│   │   ├── parse.js
│   │   └── reverse.js
│   └── util/
│       └── string.js
├── test-d/
│   ├── diffCharsOverloads.test-d.ts
│   └── originalDefinitelyTypedTests.test-d.ts
└── tsconfig.json
Download .txt
SYMBOL INDEX (171 symbols across 24 files)

FILE: src/convert/dmp.ts
  type DmpOperation (line 3) | type DmpOperation = 1 | 0 | -1;
  function convertChangesToDMP (line 8) | function convertChangesToDMP<ValueT>(changes: ChangeObject<ValueT>[]): [...

FILE: src/convert/xml.ts
  function convertChangesToXML (line 6) | function convertChangesToXML(changes: ChangeObject<string>[]): string {
  function escapeHTML (line 27) | function escapeHTML(s: string): string {

FILE: src/diff/array.ts
  class ArrayDiff (line 4) | class ArrayDiff<T> extends Diff<T, Array<T>> {
    method tokenize (line 5) | tokenize(value: Array<T>) {
    method join (line 9) | join(value: Array<T>) {
    method removeEmpty (line 13) | removeEmpty(value: Array<T>) {
  function diffArrays (line 49) | function diffArrays<T>(

FILE: src/diff/base.ts
  type DraftChangeObject (line 9) | interface DraftChangeObject {
  type Path (line 19) | interface Path {
  class Diff (line 24) | class Diff<
    method diff (line 54) | diff(
    method diffWithOptionsObj (line 77) | private diffWithOptionsObj(
    method addToPath (line 215) | private addToPath(
    method extractCommon (line 236) | private extractCommon(
    method equals (line 266) | equals(left: TokenT, right: TokenT, options: AllDiffOptions): boolean {
    method removeEmpty (line 275) | removeEmpty(array: TokenT[]): TokenT[] {
    method castInput (line 286) | castInput(value: InputValueT, options: AllDiffOptions): ValueT {
    method tokenize (line 291) | tokenize(value: ValueT, options: AllDiffOptions): TokenT[] {
    method join (line 295) | join(chars: TokenT[]): ValueT {
    method postProcess (line 303) | postProcess(
    method useLongestToken (line 311) | get useLongestToken(): boolean {
    method buildValues (line 315) | private buildValues(

FILE: src/diff/character.ts
  class CharacterDiff (line 4) | class CharacterDiff extends Diff<string, string> {}
  function diffChars (line 40) | function diffChars(

FILE: src/diff/css.ts
  class CssDiff (line 4) | class CssDiff extends Diff<string, string> {
    method tokenize (line 5) | tokenize(value: string) {
  function diffCss (line 42) | function diffCss(oldStr: string, newStr: string, options?: any): undefin...

FILE: src/diff/json.ts
  class JsonDiff (line 5) | class JsonDiff extends Diff<string, string, string | object> {
    method useLongestToken (line 6) | get useLongestToken() {
    method castInput (line 14) | castInput(value: string | object, options: DiffJsonOptionsNonabortable...
    method equals (line 20) | equals(left: string, right: string, options: DiffJsonOptionsNonabortab...
  function diffJson (line 58) | function diffJson(oldStr: string | object, newStr: string | object, opti...
  function canonicalize (line 65) | function canonicalize(

FILE: src/diff/line.ts
  class LineDiff (line 5) | class LineDiff extends Diff<string, string> {
    method equals (line 8) | equals(left: string, right: string, options: DiffLinesOptionsAbortable...
  function diffLines (line 66) | function diffLines(oldStr: string, newStr: string, options?: any): undef...
  function diffTrimmedLines (line 101) | function diffTrimmedLines(oldStr: string, newStr: string, options?: any)...
  function tokenize (line 107) | function tokenize(value: string, options: DiffLinesOptionsAbortable | Di...

FILE: src/diff/sentence.ts
  function isSentenceEndPunct (line 11) | function isSentenceEndPunct(char: string) {
  class SentenceDiff (line 15) | class SentenceDiff extends Diff<string, string> {
    method tokenize (line 16) | tokenize(value: string) {
  function diffSentences (line 89) | function diffSentences(oldStr: string, newStr: string, options?: any): u...

FILE: src/diff/word.ts
  class WordDiff (line 55) | class WordDiff extends Diff<string, string> {
    method equals (line 56) | equals(left: string, right: string, options: DiffWordsOptionsAbortable...
    method tokenize (line 65) | tokenize(value: string, options: DiffWordsOptionsAbortable | DiffWords...
    method join (line 105) | join(tokens: string[]) {
    method postProcess (line 120) | postProcess(changes: ChangeObject<string>[], options: any) {
  function diffWords (line 184) | function diffWords(oldStr: string, newStr: string, options?: any): undef...
  function dedupeWhitespaceInChangeObjects (line 196) | function dedupeWhitespaceInChangeObjects(
  class WordsWithSpaceDiff (line 323) | class WordsWithSpaceDiff extends Diff<string, string> {
    method tokenize (line 324) | tokenize(value: string) {
  function diffWordsWithSpace (line 366) | function diffWordsWithSpace(oldStr: string, newStr: string, options?: an...

FILE: src/patch/apply.ts
  type ApplyPatchOptions (line 7) | interface ApplyPatchOptions {
  type ApplyHunkReturnType (line 27) | interface ApplyHunkReturnType {
  function applyPatch (line 54) | function applyPatch(
  function applyStructuredPatch (line 75) | function applyStructuredPatch(
  type ApplyPatchesOptions (line 322) | interface ApplyPatchesOptions extends ApplyPatchOptions {
  function applyPatches (line 340) | function applyPatches(uniDiff: string | StructuredPatch[], options: Appl...

FILE: src/patch/create.ts
  type StructuredPatchCallbackAbortable (line 4) | type StructuredPatchCallbackAbortable = (patch: StructuredPatch | undefi...
  type StructuredPatchCallbackNonabortable (line 5) | type StructuredPatchCallbackNonabortable = (patch: StructuredPatch) => v...
  type HeaderOptions (line 7) | interface HeaderOptions {
  constant INCLUDE_HEADERS (line 13) | const INCLUDE_HEADERS = {
  constant FILE_HEADERS_ONLY (line 18) | const FILE_HEADERS_ONLY = {
  constant OMIT_HEADERS (line 23) | const OMIT_HEADERS = {
  type _StructuredPatchOptionsAbortable (line 29) | interface _StructuredPatchOptionsAbortable extends Pick<DiffLinesOptions...
  type StructuredPatchOptionsAbortable (line 38) | type StructuredPatchOptionsAbortable = _StructuredPatchOptionsAbortable ...
  type StructuredPatchOptionsNonabortable (line 39) | interface StructuredPatchOptionsNonabortable extends Pick<DiffLinesOptio...
  type StructuredPatchCallbackOptionAbortable (line 43) | interface StructuredPatchCallbackOptionAbortable {
  type StructuredPatchCallbackOptionNonabortable (line 50) | interface StructuredPatchCallbackOptionNonabortable {
  type ChangeObjectPlusLines (line 60) | interface ChangeObjectPlusLines extends Partial<ChangeObject<string>> {
  function structuredPatch (line 121) | function structuredPatch(
  function formatPatch (line 279) | function formatPatch(patch: StructuredPatch | StructuredPatch[], headerO...
  type CreatePatchCallbackAbortable (line 330) | type CreatePatchCallbackAbortable = (patch: string | undefined) => void;
  type CreatePatchCallbackNonabortable (line 331) | type CreatePatchCallbackNonabortable = (patch: string) => void;
  type _CreatePatchOptionsAbortable (line 333) | interface _CreatePatchOptionsAbortable extends Pick<DiffLinesOptionsAbor...
  type CreatePatchOptionsAbortable (line 338) | type CreatePatchOptionsAbortable = _CreatePatchOptionsAbortable & Aborta...
  type CreatePatchOptionsNonabortable (line 339) | interface CreatePatchOptionsNonabortable extends Pick<DiffLinesOptionsNo...
  type CreatePatchCallbackOptionAbortable (line 344) | interface CreatePatchCallbackOptionAbortable {
  type CreatePatchCallbackOptionNonabortable (line 347) | interface CreatePatchCallbackOptionNonabortable {
  function createTwoFilesPatch (line 405) | function createTwoFilesPatch(
  function createPatch (line 497) | function createPatch(
  function splitLines (line 511) | function splitLines(text: string): string[] {

FILE: src/patch/line-endings.ts
  function unixToWin (line 6) | function unixToWin(patch: StructuredPatch | StructuredPatch[]): Structur...
  function winToUnix (line 34) | function winToUnix(patch: StructuredPatch | StructuredPatch[]): Structur...
  function isUnix (line 53) | function isUnix(patch: StructuredPatch | StructuredPatch[]): boolean {
  function isWin (line 67) | function isWin(patch: StructuredPatch | StructuredPatch[]): boolean {

FILE: src/patch/parse.ts
  function parsePatch (line 8) | function parsePatch(uniDiff: string): StructuredPatch[] {

FILE: src/patch/reverse.ts
  function reversePatch (line 10) | function reversePatch(structuredPatch: StructuredPatch | StructuredPatch...

FILE: src/types.ts
  type ChangeObject (line 1) | interface ChangeObject<ValueT> {
  type Change (line 25) | type Change = ChangeObject<string>;
  type ArrayChange (line 26) | type ArrayChange<T> = ChangeObject<T[]>;
  type CommonDiffOptions (line 28) | interface CommonDiffOptions {
  type TimeoutOption (line 35) | interface TimeoutOption {
  type MaxEditLengthOption (line 43) | interface MaxEditLengthOption {
  type AbortableDiffOptions (line 52) | type AbortableDiffOptions = TimeoutOption | MaxEditLengthOption;
  type DiffCallbackNonabortable (line 54) | type DiffCallbackNonabortable<T> = (result: ChangeObject<T>[]) => void;
  type DiffCallbackAbortable (line 55) | type DiffCallbackAbortable<T> = (result: ChangeObject<T>[] | undefined) ...
  type CallbackOptionNonabortable (line 57) | interface CallbackOptionNonabortable<T> {
  type CallbackOptionAbortable (line 64) | interface CallbackOptionAbortable<T> {
  type DiffArraysOptions (line 72) | interface DiffArraysOptions<T> extends CommonDiffOptions {
  type DiffArraysOptionsNonabortable (line 75) | interface DiffArraysOptionsNonabortable<T> extends DiffArraysOptions<T> {
  type DiffArraysOptionsAbortable (line 82) | type DiffArraysOptionsAbortable<T> = DiffArraysOptions<T> & AbortableDif...
  type DiffCharsOptions (line 85) | interface DiffCharsOptions extends CommonDiffOptions {
  type DiffCharsOptionsNonabortable (line 92) | interface DiffCharsOptionsNonabortable extends DiffCharsOptions {
  type DiffCharsOptionsAbortable (line 99) | type DiffCharsOptionsAbortable = DiffCharsOptions & AbortableDiffOptions...
  type DiffLinesOptions (line 101) | interface DiffLinesOptions extends CommonDiffOptions {
  type DiffLinesOptionsNonabortable (line 133) | interface DiffLinesOptionsNonabortable extends DiffLinesOptions {
  type DiffLinesOptionsAbortable (line 140) | type DiffLinesOptionsAbortable = DiffLinesOptions & AbortableDiffOptions...
  type DiffWordsOptions (line 143) | interface DiffWordsOptions extends CommonDiffOptions {
  type DiffWordsOptionsNonabortable (line 162) | interface DiffWordsOptionsNonabortable extends DiffWordsOptions {
  type DiffWordsOptionsAbortable (line 169) | type DiffWordsOptionsAbortable = DiffWordsOptions & AbortableDiffOptions...
  type DiffSentencesOptions (line 172) | interface DiffSentencesOptions extends CommonDiffOptions {}
  type DiffSentencesOptionsNonabortable (line 173) | interface DiffSentencesOptionsNonabortable extends DiffSentencesOptions {
  type DiffSentencesOptionsAbortable (line 180) | type DiffSentencesOptionsAbortable = DiffSentencesOptions & AbortableDif...
  type DiffJsonOptions (line 183) | interface DiffJsonOptions extends CommonDiffOptions {
  type DiffJsonOptionsNonabortable (line 194) | interface DiffJsonOptionsNonabortable extends DiffJsonOptions {
  type DiffJsonOptionsAbortable (line 201) | type DiffJsonOptionsAbortable = DiffJsonOptions & AbortableDiffOptions &...
  type DiffCssOptions (line 204) | interface DiffCssOptions extends CommonDiffOptions {}
  type DiffCssOptionsNonabortable (line 205) | interface DiffCssOptionsNonabortable extends DiffCssOptions {
  type DiffCssOptionsAbortable (line 212) | type DiffCssOptionsAbortable = DiffCssOptions & AbortableDiffOptions & P...
  type AllDiffOptions (line 220) | type AllDiffOptions =
  type StructuredPatch (line 227) | interface StructuredPatch {
  type StructuredPatchHunk (line 236) | interface StructuredPatchHunk {

FILE: src/util/array.ts
  function arrayEqual (line 1) | function arrayEqual(a: any[], b: any[]): boolean {
  function arrayStartsWith (line 9) | function arrayStartsWith(array: any[], start: any[]): boolean {

FILE: src/util/params.ts
  function generateOptions (line 1) | function generateOptions(

FILE: src/util/string.ts
  function longestCommonPrefix (line 1) | function longestCommonPrefix(str1: string, str2: string): string {
  function longestCommonSuffix (line 11) | function longestCommonSuffix(str1: string, str2: string): string {
  function replacePrefix (line 29) | function replacePrefix(string: string, oldPrefix: string, newPrefix: str...
  function replaceSuffix (line 36) | function replaceSuffix(string: string, oldSuffix: string, newSuffix: str...
  function removePrefix (line 47) | function removePrefix(string: string, oldPrefix: string): string {
  function removeSuffix (line 51) | function removeSuffix(string: string, oldSuffix: string): string {
  function maximumOverlap (line 55) | function maximumOverlap(string1: string, string2: string): string {
  function overlapCount (line 60) | function overlapCount(a: string, b: string): number {
  function hasOnlyWinLineEndings (line 94) | function hasOnlyWinLineEndings(string: string): boolean {
  function hasOnlyUnixLineEndings (line 101) | function hasOnlyUnixLineEndings(string: string): boolean {
  function segment (line 115) | function segment(string: string, segmenter: Intl.Segmenter): string[] {
  function trailingWs (line 142) | function trailingWs(string: string, segmenter?: Intl.Segmenter): string {
  function leadingWs (line 167) | function leadingWs(string: string, segmenter?: Intl.Segmenter): string {
  function leadingAndTrailingWs (line 177) | function leadingAndTrailingWs(

FILE: test-d/originalDefinitelyTypedTests.test-d.ts
  type DiffObj (line 55) | interface DiffObj {
  class LineDiffWithoutWhitespace (line 77) | class LineDiffWithoutWhitespace extends Diff.Diff<string, string> {
    method tokenize (line 78) | tokenize(value: string): any {
    method equals (line 82) | equals(left: string, right: string): boolean {
  function examineChanges (line 91) | function examineChanges(diff: Diff.Change[]) {
  function verifyPatchMethods (line 100) | function verifyPatchMethods(oldStr: string, newStr: string, uniDiff: Dif...
  function verifyApplyMethods (line 115) | function verifyApplyMethods(oldStr: string, newStr: string, uniDiffStr: ...

FILE: test/diff/array.js
  function comparator (line 66) | function comparator(left, right) {
  function comparator (line 92) | function comparator(left, right) {

FILE: test/diff/line.js
  function callback (line 73) | function callback(diffResult) {
  function stringify (line 170) | function stringify(value) {

FILE: test/patch/apply.js
  method compareLine (line 1351) | compareLine(lineNumber, line, operation, patchContent) {
  method loadFile (line 1680) | loadFile(index, callback) {
  method patched (line 1683) | patched(index, content, callback) {
  method complete (line 1686) | complete(err) {
  method loadFile (line 1698) | loadFile(index, callback) {
  method patched (line 1701) | patched(index, content, callback) {
  method loadFile (line 1713) | loadFile(index, callback) {
  method patched (line 1716) | patched(index, content, callback) {
  method loadFile (line 1728) | loadFile(index, callback) {
  method complete (line 1731) | complete(err) {
  method loadFile (line 1757) | loadFile(index, callback) {
  method patched (line 1760) | patched(index, content, callback) {
  method loadFile (line 1814) | loadFile(index, callback) {
  method patched (line 1817) | patched(index, content, callback) {

FILE: test/patch/create.js
  constant VERBOSE (line 7) | const VERBOSE = false;
  function log (line 8) | function log() {
  function nextRandom (line 203) | function nextRandom() {
  function stripSpace (line 427) | function stripSpace(value) {
Condensed preview — 54 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (438K chars).
[
  {
    "path": ".babelrc",
    "chars": 147,
    "preview": "{\n  \"sourceMaps\": \"inline\",\n  \"presets\": [\"@babel/preset-env\"],\n  \"env\": {\n    \"test\": {\n      \"plugins\": [\n        \"ist"
  },
  {
    "path": ".gitignore",
    "chars": 235,
    "preview": "coverage\nnode_modules\nlibesm\nlibcjs\ndist\n.nyc_output\n.vscode\n.zed\n\n# Per https://yarnpkg.com/getting-started/qa#which-fi"
  },
  {
    "path": ".npmignore",
    "chars": 226,
    "preview": ".babelrc\n.eslint.config.mjs\n.gitignore\n.npmignore\n.nyc_output\n.vscode\n.zed\ntest-d\ncomponents\ncoverage\nexamples\nimages\nin"
  },
  {
    "path": ".yarnrc.yml",
    "chars": 25,
    "preview": "nodeLinker: node-modules\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 984,
    "preview": "## Building and testing\n\n```\nyarn\nyarn test\n```\n\nTo run tests in a *browser* (for instance to test compatibility with Fi"
  },
  {
    "path": "LICENSE",
    "chars": 1546,
    "preview": "BSD 3-Clause License\n\nCopyright (c) 2009-2015, Kevin Decker <kpdecker@gmail.com>\nAll rights reserved.\n\nRedistribution an"
  },
  {
    "path": "README.md",
    "chars": 29130,
    "preview": "# jsdiff\n\nA JavaScript text differencing implementation. Try it out in the **[online demo](https://kpdecker.github.io/js"
  },
  {
    "path": "eslint.config.mjs",
    "chars": 5395,
    "preview": "// @ts-check\n\nimport eslint from '@eslint/js';\nimport tseslint from 'typescript-eslint';\nimport globals from \"globals\";\n"
  },
  {
    "path": "examples/node_example.js",
    "chars": 405,
    "preview": "require('colors');\nconst {diffChars} = require('diff');\n\nconst one = 'beep boop';\nconst other = 'beep boob blah';\n\nconst"
  },
  {
    "path": "examples/web_example.html",
    "chars": 897,
    "preview": "<!-- If you want to try this example from within the jsdiff repo, run\n     `yarn build` first to build ../dist/diff.js t"
  },
  {
    "path": "karma.conf.js",
    "chars": 579,
    "preview": "export default function(config) {\n  config.set({\n    basePath: '',\n\n    frameworks: ['mocha'],\n\n    files: [\n      'test"
  },
  {
    "path": "package.json",
    "chars": 3778,
    "preview": "{\n  \"name\": \"diff\",\n  \"version\": \"8.0.3\",\n  \"description\": \"A JavaScript text diff implementation.\",\n  \"keywords\": [\n   "
  },
  {
    "path": "release-notes.md",
    "chars": 39071,
    "preview": "# Release Notes\n\n## 8.0.4 (prerelease)\n\n- [#667](https://github.com/kpdecker/jsdiff/pull/667) - **fix another bug in `di"
  },
  {
    "path": "rollup.config.mjs",
    "chars": 259,
    "preview": "import pkg from './package.json' with { type: 'json' };\n\nexport default [\n  // browser-friendly UMD build\n  {\n    input:"
  },
  {
    "path": "runtime.js",
    "chars": 80,
    "preview": "require('@babel/register')({\n  ignore: ['libcjs', 'libesm', 'node_modules']\n});\n"
  },
  {
    "path": "src/convert/dmp.ts",
    "chars": 698,
    "preview": "import type {ChangeObject} from '../types.js';\n\ntype DmpOperation = 1 | 0 | -1;\n\n/**\n * converts a list of change object"
  },
  {
    "path": "src/convert/xml.ts",
    "chars": 789,
    "preview": "import type {ChangeObject} from '../types.js';\n\n/**\n * converts a list of change objects to a serialized XML format\n */\n"
  },
  {
    "path": "src/diff/array.ts",
    "chars": 1444,
    "preview": "import Diff from './base.js';\nimport type {ChangeObject, DiffArraysOptionsNonabortable, CallbackOptionNonabortable, Diff"
  },
  {
    "path": "src/diff/base.ts",
    "chars": 13429,
    "preview": "import type {ChangeObject, AllDiffOptions, AbortableDiffOptions, DiffCallbackNonabortable, CallbackOptionAbortable, Call"
  },
  {
    "path": "src/diff/character.ts",
    "chars": 1430,
    "preview": "import Diff from './base.js';\nimport type { ChangeObject, CallbackOptionAbortable, CallbackOptionNonabortable, DiffCallb"
  },
  {
    "path": "src/diff/css.ts",
    "chars": 1301,
    "preview": "import Diff from './base.js';\nimport type { ChangeObject, CallbackOptionAbortable, CallbackOptionNonabortable, DiffCallb"
  },
  {
    "path": "src/diff/json.ts",
    "chars": 4288,
    "preview": "import Diff from './base.js';\nimport type { ChangeObject, CallbackOptionAbortable, CallbackOptionNonabortable, DiffCallb"
  },
  {
    "path": "src/diff/line.ts",
    "chars": 4770,
    "preview": "import Diff from './base.js';\nimport type { ChangeObject, CallbackOptionAbortable, CallbackOptionNonabortable, DiffCallb"
  },
  {
    "path": "src/diff/sentence.ts",
    "chars": 3357,
    "preview": "import Diff from './base.js';\nimport type {\n  ChangeObject,\n  CallbackOptionAbortable,\n  CallbackOptionNonabortable,\n  D"
  },
  {
    "path": "src/diff/word.ts",
    "chars": 15579,
    "preview": "import Diff from './base.js';\nimport type { ChangeObject, CallbackOptionAbortable, CallbackOptionNonabortable, DiffCallb"
  },
  {
    "path": "src/index.ts",
    "chars": 3530,
    "preview": "/* See LICENSE file for terms of use */\n\n/*\n * Text diff implementation.\n *\n * This library supports the following APIs:"
  },
  {
    "path": "src/patch/apply.ts",
    "chars": 14389,
    "preview": "import {hasOnlyWinLineEndings, hasOnlyUnixLineEndings} from '../util/string.js';\nimport {isWin, isUnix, unixToWin, winTo"
  },
  {
    "path": "src/patch/create.ts",
    "chars": 17431,
    "preview": "import {diffLines} from '../diff/line.js';\nimport type { StructuredPatch, DiffLinesOptionsAbortable, DiffLinesOptionsNon"
  },
  {
    "path": "src/patch/line-endings.ts",
    "chars": 2890,
    "preview": "import type { StructuredPatch } from '../types.js';\n\nexport function unixToWin(patch: StructuredPatch): StructuredPatch;"
  },
  {
    "path": "src/patch/parse.ts",
    "chars": 5655,
    "preview": "import type { StructuredPatch } from '../types.js';\n\n/**\n * Parses a patch into structured data, in the same structure r"
  },
  {
    "path": "src/patch/reverse.ts",
    "chars": 1531,
    "preview": "import type { StructuredPatch } from '../types.js';\n\n/**\n * @param patch either a single structured patch object (as ret"
  },
  {
    "path": "src/types.ts",
    "chars": 12687,
    "preview": "export interface ChangeObject<ValueT> {\n  /**\n   * The concatenated content of all the tokens represented by this change"
  },
  {
    "path": "src/util/array.ts",
    "chars": 402,
    "preview": "export function arrayEqual(a: any[], b: any[]): boolean {\n  if (a.length !== b.length) {\n    return false;\n  }\n\n  return"
  },
  {
    "path": "src/util/distance-iterator.ts",
    "chars": 1399,
    "preview": "// Iterator that traverses in the range of [min, max], stepping\n// by distance from a given start position. I.e. for [0,"
  },
  {
    "path": "src/util/params.ts",
    "chars": 426,
    "preview": "export function generateOptions(\n  options: {[key: string]: any} | ((_: unknown) => void),\n  defaults: any\n): object {\n "
  },
  {
    "path": "src/util/string.ts",
    "chars": 7139,
    "preview": "export function longestCommonPrefix(str1: string, str2: string): string {\n  let i;\n  for (i = 0; i < str1.length && i < "
  },
  {
    "path": "test/convert/dmp.js",
    "chars": 463,
    "preview": "import {convertChangesToDMP} from '../../libesm/convert/dmp.js';\nimport {diffChars} from '../../libesm/diff/character.js"
  },
  {
    "path": "test/diff/array.js",
    "chars": 4443,
    "preview": "import {diffArrays} from '../../libesm/diff/array.js';\n\nimport {expect} from 'chai';\n\ndescribe('diff/array', function() "
  },
  {
    "path": "test/diff/character.js",
    "chars": 3386,
    "preview": "import {diffChars} from '../../libesm/diff/character.js';\nimport {convertChangesToXML} from '../../libesm/convert/xml.js"
  },
  {
    "path": "test/diff/css.js",
    "chars": 751,
    "preview": "import {diffCss} from '../../libesm/diff/css.js';\nimport {convertChangesToXML} from '../../libesm/convert/xml.js';\n\nimpo"
  },
  {
    "path": "test/diff/json.js",
    "chars": 10219,
    "preview": "import {diffJson, canonicalize} from '../../libesm/diff/json.js';\nimport {convertChangesToXML} from '../../libesm/conver"
  },
  {
    "path": "test/diff/line.js",
    "chars": 10282,
    "preview": "import {diffLines, diffTrimmedLines} from '../../libesm/diff/line.js';\nimport {convertChangesToXML} from '../../libesm/c"
  },
  {
    "path": "test/diff/sentence.js",
    "chars": 1728,
    "preview": "import {diffSentences, sentenceDiff} from '../../libesm/diff/sentence.js';\nimport {convertChangesToXML} from '../../libe"
  },
  {
    "path": "test/diff/word.js",
    "chars": 21864,
    "preview": "import {wordDiff, diffWords, diffWordsWithSpace} from '../../libesm/diff/word.js';\nimport {convertChangesToXML} from '.."
  },
  {
    "path": "test/index.js",
    "chars": 915,
    "preview": "import * as Diff from 'diff';\n\nimport {expect} from 'chai';\n\ndescribe('root exports', function() {\n  it('should export A"
  },
  {
    "path": "test/patch/apply.js",
    "chars": 54339,
    "preview": "import {applyPatch, applyPatches} from '../../libesm/patch/apply.js';\nimport {parsePatch} from '../../libesm/patch/parse"
  },
  {
    "path": "test/patch/create.js",
    "chars": 72945,
    "preview": "import {diffWords} from 'diff';\nimport {createPatch, createTwoFilesPatch, FILE_HEADERS_ONLY, formatPatch, INCLUDE_HEADER"
  },
  {
    "path": "test/patch/line-endings.js",
    "chars": 4481,
    "preview": "import {parsePatch} from '../../libesm/patch/parse.js';\nimport {formatPatch} from '../../libesm/patch/create.js';\nimport"
  },
  {
    "path": "test/patch/parse.js",
    "chars": 20821,
    "preview": "import {parsePatch} from '../../libesm/patch/parse.js';\nimport {createPatch} from '../../libesm/patch/create.js';\n\nimpor"
  },
  {
    "path": "test/patch/reverse.js",
    "chars": 4495,
    "preview": "import {applyPatch} from '../../libesm/patch/apply.js';\nimport {structuredPatch, formatPatch} from '../../libesm/patch/c"
  },
  {
    "path": "test/util/string.js",
    "chars": 4464,
    "preview": "import {longestCommonPrefix, longestCommonSuffix, replacePrefix, replaceSuffix, removePrefix, removeSuffix, maximumOverl"
  },
  {
    "path": "test-d/diffCharsOverloads.test-d.ts",
    "chars": 1025,
    "preview": "import {expectType} from 'tsd';\nimport {ChangeObject, diffChars} from '../libesm/index.js';\n\nconst result1 = diffChars('"
  },
  {
    "path": "test-d/originalDefinitelyTypedTests.test-d.ts",
    "chars": 5742,
    "preview": "/**\n * This file was copied from\n * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/diff/diff-tests"
  },
  {
    "path": "tsconfig.json",
    "chars": 1657,
    "preview": "{\n    \"include\": [\"src/*.ts\", \"src/**/*.ts\"],\n    \"compilerOptions\": {\n        \"rootDir\": \"src/\",\n        \"target\": \"es5"
  }
]

About this extraction

This page contains the full source code of the kpdecker/jsdiff GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 54 files (411.5 KB), approximately 121.6k tokens, and a symbol index with 171 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!