@inpageedit/core 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +55 -55
  3. package/dist/ActionButton-BgbTKTg7.js.map +1 -1
  4. package/dist/CheckBox-D3rHnX7I.js.map +1 -1
  5. package/dist/IconQuickEdit-CAL1HXIb.js.map +1 -1
  6. package/dist/InputBox-BV4m05Xs.js.map +1 -1
  7. package/dist/Preferences-Bg3J5Ur9.js.map +1 -1
  8. package/dist/RadioBox-nJqWsxW2.js.map +1 -1
  9. package/dist/components/index.js.map +1 -1
  10. package/dist/{index-COlXHFRg.js → index-9Z4ds-WM.js} +281 -268
  11. package/dist/index-9Z4ds-WM.js.map +1 -0
  12. package/dist/{index-DwyuBkCK.js → index-BB9MXkUv.js} +3 -3
  13. package/dist/index-BB9MXkUv.js.map +1 -0
  14. package/dist/{index-DBV8FBjA.js → index-BDVcDlsf.js} +2 -2
  15. package/dist/index-BDVcDlsf.js.map +1 -0
  16. package/dist/index-Bh70Udzi.js.map +1 -1
  17. package/dist/{index-C8dOYIIz.js → index-CADkQBg0.js} +2 -2
  18. package/dist/{index-C8dOYIIz.js.map → index-CADkQBg0.js.map} +1 -1
  19. package/dist/{index-CeXR4lOu.js → index-CBQsBfc2.js} +32 -34
  20. package/dist/{index-CeXR4lOu.js.map → index-CBQsBfc2.js.map} +1 -1
  21. package/dist/{index-mntCdHRr.js → index-CNsB3Vcb.js} +3 -3
  22. package/dist/{index-mntCdHRr.js.map → index-CNsB3Vcb.js.map} +1 -1
  23. package/dist/{index-9M1QcjCN.js → index-CYdxWw9g.js} +124 -123
  24. package/dist/index-CYdxWw9g.js.map +1 -0
  25. package/dist/index-CvhkVj_L.js.map +1 -1
  26. package/dist/{index-Ba7Wkale.js → index-D7SQwFxl.js} +2 -2
  27. package/dist/{index-Ba7Wkale.js.map → index-D7SQwFxl.js.map} +1 -1
  28. package/dist/{index-kRdAN8h3.js → index-DMNUP3fg.js} +2 -2
  29. package/dist/{index-kRdAN8h3.js.map → index-DMNUP3fg.js.map} +1 -1
  30. package/dist/{index-Tn22YSmW.js → index-G3k3kjCU.js} +2 -2
  31. package/dist/index-G3k3kjCU.js.map +1 -0
  32. package/dist/{index-OBerV4GU.js → index-dp6_MU68.js} +2 -2
  33. package/dist/index-dp6_MU68.js.map +1 -0
  34. package/dist/index-lZkYoUca.js.map +1 -1
  35. package/dist/index.js +1 -1
  36. package/dist/makeCallable-LDU0xZMJ.js.map +1 -1
  37. package/dist/noop-ClDc6zv4.js.map +1 -1
  38. package/dist/services/CurrentPageService.d.ts +1 -0
  39. package/dist/services/WikiMetadataService.d.ts +1 -1
  40. package/dist/style.css +1 -1
  41. package/lib/index.umd.js +26 -24
  42. package/lib/index.umd.js.map +1 -1
  43. package/lib/style.css +1 -1
  44. package/package.json +3 -3
  45. package/dist/index-9M1QcjCN.js.map +0 -1
  46. package/dist/index-COlXHFRg.js.map +0 -1
  47. package/dist/index-DBV8FBjA.js.map +0 -1
  48. package/dist/index-DwyuBkCK.js.map +0 -1
  49. package/dist/index-OBerV4GU.js.map +0 -1
  50. package/dist/index-Tn22YSmW.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index-C8dOYIIz.js","sources":["../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/base.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/character.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/util/string.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/word.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/util/params.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/line.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/sentence.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/css.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/json.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/array.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/patch/line-endings.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/patch/parse.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/util/distance-iterator.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/patch/apply.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/patch/reverse.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/patch/create.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/convert/dmp.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/convert/xml.js","../src/plugins/quick-diff/JsDiffService.ts","../src/components/MwUserLinks.tsx","../src/plugins/quick-diff/components/DiffTable.tsx","../src/components/utils.tsx","../src/plugins/quick-diff/PluginQuickDiffCore.tsx","../src/plugins/quick-diff/index.tsx"],"sourcesContent":["export default class Diff {\n diff(oldStr, newStr, \n // Type below is not accurate/complete - see above for full possibilities - but it compiles\n options = {}) {\n let callback;\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n else if ('callback' in options) {\n callback = options.callback;\n }\n // Allow subclasses to massage the input prior to running\n const oldString = this.castInput(oldStr, options);\n const newString = this.castInput(newStr, options);\n const oldTokens = this.removeEmpty(this.tokenize(oldString, options));\n const newTokens = this.removeEmpty(this.tokenize(newString, options));\n return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);\n }\n diffWithOptionsObj(oldTokens, newTokens, options, callback) {\n var _a;\n const done = (value) => {\n value = this.postProcess(value, options);\n if (callback) {\n setTimeout(function () { callback(value); }, 0);\n return undefined;\n }\n else {\n return value;\n }\n };\n const newLen = newTokens.length, oldLen = oldTokens.length;\n let editLength = 1;\n let maxEditLength = newLen + oldLen;\n if (options.maxEditLength != null) {\n maxEditLength = Math.min(maxEditLength, options.maxEditLength);\n }\n const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity;\n const abortAfterTimestamp = Date.now() + maxExecutionTime;\n const bestPath = [{ oldPos: -1, lastComponent: undefined }];\n // Seed editLength = 0, i.e. the content starts with the same values\n let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);\n if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n // Identity per the equality and tokenizer\n return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));\n }\n // Once we hit the right edge of the edit graph on some diagonal k, we can\n // definitely reach the end of the edit graph in no more than k edits, so\n // there's no point in considering any moves to diagonal k+1 any more (from\n // which we're guaranteed to need at least k+1 more edits).\n // Similarly, once we've reached the bottom of the edit graph, there's no\n // point considering moves to lower diagonals.\n // We record this fact by setting minDiagonalToConsider and\n // maxDiagonalToConsider to some finite value once we've hit the edge of\n // the edit graph.\n // This optimization is not faithful to the original algorithm presented in\n // Myers's paper, which instead pointlessly extends D-paths off the end of\n // the edit graph - see page 7 of Myers's paper which notes this point\n // explicitly and illustrates it with a diagram. This has major performance\n // implications for some common scenarios. For instance, to compute a diff\n // where the new text simply appends d characters on the end of the\n // original text of length n, the true Myers algorithm will take O(n+d^2)\n // time while this optimization needs only O(n+d) time.\n let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;\n // Main worker method. checks all permutations of a given edit length for acceptance.\n const execEditLength = () => {\n for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {\n let basePath;\n const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];\n if (removePath) {\n // No one else is going to attempt to use this value, clear it\n // @ts-expect-error - perf optimisation. This type-violating value will never be read.\n bestPath[diagonalPath - 1] = undefined;\n }\n let canAdd = false;\n if (addPath) {\n // what newPos will be after we do an insertion:\n const addPathNewPos = addPath.oldPos - diagonalPath;\n canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;\n }\n const canRemove = removePath && removePath.oldPos + 1 < oldLen;\n if (!canAdd && !canRemove) {\n // If this path is a terminal then prune\n // @ts-expect-error - perf optimisation. This type-violating value will never be read.\n bestPath[diagonalPath] = undefined;\n continue;\n }\n // Select the diagonal that we want to branch from. We select the prior\n // path whose position in the old string is the farthest from the origin\n // and does not pass the bounds of the diff graph\n if (!canRemove || (canAdd && removePath.oldPos < addPath.oldPos)) {\n basePath = this.addToPath(addPath, true, false, 0, options);\n }\n else {\n basePath = this.addToPath(removePath, false, true, 1, options);\n }\n newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);\n if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n // If we have hit the end of both strings, then we are done\n return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;\n }\n else {\n bestPath[diagonalPath] = basePath;\n if (basePath.oldPos + 1 >= oldLen) {\n maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);\n }\n if (newPos + 1 >= newLen) {\n minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);\n }\n }\n }\n editLength++;\n };\n // Performs the length of edit iteration. Is a bit fugly as this has to support the\n // sync and async mode which is never fun. Loops over execEditLength until a value\n // is produced, or until the edit length exceeds options.maxEditLength (if given),\n // in which case it will return undefined.\n if (callback) {\n (function exec() {\n setTimeout(function () {\n if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {\n return callback(undefined);\n }\n if (!execEditLength()) {\n exec();\n }\n }, 0);\n }());\n }\n else {\n while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {\n const ret = execEditLength();\n if (ret) {\n return ret;\n }\n }\n }\n }\n addToPath(path, added, removed, oldPosInc, options) {\n const last = path.lastComponent;\n if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent }\n };\n }\n else {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: { count: 1, added: added, removed: removed, previousComponent: last }\n };\n }\n }\n extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {\n const newLen = newTokens.length, oldLen = oldTokens.length;\n let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;\n while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {\n newPos++;\n oldPos++;\n commonCount++;\n if (options.oneChangePerToken) {\n basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };\n }\n }\n if (commonCount && !options.oneChangePerToken) {\n basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };\n }\n basePath.oldPos = oldPos;\n return newPos;\n }\n equals(left, right, options) {\n if (options.comparator) {\n return options.comparator(left, right);\n }\n else {\n return left === right\n || (!!options.ignoreCase && left.toLowerCase() === right.toLowerCase());\n }\n }\n removeEmpty(array) {\n const ret = [];\n for (let i = 0; i < array.length; i++) {\n if (array[i]) {\n ret.push(array[i]);\n }\n }\n return ret;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n castInput(value, options) {\n return value;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n tokenize(value, options) {\n return Array.from(value);\n }\n join(chars) {\n // Assumes ValueT is string, which is the case for most subclasses.\n // When it's false, e.g. in diffArrays, this method needs to be overridden (e.g. with a no-op)\n // Yes, the casts are verbose and ugly, because this pattern - of having the base class SORT OF\n // assume tokens and values are strings, but not completely - is weird and janky.\n return chars.join('');\n }\n postProcess(changeObjects, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n options) {\n return changeObjects;\n }\n get useLongestToken() {\n return false;\n }\n buildValues(lastComponent, newTokens, oldTokens) {\n // First we convert our linked list of components in reverse order to an\n // array in the right order:\n const components = [];\n let nextComponent;\n while (lastComponent) {\n components.push(lastComponent);\n nextComponent = lastComponent.previousComponent;\n delete lastComponent.previousComponent;\n lastComponent = nextComponent;\n }\n components.reverse();\n const componentLen = components.length;\n let componentPos = 0, newPos = 0, oldPos = 0;\n for (; componentPos < componentLen; componentPos++) {\n const component = components[componentPos];\n if (!component.removed) {\n if (!component.added && this.useLongestToken) {\n let value = newTokens.slice(newPos, newPos + component.count);\n value = value.map(function (value, i) {\n const oldValue = oldTokens[oldPos + i];\n return oldValue.length > value.length ? oldValue : value;\n });\n component.value = this.join(value);\n }\n else {\n component.value = this.join(newTokens.slice(newPos, newPos + component.count));\n }\n newPos += component.count;\n // Common case\n if (!component.added) {\n oldPos += component.count;\n }\n }\n else {\n component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));\n oldPos += component.count;\n }\n }\n return components;\n }\n}\n","import Diff from './base.js';\nclass CharacterDiff extends Diff {\n}\nexport const characterDiff = new CharacterDiff();\nexport function diffChars(oldStr, newStr, options) {\n return characterDiff.diff(oldStr, newStr, options);\n}\n","export function longestCommonPrefix(str1, str2) {\n let i;\n for (i = 0; i < str1.length && i < str2.length; i++) {\n if (str1[i] != str2[i]) {\n return str1.slice(0, i);\n }\n }\n return str1.slice(0, i);\n}\nexport function longestCommonSuffix(str1, str2) {\n let i;\n // Unlike longestCommonPrefix, we need a special case to handle all scenarios\n // where we return the empty string since str1.slice(-0) will return the\n // entire string.\n if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {\n return '';\n }\n for (i = 0; i < str1.length && i < str2.length; i++) {\n if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) {\n return str1.slice(-i);\n }\n }\n return str1.slice(-i);\n}\nexport function replacePrefix(string, oldPrefix, newPrefix) {\n if (string.slice(0, oldPrefix.length) != oldPrefix) {\n throw Error(`string ${JSON.stringify(string)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`);\n }\n return newPrefix + string.slice(oldPrefix.length);\n}\nexport function replaceSuffix(string, oldSuffix, newSuffix) {\n if (!oldSuffix) {\n return string + newSuffix;\n }\n if (string.slice(-oldSuffix.length) != oldSuffix) {\n throw Error(`string ${JSON.stringify(string)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`);\n }\n return string.slice(0, -oldSuffix.length) + newSuffix;\n}\nexport function removePrefix(string, oldPrefix) {\n return replacePrefix(string, oldPrefix, '');\n}\nexport function removeSuffix(string, oldSuffix) {\n return replaceSuffix(string, oldSuffix, '');\n}\nexport function maximumOverlap(string1, string2) {\n return string2.slice(0, overlapCount(string1, string2));\n}\n// Nicked from https://stackoverflow.com/a/60422853/1709587\nfunction overlapCount(a, b) {\n // Deal with cases where the strings differ in length\n let startA = 0;\n if (a.length > b.length) {\n startA = a.length - b.length;\n }\n let endB = b.length;\n if (a.length < b.length) {\n endB = a.length;\n }\n // Create a back-reference for each index\n // that should be followed in case of a mismatch.\n // We only need B to make these references:\n const map = Array(endB);\n let k = 0; // Index that lags behind j\n map[0] = 0;\n for (let j = 1; j < endB; j++) {\n if (b[j] == b[k]) {\n map[j] = map[k]; // skip over the same character (optional optimisation)\n }\n else {\n map[j] = k;\n }\n while (k > 0 && b[j] != b[k]) {\n k = map[k];\n }\n if (b[j] == b[k]) {\n k++;\n }\n }\n // Phase 2: use these references while iterating over A\n k = 0;\n for (let i = startA; i < a.length; i++) {\n while (k > 0 && a[i] != b[k]) {\n k = map[k];\n }\n if (a[i] == b[k]) {\n k++;\n }\n }\n return k;\n}\n/**\n * Returns true if the string consistently uses Windows line endings.\n */\nexport function hasOnlyWinLineEndings(string) {\n return string.includes('\\r\\n') && !string.startsWith('\\n') && !string.match(/[^\\r]\\n/);\n}\n/**\n * Returns true if the string consistently uses Unix line endings.\n */\nexport function hasOnlyUnixLineEndings(string) {\n return !string.includes('\\r\\n') && string.includes('\\n');\n}\nexport function trailingWs(string) {\n // Yes, this looks overcomplicated and dumb - why not replace the whole function with\n // return string match(/\\s*$/)[0]\n // you ask? Because:\n // 1. the trap described at https://markamery.com/blog/quadratic-time-regexes/ would mean doing\n // this would cause this function to take O(n²) time in the worst case (specifically when\n // there is a massive run of NON-TRAILING whitespace in `string`), and\n // 2. the fix proposed in the same blog post, of using a negative lookbehind, is incompatible\n // with old Safari versions that we'd like to not break if possible (see\n // https://github.com/kpdecker/jsdiff/pull/550)\n // It feels absurd to do this with an explicit loop instead of a regex, but I really can't see a\n // better way that doesn't result in broken behaviour.\n let i;\n for (i = string.length - 1; i >= 0; i--) {\n if (!string[i].match(/\\s/)) {\n break;\n }\n }\n return string.substring(i + 1);\n}\nexport function leadingWs(string) {\n // Thankfully the annoying considerations described in trailingWs don't apply here:\n const match = string.match(/^\\s*/);\n return match ? match[0] : '';\n}\n","import Diff from './base.js';\nimport { longestCommonPrefix, longestCommonSuffix, replacePrefix, replaceSuffix, removePrefix, removeSuffix, maximumOverlap, leadingWs, trailingWs } from '../util/string.js';\n// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode\n//\n// Ranges and exceptions:\n// Latin-1 Supplement, 0080–00FF\n// - U+00D7 × Multiplication sign\n// - U+00F7 ÷ Division sign\n// Latin Extended-A, 0100–017F\n// Latin Extended-B, 0180–024F\n// IPA Extensions, 0250–02AF\n// Spacing Modifier Letters, 02B0–02FF\n// - U+02C7 ˇ &#711; Caron\n// - U+02D8 ˘ &#728; Breve\n// - U+02D9 ˙ &#729; Dot Above\n// - U+02DA ˚ &#730; Ring Above\n// - U+02DB ˛ &#731; Ogonek\n// - U+02DC ˜ &#732; Small Tilde\n// - U+02DD ˝ &#733; Double Acute Accent\n// Latin Extended Additional, 1E00–1EFF\nconst extendedWordChars = 'a-zA-Z0-9_\\\\u{C0}-\\\\u{FF}\\\\u{D8}-\\\\u{F6}\\\\u{F8}-\\\\u{2C6}\\\\u{2C8}-\\\\u{2D7}\\\\u{2DE}-\\\\u{2FF}\\\\u{1E00}-\\\\u{1EFF}';\n// Each token is one of the following:\n// - A punctuation mark plus the surrounding whitespace\n// - A word plus the surrounding whitespace\n// - Pure whitespace (but only in the special case where this the entire text\n// is just whitespace)\n//\n// We have to include surrounding whitespace in the tokens because the two\n// alternative approaches produce horribly broken results:\n// * If we just discard the whitespace, we can't fully reproduce the original\n// text from the sequence of tokens and any attempt to render the diff will\n// get the whitespace wrong.\n// * If we have separate tokens for whitespace, then in a typical text every\n// second token will be a single space character. But this often results in\n// the optimal diff between two texts being a perverse one that preserves\n// the spaces between words but deletes and reinserts actual common words.\n// See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640\n// for an example.\n//\n// Keeping the surrounding whitespace of course has implications for .equals\n// and .join, not just .tokenize.\n// This regex does NOT fully implement the tokenization rules described above.\n// Instead, it gives runs of whitespace their own \"token\". The tokenize method\n// then handles stitching whitespace tokens onto adjacent word or punctuation\n// tokens.\nconst tokenizeIncludingWhitespace = new RegExp(`[${extendedWordChars}]+|\\\\s+|[^${extendedWordChars}]`, 'ug');\nclass WordDiff extends Diff {\n equals(left, right, options) {\n if (options.ignoreCase) {\n left = left.toLowerCase();\n right = right.toLowerCase();\n }\n return left.trim() === right.trim();\n }\n tokenize(value, options = {}) {\n let parts;\n if (options.intlSegmenter) {\n const segmenter = options.intlSegmenter;\n if (segmenter.resolvedOptions().granularity != 'word') {\n throw new Error('The segmenter passed must have a granularity of \"word\"');\n }\n parts = Array.from(segmenter.segment(value), segment => segment.segment);\n }\n else {\n parts = value.match(tokenizeIncludingWhitespace) || [];\n }\n const tokens = [];\n let prevPart = null;\n parts.forEach(part => {\n if ((/\\s/).test(part)) {\n if (prevPart == null) {\n tokens.push(part);\n }\n else {\n tokens.push(tokens.pop() + part);\n }\n }\n else if (prevPart != null && (/\\s/).test(prevPart)) {\n if (tokens[tokens.length - 1] == prevPart) {\n tokens.push(tokens.pop() + part);\n }\n else {\n tokens.push(prevPart + part);\n }\n }\n else {\n tokens.push(part);\n }\n prevPart = part;\n });\n return tokens;\n }\n join(tokens) {\n // Tokens being joined here will always have appeared consecutively in the\n // same text, so we can simply strip off the leading whitespace from all the\n // tokens except the first (and except any whitespace-only tokens - but such\n // a token will always be the first and only token anyway) and then join them\n // and the whitespace around words and punctuation will end up correct.\n return tokens.map((token, i) => {\n if (i == 0) {\n return token;\n }\n else {\n return token.replace((/^\\s+/), '');\n }\n }).join('');\n }\n postProcess(changes, options) {\n if (!changes || options.oneChangePerToken) {\n return changes;\n }\n let lastKeep = null;\n // Change objects representing any insertion or deletion since the last\n // \"keep\" change object. There can be at most one of each.\n let insertion = null;\n let deletion = null;\n changes.forEach(change => {\n if (change.added) {\n insertion = change;\n }\n else if (change.removed) {\n deletion = change;\n }\n else {\n if (insertion || deletion) { // May be false at start of text\n dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change);\n }\n lastKeep = change;\n insertion = null;\n deletion = null;\n }\n });\n if (insertion || deletion) {\n dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null);\n }\n return changes;\n }\n}\nexport const wordDiff = new WordDiff();\nexport function diffWords(oldStr, newStr, options) {\n // This option has never been documented and never will be (it's clearer to\n // just call `diffWordsWithSpace` directly if you need that behavior), but\n // has existed in jsdiff for a long time, so we retain support for it here\n // for the sake of backwards compatibility.\n if ((options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) {\n return diffWordsWithSpace(oldStr, newStr, options);\n }\n return wordDiff.diff(oldStr, newStr, options);\n}\nfunction dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) {\n // Before returning, we tidy up the leading and trailing whitespace of the\n // change objects to eliminate cases where trailing whitespace in one object\n // is repeated as leading whitespace in the next.\n // Below are examples of the outcomes we want here to explain the code.\n // I=insert, K=keep, D=delete\n // 1. diffing 'foo bar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'\n // After cleanup, we want: K:'foo ' D:'bar ' K:'baz'\n //\n // 2. Diffing 'foo bar baz' vs 'foo qux baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz'\n // After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz'\n //\n // 3. Diffing 'foo\\nbar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:'\\nbar ' K:' baz'\n // After cleanup, we want K'foo' D:'\\nbar' K:' baz'\n //\n // 4. Diffing 'foo baz' vs 'foo\\nbar baz'\n // Prior to cleanup, we have K:'foo\\n' I:'\\nbar ' K:' baz'\n // After cleanup, we ideally want K'foo' I:'\\nbar' K:' baz'\n // but don't actually manage this currently (the pre-cleanup change\n // objects don't contain enough information to make it possible).\n //\n // 5. Diffing 'foo bar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'\n // After cleanup, we want K:'foo ' D:' bar ' K:'baz'\n //\n // Our handling is unavoidably imperfect in the case where there's a single\n // indel between keeps and the whitespace has changed. For instance, consider\n // diffing 'foo\\tbar\\nbaz' vs 'foo baz'. Unless we create an extra change\n // object to represent the insertion of the space character (which isn't even\n // a token), we have no way to avoid losing information about the texts'\n // original whitespace in the result we return. Still, we do our best to\n // output something that will look sensible if we e.g. print it with\n // insertions in green and deletions in red.\n // Between two \"keep\" change objects (or before the first or after the last\n // change object), we can have either:\n // * A \"delete\" followed by an \"insert\"\n // * Just an \"insert\"\n // * Just a \"delete\"\n // We handle the three cases separately.\n if (deletion && insertion) {\n const oldWsPrefix = leadingWs(deletion.value);\n const oldWsSuffix = trailingWs(deletion.value);\n const newWsPrefix = leadingWs(insertion.value);\n const newWsSuffix = trailingWs(insertion.value);\n if (startKeep) {\n const commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix);\n startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix);\n deletion.value = removePrefix(deletion.value, commonWsPrefix);\n insertion.value = removePrefix(insertion.value, commonWsPrefix);\n }\n if (endKeep) {\n const commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix);\n endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix);\n deletion.value = removeSuffix(deletion.value, commonWsSuffix);\n insertion.value = removeSuffix(insertion.value, commonWsSuffix);\n }\n }\n else if (insertion) {\n // The whitespaces all reflect what was in the new text rather than\n // the old, so we essentially have no information about whitespace\n // insertion or deletion. We just want to dedupe the whitespace.\n // We do that by having each change object keep its trailing\n // whitespace and deleting duplicate leading whitespace where\n // present.\n if (startKeep) {\n const ws = leadingWs(insertion.value);\n insertion.value = insertion.value.substring(ws.length);\n }\n if (endKeep) {\n const ws = leadingWs(endKeep.value);\n endKeep.value = endKeep.value.substring(ws.length);\n }\n // otherwise we've got a deletion and no insertion\n }\n else if (startKeep && endKeep) {\n const newWsFull = leadingWs(endKeep.value), delWsStart = leadingWs(deletion.value), delWsEnd = trailingWs(deletion.value);\n // Any whitespace that comes straight after startKeep in both the old and\n // new texts, assign to startKeep and remove from the deletion.\n const newWsStart = longestCommonPrefix(newWsFull, delWsStart);\n deletion.value = removePrefix(deletion.value, newWsStart);\n // Any whitespace that comes straight before endKeep in both the old and\n // new texts, and hasn't already been assigned to startKeep, assign to\n // endKeep and remove from the deletion.\n const newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd);\n deletion.value = removeSuffix(deletion.value, newWsEnd);\n endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd);\n // If there's any whitespace from the new text that HASN'T already been\n // assigned, assign it to the start:\n startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length));\n }\n else if (endKeep) {\n // We are at the start of the text. Preserve all the whitespace on\n // endKeep, and just remove whitespace from the end of deletion to the\n // extent that it overlaps with the start of endKeep.\n const endKeepWsPrefix = leadingWs(endKeep.value);\n const deletionWsSuffix = trailingWs(deletion.value);\n const overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);\n deletion.value = removeSuffix(deletion.value, overlap);\n }\n else if (startKeep) {\n // We are at the END of the text. Preserve all the whitespace on\n // startKeep, and just remove whitespace from the start of deletion to\n // the extent that it overlaps with the end of startKeep.\n const startKeepWsSuffix = trailingWs(startKeep.value);\n const deletionWsPrefix = leadingWs(deletion.value);\n const overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix);\n deletion.value = removePrefix(deletion.value, overlap);\n }\n}\nclass WordsWithSpaceDiff extends Diff {\n tokenize(value) {\n // Slightly different to the tokenizeIncludingWhitespace regex used above in\n // that this one treats each individual newline as a distinct tokens, rather\n // than merging them into other surrounding whitespace. This was requested\n // in https://github.com/kpdecker/jsdiff/issues/180 &\n // https://github.com/kpdecker/jsdiff/issues/211\n const regex = new RegExp(`(\\\\r?\\\\n)|[${extendedWordChars}]+|[^\\\\S\\\\n\\\\r]+|[^${extendedWordChars}]`, 'ug');\n return value.match(regex) || [];\n }\n}\nexport const wordsWithSpaceDiff = new WordsWithSpaceDiff();\nexport function diffWordsWithSpace(oldStr, newStr, options) {\n return wordsWithSpaceDiff.diff(oldStr, newStr, options);\n}\n","export function generateOptions(options, defaults) {\n if (typeof options === 'function') {\n defaults.callback = options;\n }\n else if (options) {\n for (const name in options) {\n /* istanbul ignore else */\n if (Object.prototype.hasOwnProperty.call(options, name)) {\n defaults[name] = options[name];\n }\n }\n }\n return defaults;\n}\n","import Diff from './base.js';\nimport { generateOptions } from '../util/params.js';\nclass LineDiff extends Diff {\n constructor() {\n super(...arguments);\n this.tokenize = tokenize;\n }\n equals(left, right, options) {\n // If we're ignoring whitespace, we need to normalise lines by stripping\n // whitespace before checking equality. (This has an annoying interaction\n // with newlineIsToken that requires special handling: if newlines get their\n // own token, then we DON'T want to trim the *newline* tokens down to empty\n // strings, since this would cause us to treat whitespace-only line content\n // as equal to a separator between lines, which would be weird and\n // inconsistent with the documented behavior of the options.)\n if (options.ignoreWhitespace) {\n if (!options.newlineIsToken || !left.includes('\\n')) {\n left = left.trim();\n }\n if (!options.newlineIsToken || !right.includes('\\n')) {\n right = right.trim();\n }\n }\n else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {\n if (left.endsWith('\\n')) {\n left = left.slice(0, -1);\n }\n if (right.endsWith('\\n')) {\n right = right.slice(0, -1);\n }\n }\n return super.equals(left, right, options);\n }\n}\nexport const lineDiff = new LineDiff();\nexport function diffLines(oldStr, newStr, options) {\n return lineDiff.diff(oldStr, newStr, options);\n}\nexport function diffTrimmedLines(oldStr, newStr, options) {\n options = generateOptions(options, { ignoreWhitespace: true });\n return lineDiff.diff(oldStr, newStr, options);\n}\n// Exported standalone so it can be used from jsonDiff too.\nexport function tokenize(value, options) {\n if (options.stripTrailingCr) {\n // remove one \\r before \\n to match GNU diff's --strip-trailing-cr behavior\n value = value.replace(/\\r\\n/g, '\\n');\n }\n const retLines = [], linesAndNewlines = value.split(/(\\n|\\r\\n)/);\n // Ignore the final empty token that occurs if the string ends with a new line\n if (!linesAndNewlines[linesAndNewlines.length - 1]) {\n linesAndNewlines.pop();\n }\n // Merge the content and line separators into single tokens\n for (let i = 0; i < linesAndNewlines.length; i++) {\n const line = linesAndNewlines[i];\n if (i % 2 && !options.newlineIsToken) {\n retLines[retLines.length - 1] += line;\n }\n else {\n retLines.push(line);\n }\n }\n return retLines;\n}\n","import Diff from './base.js';\nfunction isSentenceEndPunct(char) {\n return char == '.' || char == '!' || char == '?';\n}\nclass SentenceDiff extends Diff {\n tokenize(value) {\n var _a;\n // If in future we drop support for environments that don't support lookbehinds, we can replace\n // this entire function with:\n // return value.split(/(?<=[.!?])(\\s+|$)/);\n // but until then, for similar reasons to the trailingWs function in string.ts, we are forced\n // to do this verbosely \"by hand\" instead of using a regex.\n const result = [];\n let tokenStartI = 0;\n for (let i = 0; i < value.length; i++) {\n if (i == value.length - 1) {\n result.push(value.slice(tokenStartI));\n break;\n }\n if (isSentenceEndPunct(value[i]) && value[i + 1].match(/\\s/)) {\n // We've hit a sentence break - i.e. a punctuation mark followed by whitespace.\n // We now want to push TWO tokens to the result:\n // 1. the sentence\n result.push(value.slice(tokenStartI, i + 1));\n // 2. the whitespace\n i = tokenStartI = i + 1;\n while ((_a = value[i + 1]) === null || _a === void 0 ? void 0 : _a.match(/\\s/)) {\n i++;\n }\n result.push(value.slice(tokenStartI, i + 1));\n // Then the next token (a sentence) starts on the character after the whitespace.\n // (It's okay if this is off the end of the string - then the outer loop will terminate\n // here anyway.)\n tokenStartI = i + 1;\n }\n }\n return result;\n }\n}\nexport const sentenceDiff = new SentenceDiff();\nexport function diffSentences(oldStr, newStr, options) {\n return sentenceDiff.diff(oldStr, newStr, options);\n}\n","import Diff from './base.js';\nclass CssDiff extends Diff {\n tokenize(value) {\n return value.split(/([{}:;,]|\\s+)/);\n }\n}\nexport const cssDiff = new CssDiff();\nexport function diffCss(oldStr, newStr, options) {\n return cssDiff.diff(oldStr, newStr, options);\n}\n","import Diff from './base.js';\nimport { tokenize } from './line.js';\nclass JsonDiff extends Diff {\n constructor() {\n super(...arguments);\n this.tokenize = tokenize;\n }\n get useLongestToken() {\n // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a\n // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:\n return true;\n }\n castInput(value, options) {\n const { undefinedReplacement, stringifyReplacer = (k, v) => typeof v === 'undefined' ? undefinedReplacement : v } = options;\n return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), null, ' ');\n }\n equals(left, right, options) {\n return super.equals(left.replace(/,([\\r\\n])/g, '$1'), right.replace(/,([\\r\\n])/g, '$1'), options);\n }\n}\nexport const jsonDiff = new JsonDiff();\nexport function diffJson(oldStr, newStr, options) {\n return jsonDiff.diff(oldStr, newStr, options);\n}\n// This function handles the presence of circular references by bailing out when encountering an\n// object that is already on the \"stack\" of items being processed. Accepts an optional replacer\nexport function canonicalize(obj, stack, replacementStack, replacer, key) {\n stack = stack || [];\n replacementStack = replacementStack || [];\n if (replacer) {\n obj = replacer(key === undefined ? '' : key, obj);\n }\n let i;\n for (i = 0; i < stack.length; i += 1) {\n if (stack[i] === obj) {\n return replacementStack[i];\n }\n }\n let canonicalizedObj;\n if ('[object Array]' === Object.prototype.toString.call(obj)) {\n stack.push(obj);\n canonicalizedObj = new Array(obj.length);\n replacementStack.push(canonicalizedObj);\n for (i = 0; i < obj.length; i += 1) {\n canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, String(i));\n }\n stack.pop();\n replacementStack.pop();\n return canonicalizedObj;\n }\n if (obj && obj.toJSON) {\n obj = obj.toJSON();\n }\n if (typeof obj === 'object' && obj !== null) {\n stack.push(obj);\n canonicalizedObj = {};\n replacementStack.push(canonicalizedObj);\n const sortedKeys = [];\n let key;\n for (key in obj) {\n /* istanbul ignore else */\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n sortedKeys.push(key);\n }\n }\n sortedKeys.sort();\n for (i = 0; i < sortedKeys.length; i += 1) {\n key = sortedKeys[i];\n canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack, replacer, key);\n }\n stack.pop();\n replacementStack.pop();\n }\n else {\n canonicalizedObj = obj;\n }\n return canonicalizedObj;\n}\n","import Diff from './base.js';\nclass ArrayDiff extends Diff {\n tokenize(value) {\n return value.slice();\n }\n join(value) {\n return value;\n }\n removeEmpty(value) {\n return value;\n }\n}\nexport const arrayDiff = new ArrayDiff();\nexport function diffArrays(oldArr, newArr, options) {\n return arrayDiff.diff(oldArr, newArr, options);\n}\n","export function unixToWin(patch) {\n if (Array.isArray(patch)) {\n // It would be cleaner if instead of the line below we could just write\n // return patch.map(unixToWin)\n // but mysteriously TypeScript (v5.7.3 at the time of writing) does not like this and it will\n // refuse to compile, thinking that unixToWin could then return StructuredPatch[][] and the\n // result would be incompatible with the overload signatures.\n // See bug report at https://github.com/microsoft/TypeScript/issues/61398.\n return patch.map(p => unixToWin(p));\n }\n return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line, i) => {\n var _a;\n return (line.startsWith('\\\\') || line.endsWith('\\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\\\')))\n ? line\n : line + '\\r';\n }) }))) });\n}\nexport function winToUnix(patch) {\n if (Array.isArray(patch)) {\n // (See comment above equivalent line in unixToWin)\n return patch.map(p => winToUnix(p));\n }\n return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map(line => line.endsWith('\\r') ? line.substring(0, line.length - 1) : line) }))) });\n}\n/**\n * Returns true if the patch consistently uses Unix line endings (or only involves one line and has\n * no line endings).\n */\nexport function isUnix(patch) {\n if (!Array.isArray(patch)) {\n patch = [patch];\n }\n return !patch.some(index => index.hunks.some(hunk => hunk.lines.some(line => !line.startsWith('\\\\') && line.endsWith('\\r'))));\n}\n/**\n * Returns true if the patch uses Windows line endings and only Windows line endings.\n */\nexport function isWin(patch) {\n if (!Array.isArray(patch)) {\n patch = [patch];\n }\n return patch.some(index => index.hunks.some(hunk => hunk.lines.some(line => line.endsWith('\\r'))))\n && patch.every(index => index.hunks.every(hunk => hunk.lines.every((line, i) => { var _a; return line.startsWith('\\\\') || line.endsWith('\\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\\\')); })));\n}\n","/**\n * Parses a patch into structured data, in the same structure returned by `structuredPatch`.\n *\n * @return a JSON object representation of the a patch, suitable for use with the `applyPatch` method.\n */\nexport function parsePatch(uniDiff) {\n const diffstr = uniDiff.split(/\\n/), list = [];\n let i = 0;\n function parseIndex() {\n const index = {};\n list.push(index);\n // Parse diff metadata\n while (i < diffstr.length) {\n const line = diffstr[i];\n // File header found, end parsing diff metadata\n if ((/^(---|\\+\\+\\+|@@)\\s/).test(line)) {\n break;\n }\n // Diff index\n const header = (/^(?:Index:|diff(?: -r \\w+)+)\\s+(.+?)\\s*$/).exec(line);\n if (header) {\n index.index = header[1];\n }\n i++;\n }\n // Parse file headers if they are defined. Unified diff requires them, but\n // there's no technical issues to have an isolated hunk without file header\n parseFileHeader(index);\n parseFileHeader(index);\n // Parse hunks\n index.hunks = [];\n while (i < diffstr.length) {\n const line = diffstr[i];\n if ((/^(Index:\\s|diff\\s|---\\s|\\+\\+\\+\\s|===================================================================)/).test(line)) {\n break;\n }\n else if ((/^@@/).test(line)) {\n index.hunks.push(parseHunk());\n }\n else if (line) {\n throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(line));\n }\n else {\n i++;\n }\n }\n }\n // Parses the --- and +++ headers, if none are found, no lines\n // are consumed.\n function parseFileHeader(index) {\n const fileHeader = (/^(---|\\+\\+\\+)\\s+(.*)\\r?$/).exec(diffstr[i]);\n if (fileHeader) {\n const data = fileHeader[2].split('\\t', 2), header = (data[1] || '').trim();\n let fileName = data[0].replace(/\\\\\\\\/g, '\\\\');\n if ((/^\".*\"$/).test(fileName)) {\n fileName = fileName.substr(1, fileName.length - 2);\n }\n if (fileHeader[1] === '---') {\n index.oldFileName = fileName;\n index.oldHeader = header;\n }\n else {\n index.newFileName = fileName;\n index.newHeader = header;\n }\n i++;\n }\n }\n // Parses a hunk\n // This assumes that we are at the start of a hunk.\n function parseHunk() {\n var _a;\n const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/);\n const hunk = {\n oldStart: +chunkHeader[1],\n oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],\n newStart: +chunkHeader[3],\n newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],\n lines: []\n };\n // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n if (hunk.oldLines === 0) {\n hunk.oldStart += 1;\n }\n if (hunk.newLines === 0) {\n hunk.newStart += 1;\n }\n let addCount = 0, removeCount = 0;\n for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a = diffstr[i]) === null || _a === void 0 ? void 0 : _a.startsWith('\\\\'))); i++) {\n const operation = (diffstr[i].length == 0 && i != (diffstr.length - 1)) ? ' ' : diffstr[i][0];\n if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\\\') {\n hunk.lines.push(diffstr[i]);\n if (operation === '+') {\n addCount++;\n }\n else if (operation === '-') {\n removeCount++;\n }\n else if (operation === ' ') {\n addCount++;\n removeCount++;\n }\n }\n else {\n throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`);\n }\n }\n // Handle the empty block count case\n if (!addCount && hunk.newLines === 1) {\n hunk.newLines = 0;\n }\n if (!removeCount && hunk.oldLines === 1) {\n hunk.oldLines = 0;\n }\n // Perform sanity checking\n if (addCount !== hunk.newLines) {\n throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n if (removeCount !== hunk.oldLines) {\n throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n return hunk;\n }\n while (i < diffstr.length) {\n parseIndex();\n }\n return list;\n}\n","// Iterator that traverses in the range of [min, max], stepping\n// by distance from a given start position. I.e. for [0, 4], with\n// start of 2, this will iterate 2, 3, 1, 4, 0.\nexport default function (start, minLine, maxLine) {\n let wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1;\n return function iterator() {\n if (wantForward && !forwardExhausted) {\n if (backwardExhausted) {\n localOffset++;\n }\n else {\n wantForward = false;\n }\n // Check if trying to fit beyond text length, and if not, check it fits\n // after offset location (or desired location on first iteration)\n if (start + localOffset <= maxLine) {\n return start + localOffset;\n }\n forwardExhausted = true;\n }\n if (!backwardExhausted) {\n if (!forwardExhausted) {\n wantForward = true;\n }\n // Check if trying to fit before text beginning, and if not, check it fits\n // before offset location\n if (minLine <= start - localOffset) {\n return start - localOffset++;\n }\n backwardExhausted = true;\n return iterator();\n }\n // We tried to fit hunk before text beginning and beyond text length, then\n // hunk can't fit on the text. Return undefined\n return undefined;\n };\n}\n","import { hasOnlyWinLineEndings, hasOnlyUnixLineEndings } from '../util/string.js';\nimport { isWin, isUnix, unixToWin, winToUnix } from './line-endings.js';\nimport { parsePatch } from './parse.js';\nimport distanceIterator from '../util/distance-iterator.js';\n/**\n * attempts to apply a unified diff patch.\n *\n * Hunks are applied first to last.\n * `applyPatch` first tries to apply the first hunk at the line number specified in the hunk header, and with all context lines matching exactly.\n * 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.\n * 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.\n * 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.\n *\n * Once a hunk is successfully fitted, the process begins again with the next hunk.\n * Regardless of `fuzzFactor`, later hunks must be applied later in the file than earlier hunks.\n *\n * If a hunk cannot be successfully fitted *anywhere* with fewer than `fuzzFactor` mismatches, `applyPatch` fails and returns `false`.\n *\n * 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.\n * (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.)\n *\n * If the patch was applied successfully, returns a string containing the patched text.\n * 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.\n *\n * @param patch a string diff or the output from the `parsePatch` or `structuredPatch` methods.\n */\nexport function applyPatch(source, patch, options = {}) {\n let patches;\n if (typeof patch === 'string') {\n patches = parsePatch(patch);\n }\n else if (Array.isArray(patch)) {\n patches = patch;\n }\n else {\n patches = [patch];\n }\n if (patches.length > 1) {\n throw new Error('applyPatch only works with a single input.');\n }\n return applyStructuredPatch(source, patches[0], options);\n}\nfunction applyStructuredPatch(source, patch, options = {}) {\n if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) {\n if (hasOnlyWinLineEndings(source) && isUnix(patch)) {\n patch = unixToWin(patch);\n }\n else if (hasOnlyUnixLineEndings(source) && isWin(patch)) {\n patch = winToUnix(patch);\n }\n }\n // Apply the diff to the input\n const lines = source.split('\\n'), hunks = patch.hunks, compareLine = options.compareLine || ((lineNumber, line, operation, patchContent) => line === patchContent), fuzzFactor = options.fuzzFactor || 0;\n let minLine = 0;\n if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) {\n throw new Error('fuzzFactor must be a non-negative integer');\n }\n // Special case for empty patch.\n if (!hunks.length) {\n return source;\n }\n // Before anything else, handle EOFNL insertion/removal. If the patch tells us to make a change\n // to the EOFNL that is redundant/impossible - i.e. to remove a newline that's not there, or add a\n // newline that already exists - then we either return false and fail to apply the patch (if\n // fuzzFactor is 0) or simply ignore the problem and do nothing (if fuzzFactor is >0).\n // If we do need to remove/add a newline at EOF, this will always be in the final hunk:\n let prevLine = '', removeEOFNL = false, addEOFNL = false;\n for (let i = 0; i < hunks[hunks.length - 1].lines.length; i++) {\n const line = hunks[hunks.length - 1].lines[i];\n if (line[0] == '\\\\') {\n if (prevLine[0] == '+') {\n removeEOFNL = true;\n }\n else if (prevLine[0] == '-') {\n addEOFNL = true;\n }\n }\n prevLine = line;\n }\n if (removeEOFNL) {\n if (addEOFNL) {\n // This means the final line gets changed but doesn't have a trailing newline in either the\n // original or patched version. In that case, we do nothing if fuzzFactor > 0, and if\n // fuzzFactor is 0, we simply validate that the source file has no trailing newline.\n if (!fuzzFactor && lines[lines.length - 1] == '') {\n return false;\n }\n }\n else if (lines[lines.length - 1] == '') {\n lines.pop();\n }\n else if (!fuzzFactor) {\n return false;\n }\n }\n else if (addEOFNL) {\n if (lines[lines.length - 1] != '') {\n lines.push('');\n }\n else if (!fuzzFactor) {\n return false;\n }\n }\n /**\n * Checks if the hunk can be made to fit at the provided location with at most `maxErrors`\n * insertions, substitutions, or deletions, while ensuring also that:\n * - lines deleted in the hunk match exactly, and\n * - wherever an insertion operation or block of insertion operations appears in the hunk, the\n * immediately preceding and following lines of context match exactly\n *\n * `toPos` should be set such that lines[toPos] is meant to match hunkLines[0].\n *\n * If the hunk can be applied, returns an object with properties `oldLineLastI` and\n * `replacementLines`. Otherwise, returns null.\n */\n function applyHunk(hunkLines, toPos, maxErrors, hunkLinesI = 0, lastContextLineMatched = true, patchedLines = [], patchedLinesLength = 0) {\n let nConsecutiveOldContextLines = 0;\n let nextContextLineMustMatch = false;\n for (; hunkLinesI < hunkLines.length; hunkLinesI++) {\n const hunkLine = hunkLines[hunkLinesI], operation = (hunkLine.length > 0 ? hunkLine[0] : ' '), content = (hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine);\n if (operation === '-') {\n if (compareLine(toPos + 1, lines[toPos], operation, content)) {\n toPos++;\n nConsecutiveOldContextLines = 0;\n }\n else {\n if (!maxErrors || lines[toPos] == null) {\n return null;\n }\n patchedLines[patchedLinesLength] = lines[toPos];\n return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1);\n }\n }\n if (operation === '+') {\n if (!lastContextLineMatched) {\n return null;\n }\n patchedLines[patchedLinesLength] = content;\n patchedLinesLength++;\n nConsecutiveOldContextLines = 0;\n nextContextLineMustMatch = true;\n }\n if (operation === ' ') {\n nConsecutiveOldContextLines++;\n patchedLines[patchedLinesLength] = lines[toPos];\n if (compareLine(toPos + 1, lines[toPos], operation, content)) {\n patchedLinesLength++;\n lastContextLineMatched = true;\n nextContextLineMustMatch = false;\n toPos++;\n }\n else {\n if (nextContextLineMustMatch || !maxErrors) {\n return null;\n }\n // Consider 3 possibilities in sequence:\n // 1. lines contains a *substitution* not included in the patch context, or\n // 2. lines contains an *insertion* not included in the patch context, or\n // 3. lines contains a *deletion* not included in the patch context\n // The first two options are of course only possible if the line from lines is non-null -\n // i.e. only option 3 is possible if we've overrun the end of the old file.\n 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));\n }\n }\n }\n // Before returning, trim any unmodified context lines off the end of patchedLines and reduce\n // toPos (and thus oldLineLastI) accordingly. This allows later hunks to be applied to a region\n // that starts in this hunk's trailing context.\n patchedLinesLength -= nConsecutiveOldContextLines;\n toPos -= nConsecutiveOldContextLines;\n patchedLines.length = patchedLinesLength;\n return {\n patchedLines,\n oldLineLastI: toPos - 1\n };\n }\n const resultLines = [];\n // Search best fit offsets for each hunk based on the previous ones\n let prevHunkOffset = 0;\n for (let i = 0; i < hunks.length; i++) {\n const hunk = hunks[i];\n let hunkResult;\n const maxLine = lines.length - hunk.oldLines + fuzzFactor;\n let toPos;\n for (let maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) {\n toPos = hunk.oldStart + prevHunkOffset - 1;\n const iterator = distanceIterator(toPos, minLine, maxLine);\n for (; toPos !== undefined; toPos = iterator()) {\n hunkResult = applyHunk(hunk.lines, toPos, maxErrors);\n if (hunkResult) {\n break;\n }\n }\n if (hunkResult) {\n break;\n }\n }\n if (!hunkResult) {\n return false;\n }\n // Copy everything from the end of where we applied the last hunk to the start of this hunk\n for (let i = minLine; i < toPos; i++) {\n resultLines.push(lines[i]);\n }\n // Add the lines produced by applying the hunk:\n for (let i = 0; i < hunkResult.patchedLines.length; i++) {\n const line = hunkResult.patchedLines[i];\n resultLines.push(line);\n }\n // Set lower text limit to end of the current hunk, so next ones don't try\n // to fit over already patched text\n minLine = hunkResult.oldLineLastI + 1;\n // Note the offset between where the patch said the hunk should've applied and where we\n // applied it, so we can adjust future hunks accordingly:\n prevHunkOffset = toPos + 1 - hunk.oldStart;\n }\n // Copy over the rest of the lines from the old text\n for (let i = minLine; i < lines.length; i++) {\n resultLines.push(lines[i]);\n }\n return resultLines.join('\\n');\n}\n/**\n * applies one or more patches.\n *\n * `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).\n *\n * 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:\n *\n * - `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.\n * - `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.\n *\n * Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made.\n */\nexport function applyPatches(uniDiff, options) {\n const spDiff = typeof uniDiff === 'string' ? parsePatch(uniDiff) : uniDiff;\n let currentIndex = 0;\n function processIndex() {\n const index = spDiff[currentIndex++];\n if (!index) {\n return options.complete();\n }\n options.loadFile(index, function (err, data) {\n if (err) {\n return options.complete(err);\n }\n const updatedContent = applyPatch(data, index, options);\n options.patched(index, updatedContent, function (err) {\n if (err) {\n return options.complete(err);\n }\n processIndex();\n });\n });\n }\n processIndex();\n}\n","export function reversePatch(structuredPatch) {\n if (Array.isArray(structuredPatch)) {\n // (See comment in unixToWin for why we need the pointless-looking anonymous function here)\n return structuredPatch.map(patch => reversePatch(patch)).reverse();\n }\n return Object.assign(Object.assign({}, structuredPatch), { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(hunk => {\n return {\n oldLines: hunk.newLines,\n oldStart: hunk.newStart,\n newLines: hunk.oldLines,\n newStart: hunk.oldStart,\n lines: hunk.lines.map(l => {\n if (l.startsWith('-')) {\n return `+${l.slice(1)}`;\n }\n if (l.startsWith('+')) {\n return `-${l.slice(1)}`;\n }\n return l;\n })\n };\n }) });\n}\n","import { diffLines } from '../diff/line.js';\nexport function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n let optionsObj;\n if (!options) {\n optionsObj = {};\n }\n else if (typeof options === 'function') {\n optionsObj = { callback: options };\n }\n else {\n optionsObj = options;\n }\n if (typeof optionsObj.context === 'undefined') {\n optionsObj.context = 4;\n }\n // We copy this into its own variable to placate TypeScript, which thinks\n // optionsObj.context might be undefined in the callbacks below.\n const context = optionsObj.context;\n // @ts-expect-error (runtime check for something that is correctly a static type error)\n if (optionsObj.newlineIsToken) {\n throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions');\n }\n if (!optionsObj.callback) {\n return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));\n }\n else {\n const { callback } = optionsObj;\n diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => {\n const patch = diffLinesResultToPatch(diff);\n // TypeScript is unhappy without the cast because it does not understand that `patch` may\n // be undefined here only if `callback` is StructuredPatchCallbackAbortable:\n callback(patch);\n } }));\n }\n function diffLinesResultToPatch(diff) {\n // STEP 1: Build up the patch with no \"\\" lines and with the arrays\n // of lines containing trailing newline characters. We'll tidy up later...\n if (!diff) {\n return;\n }\n diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier\n function contextLines(lines) {\n return lines.map(function (entry) { return ' ' + entry; });\n }\n const hunks = [];\n let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;\n for (let i = 0; i < diff.length; i++) {\n const current = diff[i], lines = current.lines || splitLines(current.value);\n current.lines = lines;\n if (current.added || current.removed) {\n // If we have previous context, start with that\n if (!oldRangeStart) {\n const prev = diff[i - 1];\n oldRangeStart = oldLine;\n newRangeStart = newLine;\n if (prev) {\n curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : [];\n oldRangeStart -= curRange.length;\n newRangeStart -= curRange.length;\n }\n }\n // Output our changes\n for (const line of lines) {\n curRange.push((current.added ? '+' : '-') + line);\n }\n // Track the updated file position\n if (current.added) {\n newLine += lines.length;\n }\n else {\n oldLine += lines.length;\n }\n }\n else {\n // Identical context lines. Track line changes\n if (oldRangeStart) {\n // Close out any changes that have been output (or join overlapping)\n if (lines.length <= context * 2 && i < diff.length - 2) {\n // Overlapping\n for (const line of contextLines(lines)) {\n curRange.push(line);\n }\n }\n else {\n // end the range and output\n const contextSize = Math.min(lines.length, context);\n for (const line of contextLines(lines.slice(0, contextSize))) {\n curRange.push(line);\n }\n const hunk = {\n oldStart: oldRangeStart,\n oldLines: (oldLine - oldRangeStart + contextSize),\n newStart: newRangeStart,\n newLines: (newLine - newRangeStart + contextSize),\n lines: curRange\n };\n hunks.push(hunk);\n oldRangeStart = 0;\n newRangeStart = 0;\n curRange = [];\n }\n }\n oldLine += lines.length;\n newLine += lines.length;\n }\n }\n // Step 2: eliminate the trailing `\\n` from each line of each hunk, and, where needed, add\n // \"\\".\n for (const hunk of hunks) {\n for (let i = 0; i < hunk.lines.length; i++) {\n if (hunk.lines[i].endsWith('\\n')) {\n hunk.lines[i] = hunk.lines[i].slice(0, -1);\n }\n else {\n hunk.lines.splice(i + 1, 0, '\\\');\n i++; // Skip the line we just added, then continue iterating\n }\n }\n }\n return {\n oldFileName: oldFileName, newFileName: newFileName,\n oldHeader: oldHeader, newHeader: newHeader,\n hunks: hunks\n };\n }\n}\n/**\n * creates a unified diff patch.\n * @param patch either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`)\n */\nexport function formatPatch(patch) {\n if (Array.isArray(patch)) {\n return patch.map(formatPatch).join('\\n');\n }\n const ret = [];\n if (patch.oldFileName == patch.newFileName) {\n ret.push('Index: ' + patch.oldFileName);\n }\n ret.push('===================================================================');\n ret.push('--- ' + patch.oldFileName + (typeof patch.oldHeader === 'undefined' ? '' : '\\t' + patch.oldHeader));\n ret.push('+++ ' + patch.newFileName + (typeof patch.newHeader === 'undefined' ? '' : '\\t' + patch.newHeader));\n for (let i = 0; i < patch.hunks.length; i++) {\n const hunk = patch.hunks[i];\n // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n if (hunk.oldLines === 0) {\n hunk.oldStart -= 1;\n }\n if (hunk.newLines === 0) {\n hunk.newStart -= 1;\n }\n ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines\n + ' +' + hunk.newStart + ',' + hunk.newLines\n + ' @@');\n for (const line of hunk.lines) {\n ret.push(line);\n }\n }\n return ret.join('\\n') + '\\n';\n}\nexport function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n if (typeof options === 'function') {\n options = { callback: options };\n }\n if (!(options === null || options === void 0 ? void 0 : options.callback)) {\n const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);\n if (!patchObj) {\n return;\n }\n return formatPatch(patchObj);\n }\n else {\n const { callback } = options;\n structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: patchObj => {\n if (!patchObj) {\n callback(undefined);\n }\n else {\n callback(formatPatch(patchObj));\n }\n } }));\n }\n}\nexport function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {\n return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);\n}\n/**\n * Split `text` into an array of lines, including the trailing newline character (where present)\n */\nfunction splitLines(text) {\n const hasTrailingNl = text.endsWith('\\n');\n const result = text.split('\\n').map(line => line + '\\n');\n if (hasTrailingNl) {\n result.pop();\n }\n else {\n result.push(result.pop().slice(0, -1));\n }\n return result;\n}\n","/**\n * converts a list of change objects to the format returned by Google's [diff-match-patch](https://github.com/google/diff-match-patch) library\n */\nexport function convertChangesToDMP(changes) {\n const ret = [];\n let change, operation;\n for (let i = 0; i < changes.length; i++) {\n change = changes[i];\n if (change.added) {\n operation = 1;\n }\n else if (change.removed) {\n operation = -1;\n }\n else {\n operation = 0;\n }\n ret.push([operation, change.value]);\n }\n return ret;\n}\n","/**\n * converts a list of change objects to a serialized XML format\n */\nexport function convertChangesToXML(changes) {\n const ret = [];\n for (let i = 0; i < changes.length; i++) {\n const change = changes[i];\n if (change.added) {\n ret.push('<ins>');\n }\n else if (change.removed) {\n ret.push('<del>');\n }\n ret.push(escapeHTML(change.value));\n if (change.added) {\n ret.push('</ins>');\n }\n else if (change.removed) {\n ret.push('</del>');\n }\n }\n return ret.join('');\n}\nfunction escapeHTML(s) {\n let n = s;\n n = n.replace(/&/g, '&amp;');\n n = n.replace(/</g, '&lt;');\n n = n.replace(/>/g, '&gt;');\n n = n.replace(/\"/g, '&quot;');\n return n;\n}\n","/**\n * Provides the JsDiff library to InPageEdit.\n *\n * @see https://github.com/kpdecker/jsdiff\n */\n\nimport { InPageEdit } from '@/InPageEdit'\nimport * as JsDiff from 'diff'\n\ndeclare module '@/InPageEdit' {\n interface InPageEdit {\n jsdiff: JsDiffService\n }\n}\n\nexport type JsDiffDiffType =\n | 'diffChars'\n | 'diffWords'\n | 'diffWordsWithSpace'\n | 'diffLines'\n | 'diffTrimmedLines'\n | 'diffSentences'\n | 'diffCss'\n | 'diffJson'\n | 'diffArrays'\n | 'createTwoFilesPatch'\n\nexport class JsDiffService {\n constructor(public ctx: InPageEdit) {\n this.ctx.set('jsdiff', this)\n }\n JsDiff = JsDiff\n diffChars = JsDiff.diffChars\n diffWords = JsDiff.diffWords\n diffWordsWithSpace = JsDiff.diffWordsWithSpace\n diffLines = JsDiff.diffLines\n diffTrimmedLines = JsDiff.diffTrimmedLines\n diffSentences = JsDiff.diffSentences\n diffCss = JsDiff.diffCss\n diffJson = JsDiff.diffJson\n diffArrays = JsDiff.diffArrays\n createTwoFilesPatch = JsDiff.createTwoFilesPatch\n}\n","import { InPageEdit } from '@/InPageEdit'\n\nexport const MwUserLinks = (props: { user: string; target?: string; ctx: InPageEdit }) => {\n let { user, target, ctx } = props\n const getUrl = ctx.getUrl.bind(ctx)\n return (\n <span className=\"mw-userlinks\">\n <a href={getUrl(`User:${user}`)} className=\"mw-userlink\" target={target}>\n {user}\n </a>{' '}\n <span className=\"mw-usertoollinks\">\n (\n <a href={getUrl(`User_talk:${user}`)} className=\"mw-usertoollinks-talk\" target={target}>\n talk\n </a>\n {' | '}\n <a\n href={getUrl(`Special:Contributions/${user}`)}\n className=\"mw-usertoollinks-contribs\"\n target={target}\n >\n contribs\n </a>\n {' | '}\n <a\n href={getUrl(`Special:Block/${user}`)}\n className=\"mw-usertoollinks-block\"\n target={target}\n >\n block\n </a>\n )\n </span>\n </span>\n )\n}\n","import './style.scss'\nimport { JSX } from 'jsx-dom/jsx-runtime'\nimport { CompareApiResponse } from '../PluginQuickDiffCore'\nimport { InPageEdit } from '@/InPageEdit'\n\nexport type DiffTableProps = {\n data: Partial<CompareApiResponse['compare']>\n ctx: InPageEdit\n} & JSX.IntrinsicElements['table']\n\nexport enum DiffTableEvent {\n update = 'ipe:diff-table/update',\n edit = 'ipe:diff-table/edit',\n}\n\n// DOM 事件类型定义\ndeclare global {\n interface HTMLElementEventMap {\n [DiffTableEvent.update]: CustomEvent<{\n fromrev: number\n torev: number\n }>\n [DiffTableEvent.edit]: CustomEvent<{\n revid: number\n }>\n }\n}\n\nconst formatDate = new Intl.DateTimeFormat(undefined, {\n dateStyle: 'medium',\n timeStyle: 'medium',\n}).format\n\nconst DiffTableHeader = (props: {\n ctx: InPageEdit\n type?: 'from' | 'to'\n pageid?: number\n pagetitle?: string\n revid?: number\n size?: number\n timestamp?: string\n username?: string\n userid?: number\n comment?: string\n parsedcomment?: string\n}) => {\n let classList = ['diff-title']\n if (props.type === 'from') {\n classList.push('diff-otitle')\n } else if (props.type === 'to') {\n classList.push('diff-ntitle')\n }\n if (!props.pageid || !props.userid) {\n return (\n <td colSpan={2} className={classList}>\n <div className=\"mw-diff-title--title\">\n {props.type === 'from' ? 'Original content' : props.type === 'to' ? 'Your content' : ''}\n </div>\n </td>\n )\n }\n const handleEditClick = (e: Event) => {\n e.preventDefault()\n e.target!.dispatchEvent(\n new CustomEvent(DiffTableEvent.edit, {\n detail: { revid: props.revid! },\n bubbles: true,\n })\n )\n }\n return (\n <td colSpan={2} className={classList}>\n <div className=\"mw-diff-title--title\">\n {props.pagetitle || props.timestamp}\n {props.revid ? ` (rev#${props.revid})` : ''}\n </div>\n <div className=\"mw-diff-title--actions\">\n <a\n href={props.ctx.getUrl('', { action: 'edit', oldid: props.revid! })}\n onClick={handleEditClick}\n >\n <IconQuickEdit style=\"width: 1em; height: 1em\" />\n Quick edit\n </a>\n </div>\n <div className=\"mw-diff-title--user\">\n {props.username && <MwUserLinks ctx={props.ctx} user={props.username} target=\"_blank\" />}\n </div>\n <div className=\"mw-diff-title--timestamp\">\n {props.timestamp && formatDate(new Date(props.timestamp))}\n </div>\n <div className=\"mw-diff-title--comment\">\n {props.parsedcomment && (\n <>\n (<i innerHTML={props.parsedcomment}></i>)\n </>\n )}\n </div>\n </td>\n )\n}\n\nconst DiffTableNavigation = (props: { data: DiffTableProps['data']; ctx: InPageEdit }) => {\n const data = props.data\n if (!data.prev && !data.next) {\n return null\n }\n\n // 统一的事件处理器\n const handleNavigationClick = (e: Event, fromrev: number, torev: number) => {\n e.preventDefault()\n e.target!.dispatchEvent(\n new CustomEvent(DiffTableEvent.update, {\n detail: { fromrev, torev },\n bubbles: true,\n })\n )\n }\n\n return (\n <tr className=\"mw-diff-title--navigation\">\n <td colSpan={2}>\n {data.prev ? (\n <a\n href={props.ctx.getUrl('', { diff: data.prev!, oldid: data.fromrevid! })}\n onClick={(e) => handleNavigationClick(e, data.prev!, data.fromrevid!)}\n >\n ← Previous\n </a>\n ) : (\n <i>Oldest version</i>\n )}\n </td>\n <td colSpan={2}>\n {data.next ? (\n <a\n href={props.ctx.getUrl('', { diff: data.next!, oldid: data.torevid! })}\n onClick={(e) => handleNavigationClick(e, data.torevid!, data.next!)}\n >\n Next →\n </a>\n ) : (\n <i>Newest version</i>\n )}\n </td>\n </tr>\n )\n}\n\nexport const DiffTable = (props: DiffTableProps) => {\n const { data, ...rest } = props\n const table = (\n <table className={`theme-ipe diff diff-type-table`} data-mw=\"interface\" {...rest}>\n <colgroup>\n <col className=\"diff-marker\" />\n <col className=\"diff-content\" />\n <col className=\"diff-marker\" />\n <col className=\"diff-content\" />\n </colgroup>\n <tbody>\n <tr>\n <DiffTableHeader\n ctx={props.ctx}\n type=\"from\"\n pageid={data.fromid}\n pagetitle={data.fromtitle}\n revid={data.fromrevid}\n size={data.fromsize}\n timestamp={data.fromtimestamp}\n username={data.fromuser}\n userid={data.fromuserid}\n comment={data.fromcomment}\n parsedcomment={data.fromparsedcomment}\n />\n <DiffTableHeader\n ctx={props.ctx}\n type=\"to\"\n pageid={data.toid}\n pagetitle={data.totitle}\n revid={data.torevid}\n size={data.tosize}\n timestamp={data.totimestamp}\n username={data.touser}\n userid={data.touserid}\n comment={data.tocomment}\n parsedcomment={data.toparsedcomment}\n />\n </tr>\n <DiffTableNavigation data={data} ctx={props.ctx} />\n <div id=\"diffbody\"></div>\n <tr className=\"diff-size\" style={{ textAlign: 'center' }}>\n <td colSpan={2} className=\"diff-size-old\">\n {data.fromsize !== undefined && `${data.fromsize} bytes`}\n </td>\n <td colSpan={2} className=\"diff-size-new\">\n {data.tosize !== undefined && `${data.tosize} bytes`}\n </td>\n </tr>\n </tbody>\n </table>\n )\n table.querySelector('#diffbody')!.outerHTML =\n data.body ||\n (\n <tr>\n <td colSpan={4}>\n <div\n style={{\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center',\n height: '5rem',\n }}\n >\n <i>No changes</i>\n </div>\n </td>\n </tr>\n ).outerHTML\n return table\n}\n","import { CSSProperties, ReactElement } from 'jsx-dom'\n\nexport const qs = <T extends Element>(\n selector: string,\n parent: HTMLElement | Document = document\n) => {\n return parent.querySelector(selector) as T | null\n}\nexport const qsa = <T extends Element>(\n selector: string,\n parent: HTMLElement | Document = document\n) => {\n return parent.querySelectorAll(selector) as NodeListOf<T>\n}\n\nexport const setStyles = (el: HTMLElement | ReactElement, style: CSSProperties) => {\n Object.entries(style).forEach(([key, value]) => {\n if (typeof value === 'undefined' || value === null) {\n el.style.removeProperty(key)\n } else {\n const isImportant = typeof value === 'string' && value.endsWith('!important')\n // @ts-ignore\n el.style.setProperty(\n key,\n value.replace('!important', '').trim(),\n isImportant ? 'important' : undefined\n )\n }\n })\n return el\n}\n","import { Inject, InPageEdit, Schema } from '@/InPageEdit'\nimport { type QuickEditEventPayload } from '@/plugins/quick-edit'\nimport { JsDiffDiffType } from './JsDiffService'\n\nimport styles from './styles.module.sass'\nimport { ChangeObject } from 'diff'\nimport { DiffTable, DiffTableEvent } from './components/DiffTable'\nimport { IPEModal, IPEModalOptions } from '@inpageedit/modal'\nimport { MwApiResponse } from 'wiki-saikou'\n\ndeclare module '@/InPageEdit' {\n interface InPageEdit {\n quickDiff: PluginQuickDiffCore\n }\n}\n\nexport interface CompareApiRequestOptions {\n fromtitle: string\n fromid: number\n fromrev: number\n frompst: boolean\n totitle: string\n toid: number\n torev: number\n torelative?: 'cur' | 'prev' | 'next'\n topst: boolean\n prop: string\n difftype: 'table' | 'unified'\n // deprecated, but still works\n fromtext: string\n fromsection: string | number\n fromcontentmodel: string\n totext: string\n tosection: string | number\n tocontentmodel: string\n}\n\nexport interface CompareApiResponse {\n compare: Partial<{\n fromid: number\n fromrevid: number\n fromns: number\n fromtitle: string\n fromsize: number\n fromtimestamp: string\n fromuser: string\n fromuserid: number\n fromcomment: string\n fromparsedcomment?: string\n toid: number\n torevid: number\n tons: number\n totitle: string\n tosize: number\n totimestamp: string\n touser: string\n touserid: number\n tocomment: string\n toparsedcomment: string\n diffsize: number\n prev: number\n next: number\n }> & {\n body: string\n }\n}\n\nconst VALID_DIFF_TYPES = [\n 'diffChars',\n 'diffWords',\n 'diffSentences',\n 'diffLines',\n 'createTwoFilesPatch',\n] as JsDiffDiffType[]\n\n@Inject(['jsdiff', 'wiki', 'getUrl'])\n@RegisterPreferences(\n Schema.object({\n 'quickDiff.preferredCompareMode': Schema.union([Schema.const('jsDiff'), Schema.const('mwApi')])\n .description('The preferred comparison mode for quick diff')\n .default('mwApi'),\n 'quickDiff.jsDiff.defaultType': Schema.union(VALID_DIFF_TYPES.map((type) => Schema.const(type)))\n .description('The default diff type for JsDiff')\n .default('diffSentences'),\n }).description('Quick Diff Preferences'),\n {\n 'quickDiff.preferredCompareMode': 'mwApi',\n 'quickDiff.jsDiff.defaultType': 'diffSentences',\n }\n)\nexport class PluginQuickDiffCore extends BasePlugin {\n VALID_DIFF_TYPES = VALID_DIFF_TYPES\n\n constructor(public ctx: InPageEdit) {\n super(ctx, {}, 'quick-diff')\n }\n\n protected start(): Promise<void> | void {\n this.ctx.set('quickDiff', this)\n this.ctx.on('quick-edit/wiki-page', this.injectQuickEdit.bind(this))\n window.RLQ.push(this.injectHistoryPage.bind(this))\n }\n\n protected stop(): Promise<void> | void {}\n\n private injectHistoryPage() {\n const mwCompareForm = qs<HTMLFormElement>('#mw-history-compare')\n if (!mwCompareForm) {\n return\n }\n const compareButtons = qsa('.mw-history-compareselectedversions-button', mwCompareForm)\n compareButtons.forEach((el) => {\n el.after(\n <button\n className=\"cdx-button\"\n onClick={(e) => {\n e.preventDefault()\n const formData = new FormData(mwCompareForm)\n const fromrev = Number(formData.get('oldid')) || 0\n const torev = Number(formData.get('diff')) || 0\n const title = formData.get('title') as string\n if (!title || !fromrev || !torev) {\n return this.logger.warn('Missing title or revision IDs')\n }\n this.comparePages({\n fromrev,\n torev,\n })\n }}\n >\n Quick Diff\n </button>\n )\n })\n }\n\n private injectQuickEdit({ modal, wikiPage, options }: QuickEditEventPayload) {\n if (wikiPage.pageid === 0 || options.section === 'new') {\n // User is creating a new page, no need to show diff button\n return\n }\n let latestDiffModal: IPEModal | undefined = undefined\n modal.addButton(\n {\n label: 'Diff',\n side: 'left',\n keyPress: 'ctrl-d',\n className: 'btn btn-secondary',\n method: () => {\n const pageTitle = wikiPage.title\n const fromtext = wikiPage.revisions?.[0]?.content || ''\n const totext =\n (modal.get$content().querySelector<HTMLTextAreaElement>('textarea[name=\"text\"]')\n ?.value as string) || ''\n\n if (fromtext === totext) {\n return this.ctx.modal.notify('info', { title: 'Quick Diff', content: 'No changes' })\n }\n\n latestDiffModal = this.comparePages(\n {\n fromtitle: pageTitle,\n fromtext,\n totitle: pageTitle,\n totext,\n topst: true,\n },\n latestDiffModal,\n {\n backdrop: false,\n draggable: true,\n }\n )\n return latestDiffModal\n },\n },\n 2\n )\n modal.on(modal.Event.Close, () => {\n latestDiffModal?.destroy()\n latestDiffModal = undefined\n })\n }\n\n simpleTextDiff(oldText: string, newText: string) {\n const modal = this.ctx.modal.show({\n title: 'Quick Diff',\n className: 'in-page-edit ipe-quickDiff',\n })\n modal.show()\n\n const container = <pre className={styles['diff-container']}></pre>\n const controller = (\n <div\n style={{\n display: 'flex',\n gap: '1em',\n }}\n >\n {this.VALID_DIFF_TYPES.map((type, index) => (\n <RadioBox\n name=\"diffType\"\n value={type}\n label={type}\n inputProps={{\n checked: index === 0,\n }}\n />\n ))}\n </div>\n )\n modal.setContent(\n (\n <section>\n {controller}\n {container}\n </section>\n ) as HTMLElement\n )\n controller.querySelectorAll<HTMLInputElement>('input[name=\"diffType\"]').forEach((input) => {\n input.addEventListener('change', () => {\n const diff = this.renderJsDiff(oldText, newText, input.value as JsDiffDiffType)\n container.textContent = ''\n container.appendChild(diff)\n })\n })\n controller\n .querySelector<HTMLInputElement>('input[name=\"diffType\"]')!\n .dispatchEvent(new Event('change'))\n }\n\n /**\n * TODO: 类型体操\n */\n renderJsDiff(oldStr: string, newStr: string, diffType: JsDiffDiffType = 'diffSentences') {\n const fragment = document.createDocumentFragment()\n\n let diff: (ChangeObject<string> & { chunkHeader?: boolean })[]\n if (diffType === 'createTwoFilesPatch') {\n // 将 patch 结果转化为与 diffChars/diffWords... 类似的结构\n let pastHunkHeader = false\n diff = this.ctx.jsdiff\n .createTwoFilesPatch('original.txt', 'modified.txt', oldStr, newStr)\n .split('\\n')\n .map(function (entry) {\n const line = {\n value: entry + '\\n',\n } as ChangeObject<string> & { chunkHeader: boolean }\n if (entry.startsWith('@@')) {\n line.chunkHeader = true\n pastHunkHeader = true\n } else if (pastHunkHeader) {\n if (entry.startsWith('-')) {\n line.removed = true\n } else if (entry.startsWith('+')) {\n line.added = true\n }\n }\n return line\n })\n } else {\n const handler = this.ctx.jsdiff[diffType] as (\n oldStr: string,\n newStr: string\n ) => ChangeObject<string>[]\n if (!handler) {\n throw new Error(`Missing DiffEngine for ${diffType}`)\n }\n diff = handler(oldStr, newStr)\n }\n\n if (!Array.isArray(diff)) {\n throw new Error('Missing diff result')\n }\n\n // 交换逻辑(一个删除一个新增时)\n for (let i = 0; i < diff.length; i++) {\n if (diff[i].added && diff[i + 1] && diff[i + 1].removed) {\n const swap = diff[i]\n diff[i] = diff[i + 1]\n diff[i + 1] = swap\n }\n\n let node\n if (diff[i].removed) {\n node = document.createElement('del')\n node.appendChild(document.createTextNode(diff[i].value))\n } else if (diff[i].added) {\n node = document.createElement('ins')\n node.appendChild(document.createTextNode(diff[i].value))\n } else if (diff[i].chunkHeader) {\n node = document.createElement('span')\n node.setAttribute('class', 'chunk-header')\n node.appendChild(document.createTextNode(diff[i].value))\n } else {\n node = document.createTextNode(diff[i].value)\n }\n fragment.appendChild(node)\n }\n\n return fragment\n }\n\n readonly COMPARE_API_DEFAULT_OPTIONS: Partial<CompareApiRequestOptions> = {\n prop: [\n 'comment',\n 'diff',\n 'diffsize',\n 'ids',\n 'parsedcomment',\n 'size',\n 'timestamp',\n 'title',\n 'user',\n 'rel',\n ].join('|'),\n difftype: 'table',\n }\n\n comparePages(\n options: Partial<CompareApiRequestOptions>,\n modal?: IPEModal,\n modalOptions?: Partial<IPEModalOptions>\n ) {\n if (!modal || modal.isDestroyed) {\n modal = this.ctx.modal\n .createObject({\n title: 'Loading diff...',\n content: '',\n className: 'quick-diff',\n center: false,\n ...modalOptions,\n })\n .init()\n } else {\n modal.removeButton('*')\n }\n\n modal.setContent(\n <section\n style={{ height: '70vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}\n >\n <ProgressBar />\n </section>\n )\n modal.bringToFront()\n\n if (window.mw && mw.loader.getState('mediawiki.diff.styles') !== 'ready') {\n mw.loader.load(['mediawiki.diff.styles'])\n }\n\n this.ctx.api\n .post<MwApiResponse<CompareApiResponse>>({\n ...this.COMPARE_API_DEFAULT_OPTIONS,\n ...options,\n action: 'compare',\n format: 'json',\n formatversion: 2,\n })\n .then((res) => {\n if (!res.data.compare) {\n throw new Error('No compare data received', { cause: res })\n }\n const {\n data: { compare },\n } = res\n modal.setTitle(\n compare.fromtitle && compare.totitle\n ? `${compare.fromtitle}${compare.fromrevid ? ` (${compare.fromrevid})` : ''} ⇔ ${compare.totitle}${compare.torevid ? ` (${compare.torevid})` : ''}`\n : 'Differences'\n )\n let diffTable!: HTMLElement\n modal.setContent(\n (\n <section\n style={{\n minHeight: '70vh',\n }}\n >\n <DiffTable ref={(ref) => (diffTable = ref)} data={compare} ctx={this.ctx} />\n </section>\n ) as HTMLElement\n )\n diffTable.addEventListener(\n DiffTableEvent.update,\n (e) => {\n e.stopPropagation()\n this.comparePages(\n {\n fromrev: e.detail.fromrev,\n torev: e.detail.torev,\n },\n modal,\n modalOptions\n )\n },\n { once: true }\n )\n\n // TODO: 不应该硬编码,移动到 in-article-links 插件中\n this.ctx.inject(['quickEdit'], (ctx) => {\n const handleQuickEdit = (e: CustomEvent<{ revid: number }>) => {\n e.stopPropagation()\n ctx.quickEdit({ revision: e.detail.revid })\n }\n diffTable.addEventListener(DiffTableEvent.edit, handleQuickEdit)\n modal.on(modal.Event.Close, () => {\n diffTable.removeEventListener(DiffTableEvent.edit, handleQuickEdit)\n })\n })\n\n if (compare.fromrevid && compare.torevid) {\n modal.addButton({\n label: 'Original Compare Page',\n side: 'right',\n className: 'btn btn-secondary',\n method: () => {\n window.location.href = this.ctx.getUrl('', {\n oldid: compare.fromrevid,\n diff: compare.torevid,\n })\n },\n })\n }\n })\n .catch((err) => {\n modal.setContent(\n (\n <MBox title=\"Failed to load diff\" type=\"error\">\n <pre>{err instanceof Error ? err.message : String(err)}</pre>\n </MBox>\n ) as HTMLElement\n )\n })\n\n return modal.show()\n }\n}\n","import { InPageEdit } from '@/InPageEdit'\nimport { JsDiffService } from './JsDiffService'\nimport { PluginQuickDiffCore } from './PluginQuickDiffCore'\n\nexport class PluginQuickDiff extends BasePlugin {\n static readonly inject = ['api', 'wikiPage', 'modal']\n\n constructor(public ctx: InPageEdit) {\n super(ctx, {}, 'quick-diff-loader')\n ctx.plugin(JsDiffService)\n ctx.plugin(PluginQuickDiffCore)\n }\n}\n"],"names":["Diff","oldStr","newStr","options","callback","oldString","newString","oldTokens","newTokens","_a","done","value","newLen","oldLen","editLength","maxEditLength","maxExecutionTime","abortAfterTimestamp","bestPath","newPos","minDiagonalToConsider","maxDiagonalToConsider","execEditLength","diagonalPath","basePath","removePath","addPath","canAdd","addPathNewPos","canRemove","exec","ret","path","added","removed","oldPosInc","last","oldPos","commonCount","left","right","array","chars","changeObjects","lastComponent","components","nextComponent","componentLen","componentPos","component","i","oldValue","CharacterDiff","characterDiff","diffChars","longestCommonPrefix","str1","str2","longestCommonSuffix","replacePrefix","string","oldPrefix","newPrefix","replaceSuffix","oldSuffix","newSuffix","removePrefix","removeSuffix","maximumOverlap","string1","string2","overlapCount","a","b","startA","endB","map","k","j","hasOnlyWinLineEndings","hasOnlyUnixLineEndings","trailingWs","leadingWs","match","extendedWordChars","tokenizeIncludingWhitespace","WordDiff","parts","segmenter","segment","tokens","prevPart","part","token","changes","lastKeep","insertion","deletion","change","dedupeWhitespaceInChangeObjects","wordDiff","diffWords","diffWordsWithSpace","startKeep","endKeep","oldWsPrefix","oldWsSuffix","newWsPrefix","newWsSuffix","commonWsPrefix","commonWsSuffix","ws","newWsFull","delWsStart","delWsEnd","newWsStart","newWsEnd","endKeepWsPrefix","deletionWsSuffix","overlap","startKeepWsSuffix","deletionWsPrefix","WordsWithSpaceDiff","regex","wordsWithSpaceDiff","generateOptions","defaults","name","LineDiff","tokenize","lineDiff","diffLines","diffTrimmedLines","retLines","linesAndNewlines","line","isSentenceEndPunct","char","SentenceDiff","result","tokenStartI","sentenceDiff","diffSentences","CssDiff","cssDiff","diffCss","JsonDiff","undefinedReplacement","stringifyReplacer","v","canonicalize","jsonDiff","diffJson","obj","stack","replacementStack","replacer","key","canonicalizedObj","sortedKeys","ArrayDiff","arrayDiff","diffArrays","oldArr","newArr","unixToWin","patch","p","hunk","winToUnix","isUnix","index","isWin","parsePatch","uniDiff","diffstr","list","parseIndex","header","parseFileHeader","parseHunk","fileHeader","data","fileName","chunkHeaderIndex","chunkHeaderLine","chunkHeader","addCount","removeCount","operation","distanceIterator","start","minLine","maxLine","wantForward","backwardExhausted","forwardExhausted","localOffset","iterator","applyPatch","source","patches","applyStructuredPatch","lines","hunks","compareLine","lineNumber","patchContent","fuzzFactor","prevLine","removeEOFNL","addEOFNL","applyHunk","hunkLines","toPos","maxErrors","hunkLinesI","lastContextLineMatched","patchedLines","patchedLinesLength","nConsecutiveOldContextLines","nextContextLineMustMatch","hunkLine","content","resultLines","prevHunkOffset","hunkResult","applyPatches","spDiff","currentIndex","processIndex","err","updatedContent","reversePatch","structuredPatch","l","oldFileName","newFileName","oldHeader","newHeader","optionsObj","context","diff","diffLinesResultToPatch","contextLines","entry","oldRangeStart","newRangeStart","curRange","oldLine","newLine","current","splitLines","prev","contextSize","formatPatch","createTwoFilesPatch","patchObj","createPatch","text","hasTrailingNl","convertChangesToDMP","convertChangesToXML","escapeHTML","s","n","JsDiffService","ctx","JsDiff","JsDiff.diffChars","JsDiff.diffWords","JsDiff.diffWordsWithSpace","JsDiff.diffLines","JsDiff.diffTrimmedLines","JsDiff.diffSentences","JsDiff.diffCss","JsDiff.diffJson","JsDiff.diffArrays","JsDiff.createTwoFilesPatch","MwUserLinks","props","user","target","getUrl","jsxs","jsx","DiffTableEvent","formatDate","DiffTableHeader","classList","handleEditClick","e","IconQuickEdit","Fragment","DiffTableNavigation","handleNavigationClick","fromrev","torev","DiffTable","rest","table","qs","selector","parent","qsa","_PluginQuickDiffCore_decorators","_init","VALID_DIFF_TYPES","Inject","RegisterPreferences","Schema","type","PluginQuickDiffCore","BasePlugin","mwCompareForm","el","formData","modal","wikiPage","latestDiffModal","pageTitle","fromtext","totext","oldText","newText","container","styles","controller","RadioBox","input","diffType","fragment","pastHunkHeader","handler","swap","node","modalOptions","ProgressBar","res","compare","diffTable","ref","handleQuickEdit","MBox","__decoratorStart","__decorateElement","__runInitializers","PluginQuickDiff"],"mappings":";;;;;;AAAe,MAAMA,EAAK;AAAA,EACtB,KAAKC,GAAQC,GAEbC,IAAU,CAAA,GAAI;AACV,QAAIC;AACJ,IAAI,OAAOD,KAAY,cACnBC,IAAWD,GACXA,IAAU,CAAA,KAEL,cAAcA,MACnBC,IAAWD,EAAQ;AAGvB,UAAME,IAAY,KAAK,UAAUJ,GAAQE,CAAO,GAC1CG,IAAY,KAAK,UAAUJ,GAAQC,CAAO,GAC1CI,IAAY,KAAK,YAAY,KAAK,SAASF,GAAWF,CAAO,CAAC,GAC9DK,IAAY,KAAK,YAAY,KAAK,SAASF,GAAWH,CAAO,CAAC;AACpE,WAAO,KAAK,mBAAmBI,GAAWC,GAAWL,GAASC,CAAQ;AAAA,EAC1E;AAAA,EACA,mBAAmBG,GAAWC,GAAWL,GAASC,GAAU;AACxD,QAAIK;AACJ,UAAMC,IAAO,CAACC,MAAU;AAEpB,UADAA,IAAQ,KAAK,YAAYA,GAAOR,CAAO,GACnCC,GAAU;AACV,mBAAW,WAAY;AAAE,UAAAA,EAASO,CAAK;AAAA,QAAG,GAAG,CAAC;AAC9C;AAAA,MACJ;AAEI,eAAOA;AAAA,IAEf,GACMC,IAASJ,EAAU,QAAQK,IAASN,EAAU;AACpD,QAAIO,IAAa,GACbC,IAAgBH,IAASC;AAC7B,IAAIV,EAAQ,iBAAiB,SACzBY,IAAgB,KAAK,IAAIA,GAAeZ,EAAQ,aAAa;AAEjE,UAAMa,KAAoBP,IAAKN,EAAQ,aAAa,QAAQM,MAAO,SAASA,IAAK,OAC3EQ,IAAsB,KAAK,IAAG,IAAKD,GACnCE,IAAW,CAAC,EAAE,QAAQ,IAAI,eAAe,QAAW;AAE1D,QAAIC,IAAS,KAAK,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AA,CACzD;AAAA,MAAA;AAAA,IAGN,CAAC,GAEIsF,EAAM,KAAA;AAAA,EACf;AACF;AA3VOX,IAAAsC,GAAA/U,EAAA;AAAM+S,IAANiC,gCAfPxC,IAeaO,CAAA;AAANkC,GAAAxC,GAAA,GAAMM,CAAA;ACtFN,MAAMmC,WAAwBlC,EAAW;AAAA,EAG9C,YAAmB9C,GAAiB;AAClC,UAAMA,GAAK,CAAA,GAAI,mBAAmB,GADjB,KAAA,MAAAA,GAEjBA,EAAI,OAAOD,EAAa,GACxBC,EAAI,OAAO6C,CAAmB;AAAA,EAChC;AAAA,EANA,OAAA;AAAA,SAAgB,SAAS,CAAC,OAAO,YAAY,OAAO;AAAA,EAAA;AAOtD;","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]}
1
+ {"version":3,"file":"index-CADkQBg0.js","sources":["../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/base.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/character.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/util/string.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/word.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/util/params.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/line.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/sentence.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/css.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/json.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/diff/array.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/patch/line-endings.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/patch/parse.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/util/distance-iterator.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/patch/apply.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/patch/reverse.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/patch/create.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/convert/dmp.js","../../../node_modules/.pnpm/diff@8.0.2/node_modules/diff/libesm/convert/xml.js","../src/plugins/quick-diff/JsDiffService.ts","../src/components/MwUserLinks.tsx","../src/plugins/quick-diff/components/DiffTable.tsx","../src/components/utils.tsx","../src/plugins/quick-diff/PluginQuickDiffCore.tsx","../src/plugins/quick-diff/index.tsx"],"sourcesContent":["export default class Diff {\n diff(oldStr, newStr, \n // Type below is not accurate/complete - see above for full possibilities - but it compiles\n options = {}) {\n let callback;\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n else if ('callback' in options) {\n callback = options.callback;\n }\n // Allow subclasses to massage the input prior to running\n const oldString = this.castInput(oldStr, options);\n const newString = this.castInput(newStr, options);\n const oldTokens = this.removeEmpty(this.tokenize(oldString, options));\n const newTokens = this.removeEmpty(this.tokenize(newString, options));\n return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);\n }\n diffWithOptionsObj(oldTokens, newTokens, options, callback) {\n var _a;\n const done = (value) => {\n value = this.postProcess(value, options);\n if (callback) {\n setTimeout(function () { callback(value); }, 0);\n return undefined;\n }\n else {\n return value;\n }\n };\n const newLen = newTokens.length, oldLen = oldTokens.length;\n let editLength = 1;\n let maxEditLength = newLen + oldLen;\n if (options.maxEditLength != null) {\n maxEditLength = Math.min(maxEditLength, options.maxEditLength);\n }\n const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity;\n const abortAfterTimestamp = Date.now() + maxExecutionTime;\n const bestPath = [{ oldPos: -1, lastComponent: undefined }];\n // Seed editLength = 0, i.e. the content starts with the same values\n let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);\n if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n // Identity per the equality and tokenizer\n return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));\n }\n // Once we hit the right edge of the edit graph on some diagonal k, we can\n // definitely reach the end of the edit graph in no more than k edits, so\n // there's no point in considering any moves to diagonal k+1 any more (from\n // which we're guaranteed to need at least k+1 more edits).\n // Similarly, once we've reached the bottom of the edit graph, there's no\n // point considering moves to lower diagonals.\n // We record this fact by setting minDiagonalToConsider and\n // maxDiagonalToConsider to some finite value once we've hit the edge of\n // the edit graph.\n // This optimization is not faithful to the original algorithm presented in\n // Myers's paper, which instead pointlessly extends D-paths off the end of\n // the edit graph - see page 7 of Myers's paper which notes this point\n // explicitly and illustrates it with a diagram. This has major performance\n // implications for some common scenarios. For instance, to compute a diff\n // where the new text simply appends d characters on the end of the\n // original text of length n, the true Myers algorithm will take O(n+d^2)\n // time while this optimization needs only O(n+d) time.\n let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;\n // Main worker method. checks all permutations of a given edit length for acceptance.\n const execEditLength = () => {\n for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {\n let basePath;\n const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];\n if (removePath) {\n // No one else is going to attempt to use this value, clear it\n // @ts-expect-error - perf optimisation. This type-violating value will never be read.\n bestPath[diagonalPath - 1] = undefined;\n }\n let canAdd = false;\n if (addPath) {\n // what newPos will be after we do an insertion:\n const addPathNewPos = addPath.oldPos - diagonalPath;\n canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;\n }\n const canRemove = removePath && removePath.oldPos + 1 < oldLen;\n if (!canAdd && !canRemove) {\n // If this path is a terminal then prune\n // @ts-expect-error - perf optimisation. This type-violating value will never be read.\n bestPath[diagonalPath] = undefined;\n continue;\n }\n // Select the diagonal that we want to branch from. We select the prior\n // path whose position in the old string is the farthest from the origin\n // and does not pass the bounds of the diff graph\n if (!canRemove || (canAdd && removePath.oldPos < addPath.oldPos)) {\n basePath = this.addToPath(addPath, true, false, 0, options);\n }\n else {\n basePath = this.addToPath(removePath, false, true, 1, options);\n }\n newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);\n if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {\n // If we have hit the end of both strings, then we are done\n return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;\n }\n else {\n bestPath[diagonalPath] = basePath;\n if (basePath.oldPos + 1 >= oldLen) {\n maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);\n }\n if (newPos + 1 >= newLen) {\n minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);\n }\n }\n }\n editLength++;\n };\n // Performs the length of edit iteration. Is a bit fugly as this has to support the\n // sync and async mode which is never fun. Loops over execEditLength until a value\n // is produced, or until the edit length exceeds options.maxEditLength (if given),\n // in which case it will return undefined.\n if (callback) {\n (function exec() {\n setTimeout(function () {\n if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {\n return callback(undefined);\n }\n if (!execEditLength()) {\n exec();\n }\n }, 0);\n }());\n }\n else {\n while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {\n const ret = execEditLength();\n if (ret) {\n return ret;\n }\n }\n }\n }\n addToPath(path, added, removed, oldPosInc, options) {\n const last = path.lastComponent;\n if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent }\n };\n }\n else {\n return {\n oldPos: path.oldPos + oldPosInc,\n lastComponent: { count: 1, added: added, removed: removed, previousComponent: last }\n };\n }\n }\n extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {\n const newLen = newTokens.length, oldLen = oldTokens.length;\n let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;\n while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {\n newPos++;\n oldPos++;\n commonCount++;\n if (options.oneChangePerToken) {\n basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };\n }\n }\n if (commonCount && !options.oneChangePerToken) {\n basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };\n }\n basePath.oldPos = oldPos;\n return newPos;\n }\n equals(left, right, options) {\n if (options.comparator) {\n return options.comparator(left, right);\n }\n else {\n return left === right\n || (!!options.ignoreCase && left.toLowerCase() === right.toLowerCase());\n }\n }\n removeEmpty(array) {\n const ret = [];\n for (let i = 0; i < array.length; i++) {\n if (array[i]) {\n ret.push(array[i]);\n }\n }\n return ret;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n castInput(value, options) {\n return value;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n tokenize(value, options) {\n return Array.from(value);\n }\n join(chars) {\n // Assumes ValueT is string, which is the case for most subclasses.\n // When it's false, e.g. in diffArrays, this method needs to be overridden (e.g. with a no-op)\n // Yes, the casts are verbose and ugly, because this pattern - of having the base class SORT OF\n // assume tokens and values are strings, but not completely - is weird and janky.\n return chars.join('');\n }\n postProcess(changeObjects, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n options) {\n return changeObjects;\n }\n get useLongestToken() {\n return false;\n }\n buildValues(lastComponent, newTokens, oldTokens) {\n // First we convert our linked list of components in reverse order to an\n // array in the right order:\n const components = [];\n let nextComponent;\n while (lastComponent) {\n components.push(lastComponent);\n nextComponent = lastComponent.previousComponent;\n delete lastComponent.previousComponent;\n lastComponent = nextComponent;\n }\n components.reverse();\n const componentLen = components.length;\n let componentPos = 0, newPos = 0, oldPos = 0;\n for (; componentPos < componentLen; componentPos++) {\n const component = components[componentPos];\n if (!component.removed) {\n if (!component.added && this.useLongestToken) {\n let value = newTokens.slice(newPos, newPos + component.count);\n value = value.map(function (value, i) {\n const oldValue = oldTokens[oldPos + i];\n return oldValue.length > value.length ? oldValue : value;\n });\n component.value = this.join(value);\n }\n else {\n component.value = this.join(newTokens.slice(newPos, newPos + component.count));\n }\n newPos += component.count;\n // Common case\n if (!component.added) {\n oldPos += component.count;\n }\n }\n else {\n component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));\n oldPos += component.count;\n }\n }\n return components;\n }\n}\n","import Diff from './base.js';\nclass CharacterDiff extends Diff {\n}\nexport const characterDiff = new CharacterDiff();\nexport function diffChars(oldStr, newStr, options) {\n return characterDiff.diff(oldStr, newStr, options);\n}\n","export function longestCommonPrefix(str1, str2) {\n let i;\n for (i = 0; i < str1.length && i < str2.length; i++) {\n if (str1[i] != str2[i]) {\n return str1.slice(0, i);\n }\n }\n return str1.slice(0, i);\n}\nexport function longestCommonSuffix(str1, str2) {\n let i;\n // Unlike longestCommonPrefix, we need a special case to handle all scenarios\n // where we return the empty string since str1.slice(-0) will return the\n // entire string.\n if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) {\n return '';\n }\n for (i = 0; i < str1.length && i < str2.length; i++) {\n if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) {\n return str1.slice(-i);\n }\n }\n return str1.slice(-i);\n}\nexport function replacePrefix(string, oldPrefix, newPrefix) {\n if (string.slice(0, oldPrefix.length) != oldPrefix) {\n throw Error(`string ${JSON.stringify(string)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`);\n }\n return newPrefix + string.slice(oldPrefix.length);\n}\nexport function replaceSuffix(string, oldSuffix, newSuffix) {\n if (!oldSuffix) {\n return string + newSuffix;\n }\n if (string.slice(-oldSuffix.length) != oldSuffix) {\n throw Error(`string ${JSON.stringify(string)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`);\n }\n return string.slice(0, -oldSuffix.length) + newSuffix;\n}\nexport function removePrefix(string, oldPrefix) {\n return replacePrefix(string, oldPrefix, '');\n}\nexport function removeSuffix(string, oldSuffix) {\n return replaceSuffix(string, oldSuffix, '');\n}\nexport function maximumOverlap(string1, string2) {\n return string2.slice(0, overlapCount(string1, string2));\n}\n// Nicked from https://stackoverflow.com/a/60422853/1709587\nfunction overlapCount(a, b) {\n // Deal with cases where the strings differ in length\n let startA = 0;\n if (a.length > b.length) {\n startA = a.length - b.length;\n }\n let endB = b.length;\n if (a.length < b.length) {\n endB = a.length;\n }\n // Create a back-reference for each index\n // that should be followed in case of a mismatch.\n // We only need B to make these references:\n const map = Array(endB);\n let k = 0; // Index that lags behind j\n map[0] = 0;\n for (let j = 1; j < endB; j++) {\n if (b[j] == b[k]) {\n map[j] = map[k]; // skip over the same character (optional optimisation)\n }\n else {\n map[j] = k;\n }\n while (k > 0 && b[j] != b[k]) {\n k = map[k];\n }\n if (b[j] == b[k]) {\n k++;\n }\n }\n // Phase 2: use these references while iterating over A\n k = 0;\n for (let i = startA; i < a.length; i++) {\n while (k > 0 && a[i] != b[k]) {\n k = map[k];\n }\n if (a[i] == b[k]) {\n k++;\n }\n }\n return k;\n}\n/**\n * Returns true if the string consistently uses Windows line endings.\n */\nexport function hasOnlyWinLineEndings(string) {\n return string.includes('\\r\\n') && !string.startsWith('\\n') && !string.match(/[^\\r]\\n/);\n}\n/**\n * Returns true if the string consistently uses Unix line endings.\n */\nexport function hasOnlyUnixLineEndings(string) {\n return !string.includes('\\r\\n') && string.includes('\\n');\n}\nexport function trailingWs(string) {\n // Yes, this looks overcomplicated and dumb - why not replace the whole function with\n // return string match(/\\s*$/)[0]\n // you ask? Because:\n // 1. the trap described at https://markamery.com/blog/quadratic-time-regexes/ would mean doing\n // this would cause this function to take O(n²) time in the worst case (specifically when\n // there is a massive run of NON-TRAILING whitespace in `string`), and\n // 2. the fix proposed in the same blog post, of using a negative lookbehind, is incompatible\n // with old Safari versions that we'd like to not break if possible (see\n // https://github.com/kpdecker/jsdiff/pull/550)\n // It feels absurd to do this with an explicit loop instead of a regex, but I really can't see a\n // better way that doesn't result in broken behaviour.\n let i;\n for (i = string.length - 1; i >= 0; i--) {\n if (!string[i].match(/\\s/)) {\n break;\n }\n }\n return string.substring(i + 1);\n}\nexport function leadingWs(string) {\n // Thankfully the annoying considerations described in trailingWs don't apply here:\n const match = string.match(/^\\s*/);\n return match ? match[0] : '';\n}\n","import Diff from './base.js';\nimport { longestCommonPrefix, longestCommonSuffix, replacePrefix, replaceSuffix, removePrefix, removeSuffix, maximumOverlap, leadingWs, trailingWs } from '../util/string.js';\n// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode\n//\n// Ranges and exceptions:\n// Latin-1 Supplement, 0080–00FF\n// - U+00D7 × Multiplication sign\n// - U+00F7 ÷ Division sign\n// Latin Extended-A, 0100–017F\n// Latin Extended-B, 0180–024F\n// IPA Extensions, 0250–02AF\n// Spacing Modifier Letters, 02B0–02FF\n// - U+02C7 ˇ &#711; Caron\n// - U+02D8 ˘ &#728; Breve\n// - U+02D9 ˙ &#729; Dot Above\n// - U+02DA ˚ &#730; Ring Above\n// - U+02DB ˛ &#731; Ogonek\n// - U+02DC ˜ &#732; Small Tilde\n// - U+02DD ˝ &#733; Double Acute Accent\n// Latin Extended Additional, 1E00–1EFF\nconst extendedWordChars = 'a-zA-Z0-9_\\\\u{C0}-\\\\u{FF}\\\\u{D8}-\\\\u{F6}\\\\u{F8}-\\\\u{2C6}\\\\u{2C8}-\\\\u{2D7}\\\\u{2DE}-\\\\u{2FF}\\\\u{1E00}-\\\\u{1EFF}';\n// Each token is one of the following:\n// - A punctuation mark plus the surrounding whitespace\n// - A word plus the surrounding whitespace\n// - Pure whitespace (but only in the special case where this the entire text\n// is just whitespace)\n//\n// We have to include surrounding whitespace in the tokens because the two\n// alternative approaches produce horribly broken results:\n// * If we just discard the whitespace, we can't fully reproduce the original\n// text from the sequence of tokens and any attempt to render the diff will\n// get the whitespace wrong.\n// * If we have separate tokens for whitespace, then in a typical text every\n// second token will be a single space character. But this often results in\n// the optimal diff between two texts being a perverse one that preserves\n// the spaces between words but deletes and reinserts actual common words.\n// See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640\n// for an example.\n//\n// Keeping the surrounding whitespace of course has implications for .equals\n// and .join, not just .tokenize.\n// This regex does NOT fully implement the tokenization rules described above.\n// Instead, it gives runs of whitespace their own \"token\". The tokenize method\n// then handles stitching whitespace tokens onto adjacent word or punctuation\n// tokens.\nconst tokenizeIncludingWhitespace = new RegExp(`[${extendedWordChars}]+|\\\\s+|[^${extendedWordChars}]`, 'ug');\nclass WordDiff extends Diff {\n equals(left, right, options) {\n if (options.ignoreCase) {\n left = left.toLowerCase();\n right = right.toLowerCase();\n }\n return left.trim() === right.trim();\n }\n tokenize(value, options = {}) {\n let parts;\n if (options.intlSegmenter) {\n const segmenter = options.intlSegmenter;\n if (segmenter.resolvedOptions().granularity != 'word') {\n throw new Error('The segmenter passed must have a granularity of \"word\"');\n }\n parts = Array.from(segmenter.segment(value), segment => segment.segment);\n }\n else {\n parts = value.match(tokenizeIncludingWhitespace) || [];\n }\n const tokens = [];\n let prevPart = null;\n parts.forEach(part => {\n if ((/\\s/).test(part)) {\n if (prevPart == null) {\n tokens.push(part);\n }\n else {\n tokens.push(tokens.pop() + part);\n }\n }\n else if (prevPart != null && (/\\s/).test(prevPart)) {\n if (tokens[tokens.length - 1] == prevPart) {\n tokens.push(tokens.pop() + part);\n }\n else {\n tokens.push(prevPart + part);\n }\n }\n else {\n tokens.push(part);\n }\n prevPart = part;\n });\n return tokens;\n }\n join(tokens) {\n // Tokens being joined here will always have appeared consecutively in the\n // same text, so we can simply strip off the leading whitespace from all the\n // tokens except the first (and except any whitespace-only tokens - but such\n // a token will always be the first and only token anyway) and then join them\n // and the whitespace around words and punctuation will end up correct.\n return tokens.map((token, i) => {\n if (i == 0) {\n return token;\n }\n else {\n return token.replace((/^\\s+/), '');\n }\n }).join('');\n }\n postProcess(changes, options) {\n if (!changes || options.oneChangePerToken) {\n return changes;\n }\n let lastKeep = null;\n // Change objects representing any insertion or deletion since the last\n // \"keep\" change object. There can be at most one of each.\n let insertion = null;\n let deletion = null;\n changes.forEach(change => {\n if (change.added) {\n insertion = change;\n }\n else if (change.removed) {\n deletion = change;\n }\n else {\n if (insertion || deletion) { // May be false at start of text\n dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change);\n }\n lastKeep = change;\n insertion = null;\n deletion = null;\n }\n });\n if (insertion || deletion) {\n dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null);\n }\n return changes;\n }\n}\nexport const wordDiff = new WordDiff();\nexport function diffWords(oldStr, newStr, options) {\n // This option has never been documented and never will be (it's clearer to\n // just call `diffWordsWithSpace` directly if you need that behavior), but\n // has existed in jsdiff for a long time, so we retain support for it here\n // for the sake of backwards compatibility.\n if ((options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) {\n return diffWordsWithSpace(oldStr, newStr, options);\n }\n return wordDiff.diff(oldStr, newStr, options);\n}\nfunction dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) {\n // Before returning, we tidy up the leading and trailing whitespace of the\n // change objects to eliminate cases where trailing whitespace in one object\n // is repeated as leading whitespace in the next.\n // Below are examples of the outcomes we want here to explain the code.\n // I=insert, K=keep, D=delete\n // 1. diffing 'foo bar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'\n // After cleanup, we want: K:'foo ' D:'bar ' K:'baz'\n //\n // 2. Diffing 'foo bar baz' vs 'foo qux baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz'\n // After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz'\n //\n // 3. Diffing 'foo\\nbar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:'\\nbar ' K:' baz'\n // After cleanup, we want K'foo' D:'\\nbar' K:' baz'\n //\n // 4. Diffing 'foo baz' vs 'foo\\nbar baz'\n // Prior to cleanup, we have K:'foo\\n' I:'\\nbar ' K:' baz'\n // After cleanup, we ideally want K'foo' I:'\\nbar' K:' baz'\n // but don't actually manage this currently (the pre-cleanup change\n // objects don't contain enough information to make it possible).\n //\n // 5. Diffing 'foo bar baz' vs 'foo baz'\n // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz'\n // After cleanup, we want K:'foo ' D:' bar ' K:'baz'\n //\n // Our handling is unavoidably imperfect in the case where there's a single\n // indel between keeps and the whitespace has changed. For instance, consider\n // diffing 'foo\\tbar\\nbaz' vs 'foo baz'. Unless we create an extra change\n // object to represent the insertion of the space character (which isn't even\n // a token), we have no way to avoid losing information about the texts'\n // original whitespace in the result we return. Still, we do our best to\n // output something that will look sensible if we e.g. print it with\n // insertions in green and deletions in red.\n // Between two \"keep\" change objects (or before the first or after the last\n // change object), we can have either:\n // * A \"delete\" followed by an \"insert\"\n // * Just an \"insert\"\n // * Just a \"delete\"\n // We handle the three cases separately.\n if (deletion && insertion) {\n const oldWsPrefix = leadingWs(deletion.value);\n const oldWsSuffix = trailingWs(deletion.value);\n const newWsPrefix = leadingWs(insertion.value);\n const newWsSuffix = trailingWs(insertion.value);\n if (startKeep) {\n const commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix);\n startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix);\n deletion.value = removePrefix(deletion.value, commonWsPrefix);\n insertion.value = removePrefix(insertion.value, commonWsPrefix);\n }\n if (endKeep) {\n const commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix);\n endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix);\n deletion.value = removeSuffix(deletion.value, commonWsSuffix);\n insertion.value = removeSuffix(insertion.value, commonWsSuffix);\n }\n }\n else if (insertion) {\n // The whitespaces all reflect what was in the new text rather than\n // the old, so we essentially have no information about whitespace\n // insertion or deletion. We just want to dedupe the whitespace.\n // We do that by having each change object keep its trailing\n // whitespace and deleting duplicate leading whitespace where\n // present.\n if (startKeep) {\n const ws = leadingWs(insertion.value);\n insertion.value = insertion.value.substring(ws.length);\n }\n if (endKeep) {\n const ws = leadingWs(endKeep.value);\n endKeep.value = endKeep.value.substring(ws.length);\n }\n // otherwise we've got a deletion and no insertion\n }\n else if (startKeep && endKeep) {\n const newWsFull = leadingWs(endKeep.value), delWsStart = leadingWs(deletion.value), delWsEnd = trailingWs(deletion.value);\n // Any whitespace that comes straight after startKeep in both the old and\n // new texts, assign to startKeep and remove from the deletion.\n const newWsStart = longestCommonPrefix(newWsFull, delWsStart);\n deletion.value = removePrefix(deletion.value, newWsStart);\n // Any whitespace that comes straight before endKeep in both the old and\n // new texts, and hasn't already been assigned to startKeep, assign to\n // endKeep and remove from the deletion.\n const newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd);\n deletion.value = removeSuffix(deletion.value, newWsEnd);\n endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd);\n // If there's any whitespace from the new text that HASN'T already been\n // assigned, assign it to the start:\n startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length));\n }\n else if (endKeep) {\n // We are at the start of the text. Preserve all the whitespace on\n // endKeep, and just remove whitespace from the end of deletion to the\n // extent that it overlaps with the start of endKeep.\n const endKeepWsPrefix = leadingWs(endKeep.value);\n const deletionWsSuffix = trailingWs(deletion.value);\n const overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix);\n deletion.value = removeSuffix(deletion.value, overlap);\n }\n else if (startKeep) {\n // We are at the END of the text. Preserve all the whitespace on\n // startKeep, and just remove whitespace from the start of deletion to\n // the extent that it overlaps with the end of startKeep.\n const startKeepWsSuffix = trailingWs(startKeep.value);\n const deletionWsPrefix = leadingWs(deletion.value);\n const overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix);\n deletion.value = removePrefix(deletion.value, overlap);\n }\n}\nclass WordsWithSpaceDiff extends Diff {\n tokenize(value) {\n // Slightly different to the tokenizeIncludingWhitespace regex used above in\n // that this one treats each individual newline as a distinct tokens, rather\n // than merging them into other surrounding whitespace. This was requested\n // in https://github.com/kpdecker/jsdiff/issues/180 &\n // https://github.com/kpdecker/jsdiff/issues/211\n const regex = new RegExp(`(\\\\r?\\\\n)|[${extendedWordChars}]+|[^\\\\S\\\\n\\\\r]+|[^${extendedWordChars}]`, 'ug');\n return value.match(regex) || [];\n }\n}\nexport const wordsWithSpaceDiff = new WordsWithSpaceDiff();\nexport function diffWordsWithSpace(oldStr, newStr, options) {\n return wordsWithSpaceDiff.diff(oldStr, newStr, options);\n}\n","export function generateOptions(options, defaults) {\n if (typeof options === 'function') {\n defaults.callback = options;\n }\n else if (options) {\n for (const name in options) {\n /* istanbul ignore else */\n if (Object.prototype.hasOwnProperty.call(options, name)) {\n defaults[name] = options[name];\n }\n }\n }\n return defaults;\n}\n","import Diff from './base.js';\nimport { generateOptions } from '../util/params.js';\nclass LineDiff extends Diff {\n constructor() {\n super(...arguments);\n this.tokenize = tokenize;\n }\n equals(left, right, options) {\n // If we're ignoring whitespace, we need to normalise lines by stripping\n // whitespace before checking equality. (This has an annoying interaction\n // with newlineIsToken that requires special handling: if newlines get their\n // own token, then we DON'T want to trim the *newline* tokens down to empty\n // strings, since this would cause us to treat whitespace-only line content\n // as equal to a separator between lines, which would be weird and\n // inconsistent with the documented behavior of the options.)\n if (options.ignoreWhitespace) {\n if (!options.newlineIsToken || !left.includes('\\n')) {\n left = left.trim();\n }\n if (!options.newlineIsToken || !right.includes('\\n')) {\n right = right.trim();\n }\n }\n else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {\n if (left.endsWith('\\n')) {\n left = left.slice(0, -1);\n }\n if (right.endsWith('\\n')) {\n right = right.slice(0, -1);\n }\n }\n return super.equals(left, right, options);\n }\n}\nexport const lineDiff = new LineDiff();\nexport function diffLines(oldStr, newStr, options) {\n return lineDiff.diff(oldStr, newStr, options);\n}\nexport function diffTrimmedLines(oldStr, newStr, options) {\n options = generateOptions(options, { ignoreWhitespace: true });\n return lineDiff.diff(oldStr, newStr, options);\n}\n// Exported standalone so it can be used from jsonDiff too.\nexport function tokenize(value, options) {\n if (options.stripTrailingCr) {\n // remove one \\r before \\n to match GNU diff's --strip-trailing-cr behavior\n value = value.replace(/\\r\\n/g, '\\n');\n }\n const retLines = [], linesAndNewlines = value.split(/(\\n|\\r\\n)/);\n // Ignore the final empty token that occurs if the string ends with a new line\n if (!linesAndNewlines[linesAndNewlines.length - 1]) {\n linesAndNewlines.pop();\n }\n // Merge the content and line separators into single tokens\n for (let i = 0; i < linesAndNewlines.length; i++) {\n const line = linesAndNewlines[i];\n if (i % 2 && !options.newlineIsToken) {\n retLines[retLines.length - 1] += line;\n }\n else {\n retLines.push(line);\n }\n }\n return retLines;\n}\n","import Diff from './base.js';\nfunction isSentenceEndPunct(char) {\n return char == '.' || char == '!' || char == '?';\n}\nclass SentenceDiff extends Diff {\n tokenize(value) {\n var _a;\n // If in future we drop support for environments that don't support lookbehinds, we can replace\n // this entire function with:\n // return value.split(/(?<=[.!?])(\\s+|$)/);\n // but until then, for similar reasons to the trailingWs function in string.ts, we are forced\n // to do this verbosely \"by hand\" instead of using a regex.\n const result = [];\n let tokenStartI = 0;\n for (let i = 0; i < value.length; i++) {\n if (i == value.length - 1) {\n result.push(value.slice(tokenStartI));\n break;\n }\n if (isSentenceEndPunct(value[i]) && value[i + 1].match(/\\s/)) {\n // We've hit a sentence break - i.e. a punctuation mark followed by whitespace.\n // We now want to push TWO tokens to the result:\n // 1. the sentence\n result.push(value.slice(tokenStartI, i + 1));\n // 2. the whitespace\n i = tokenStartI = i + 1;\n while ((_a = value[i + 1]) === null || _a === void 0 ? void 0 : _a.match(/\\s/)) {\n i++;\n }\n result.push(value.slice(tokenStartI, i + 1));\n // Then the next token (a sentence) starts on the character after the whitespace.\n // (It's okay if this is off the end of the string - then the outer loop will terminate\n // here anyway.)\n tokenStartI = i + 1;\n }\n }\n return result;\n }\n}\nexport const sentenceDiff = new SentenceDiff();\nexport function diffSentences(oldStr, newStr, options) {\n return sentenceDiff.diff(oldStr, newStr, options);\n}\n","import Diff from './base.js';\nclass CssDiff extends Diff {\n tokenize(value) {\n return value.split(/([{}:;,]|\\s+)/);\n }\n}\nexport const cssDiff = new CssDiff();\nexport function diffCss(oldStr, newStr, options) {\n return cssDiff.diff(oldStr, newStr, options);\n}\n","import Diff from './base.js';\nimport { tokenize } from './line.js';\nclass JsonDiff extends Diff {\n constructor() {\n super(...arguments);\n this.tokenize = tokenize;\n }\n get useLongestToken() {\n // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a\n // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:\n return true;\n }\n castInput(value, options) {\n const { undefinedReplacement, stringifyReplacer = (k, v) => typeof v === 'undefined' ? undefinedReplacement : v } = options;\n return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), null, ' ');\n }\n equals(left, right, options) {\n return super.equals(left.replace(/,([\\r\\n])/g, '$1'), right.replace(/,([\\r\\n])/g, '$1'), options);\n }\n}\nexport const jsonDiff = new JsonDiff();\nexport function diffJson(oldStr, newStr, options) {\n return jsonDiff.diff(oldStr, newStr, options);\n}\n// This function handles the presence of circular references by bailing out when encountering an\n// object that is already on the \"stack\" of items being processed. Accepts an optional replacer\nexport function canonicalize(obj, stack, replacementStack, replacer, key) {\n stack = stack || [];\n replacementStack = replacementStack || [];\n if (replacer) {\n obj = replacer(key === undefined ? '' : key, obj);\n }\n let i;\n for (i = 0; i < stack.length; i += 1) {\n if (stack[i] === obj) {\n return replacementStack[i];\n }\n }\n let canonicalizedObj;\n if ('[object Array]' === Object.prototype.toString.call(obj)) {\n stack.push(obj);\n canonicalizedObj = new Array(obj.length);\n replacementStack.push(canonicalizedObj);\n for (i = 0; i < obj.length; i += 1) {\n canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, String(i));\n }\n stack.pop();\n replacementStack.pop();\n return canonicalizedObj;\n }\n if (obj && obj.toJSON) {\n obj = obj.toJSON();\n }\n if (typeof obj === 'object' && obj !== null) {\n stack.push(obj);\n canonicalizedObj = {};\n replacementStack.push(canonicalizedObj);\n const sortedKeys = [];\n let key;\n for (key in obj) {\n /* istanbul ignore else */\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n sortedKeys.push(key);\n }\n }\n sortedKeys.sort();\n for (i = 0; i < sortedKeys.length; i += 1) {\n key = sortedKeys[i];\n canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack, replacer, key);\n }\n stack.pop();\n replacementStack.pop();\n }\n else {\n canonicalizedObj = obj;\n }\n return canonicalizedObj;\n}\n","import Diff from './base.js';\nclass ArrayDiff extends Diff {\n tokenize(value) {\n return value.slice();\n }\n join(value) {\n return value;\n }\n removeEmpty(value) {\n return value;\n }\n}\nexport const arrayDiff = new ArrayDiff();\nexport function diffArrays(oldArr, newArr, options) {\n return arrayDiff.diff(oldArr, newArr, options);\n}\n","export function unixToWin(patch) {\n if (Array.isArray(patch)) {\n // It would be cleaner if instead of the line below we could just write\n // return patch.map(unixToWin)\n // but mysteriously TypeScript (v5.7.3 at the time of writing) does not like this and it will\n // refuse to compile, thinking that unixToWin could then return StructuredPatch[][] and the\n // result would be incompatible with the overload signatures.\n // See bug report at https://github.com/microsoft/TypeScript/issues/61398.\n return patch.map(p => unixToWin(p));\n }\n return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map((line, i) => {\n var _a;\n return (line.startsWith('\\\\') || line.endsWith('\\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\\\')))\n ? line\n : line + '\\r';\n }) }))) });\n}\nexport function winToUnix(patch) {\n if (Array.isArray(patch)) {\n // (See comment above equivalent line in unixToWin)\n return patch.map(p => winToUnix(p));\n }\n return Object.assign(Object.assign({}, patch), { hunks: patch.hunks.map(hunk => (Object.assign(Object.assign({}, hunk), { lines: hunk.lines.map(line => line.endsWith('\\r') ? line.substring(0, line.length - 1) : line) }))) });\n}\n/**\n * Returns true if the patch consistently uses Unix line endings (or only involves one line and has\n * no line endings).\n */\nexport function isUnix(patch) {\n if (!Array.isArray(patch)) {\n patch = [patch];\n }\n return !patch.some(index => index.hunks.some(hunk => hunk.lines.some(line => !line.startsWith('\\\\') && line.endsWith('\\r'))));\n}\n/**\n * Returns true if the patch uses Windows line endings and only Windows line endings.\n */\nexport function isWin(patch) {\n if (!Array.isArray(patch)) {\n patch = [patch];\n }\n return patch.some(index => index.hunks.some(hunk => hunk.lines.some(line => line.endsWith('\\r'))))\n && patch.every(index => index.hunks.every(hunk => hunk.lines.every((line, i) => { var _a; return line.startsWith('\\\\') || line.endsWith('\\r') || ((_a = hunk.lines[i + 1]) === null || _a === void 0 ? void 0 : _a.startsWith('\\\\')); })));\n}\n","/**\n * Parses a patch into structured data, in the same structure returned by `structuredPatch`.\n *\n * @return a JSON object representation of the a patch, suitable for use with the `applyPatch` method.\n */\nexport function parsePatch(uniDiff) {\n const diffstr = uniDiff.split(/\\n/), list = [];\n let i = 0;\n function parseIndex() {\n const index = {};\n list.push(index);\n // Parse diff metadata\n while (i < diffstr.length) {\n const line = diffstr[i];\n // File header found, end parsing diff metadata\n if ((/^(---|\\+\\+\\+|@@)\\s/).test(line)) {\n break;\n }\n // Diff index\n const header = (/^(?:Index:|diff(?: -r \\w+)+)\\s+(.+?)\\s*$/).exec(line);\n if (header) {\n index.index = header[1];\n }\n i++;\n }\n // Parse file headers if they are defined. Unified diff requires them, but\n // there's no technical issues to have an isolated hunk without file header\n parseFileHeader(index);\n parseFileHeader(index);\n // Parse hunks\n index.hunks = [];\n while (i < diffstr.length) {\n const line = diffstr[i];\n if ((/^(Index:\\s|diff\\s|---\\s|\\+\\+\\+\\s|===================================================================)/).test(line)) {\n break;\n }\n else if ((/^@@/).test(line)) {\n index.hunks.push(parseHunk());\n }\n else if (line) {\n throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(line));\n }\n else {\n i++;\n }\n }\n }\n // Parses the --- and +++ headers, if none are found, no lines\n // are consumed.\n function parseFileHeader(index) {\n const fileHeader = (/^(---|\\+\\+\\+)\\s+(.*)\\r?$/).exec(diffstr[i]);\n if (fileHeader) {\n const data = fileHeader[2].split('\\t', 2), header = (data[1] || '').trim();\n let fileName = data[0].replace(/\\\\\\\\/g, '\\\\');\n if ((/^\".*\"$/).test(fileName)) {\n fileName = fileName.substr(1, fileName.length - 2);\n }\n if (fileHeader[1] === '---') {\n index.oldFileName = fileName;\n index.oldHeader = header;\n }\n else {\n index.newFileName = fileName;\n index.newHeader = header;\n }\n i++;\n }\n }\n // Parses a hunk\n // This assumes that we are at the start of a hunk.\n function parseHunk() {\n var _a;\n const chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/);\n const hunk = {\n oldStart: +chunkHeader[1],\n oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],\n newStart: +chunkHeader[3],\n newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],\n lines: []\n };\n // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n if (hunk.oldLines === 0) {\n hunk.oldStart += 1;\n }\n if (hunk.newLines === 0) {\n hunk.newStart += 1;\n }\n let addCount = 0, removeCount = 0;\n for (; i < diffstr.length && (removeCount < hunk.oldLines || addCount < hunk.newLines || ((_a = diffstr[i]) === null || _a === void 0 ? void 0 : _a.startsWith('\\\\'))); i++) {\n const operation = (diffstr[i].length == 0 && i != (diffstr.length - 1)) ? ' ' : diffstr[i][0];\n if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\\\') {\n hunk.lines.push(diffstr[i]);\n if (operation === '+') {\n addCount++;\n }\n else if (operation === '-') {\n removeCount++;\n }\n else if (operation === ' ') {\n addCount++;\n removeCount++;\n }\n }\n else {\n throw new Error(`Hunk at line ${chunkHeaderIndex + 1} contained invalid line ${diffstr[i]}`);\n }\n }\n // Handle the empty block count case\n if (!addCount && hunk.newLines === 1) {\n hunk.newLines = 0;\n }\n if (!removeCount && hunk.oldLines === 1) {\n hunk.oldLines = 0;\n }\n // Perform sanity checking\n if (addCount !== hunk.newLines) {\n throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n if (removeCount !== hunk.oldLines) {\n throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n return hunk;\n }\n while (i < diffstr.length) {\n parseIndex();\n }\n return list;\n}\n","// Iterator that traverses in the range of [min, max], stepping\n// by distance from a given start position. I.e. for [0, 4], with\n// start of 2, this will iterate 2, 3, 1, 4, 0.\nexport default function (start, minLine, maxLine) {\n let wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1;\n return function iterator() {\n if (wantForward && !forwardExhausted) {\n if (backwardExhausted) {\n localOffset++;\n }\n else {\n wantForward = false;\n }\n // Check if trying to fit beyond text length, and if not, check it fits\n // after offset location (or desired location on first iteration)\n if (start + localOffset <= maxLine) {\n return start + localOffset;\n }\n forwardExhausted = true;\n }\n if (!backwardExhausted) {\n if (!forwardExhausted) {\n wantForward = true;\n }\n // Check if trying to fit before text beginning, and if not, check it fits\n // before offset location\n if (minLine <= start - localOffset) {\n return start - localOffset++;\n }\n backwardExhausted = true;\n return iterator();\n }\n // We tried to fit hunk before text beginning and beyond text length, then\n // hunk can't fit on the text. Return undefined\n return undefined;\n };\n}\n","import { hasOnlyWinLineEndings, hasOnlyUnixLineEndings } from '../util/string.js';\nimport { isWin, isUnix, unixToWin, winToUnix } from './line-endings.js';\nimport { parsePatch } from './parse.js';\nimport distanceIterator from '../util/distance-iterator.js';\n/**\n * attempts to apply a unified diff patch.\n *\n * Hunks are applied first to last.\n * `applyPatch` first tries to apply the first hunk at the line number specified in the hunk header, and with all context lines matching exactly.\n * 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.\n * 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.\n * 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.\n *\n * Once a hunk is successfully fitted, the process begins again with the next hunk.\n * Regardless of `fuzzFactor`, later hunks must be applied later in the file than earlier hunks.\n *\n * If a hunk cannot be successfully fitted *anywhere* with fewer than `fuzzFactor` mismatches, `applyPatch` fails and returns `false`.\n *\n * 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.\n * (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.)\n *\n * If the patch was applied successfully, returns a string containing the patched text.\n * 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.\n *\n * @param patch a string diff or the output from the `parsePatch` or `structuredPatch` methods.\n */\nexport function applyPatch(source, patch, options = {}) {\n let patches;\n if (typeof patch === 'string') {\n patches = parsePatch(patch);\n }\n else if (Array.isArray(patch)) {\n patches = patch;\n }\n else {\n patches = [patch];\n }\n if (patches.length > 1) {\n throw new Error('applyPatch only works with a single input.');\n }\n return applyStructuredPatch(source, patches[0], options);\n}\nfunction applyStructuredPatch(source, patch, options = {}) {\n if (options.autoConvertLineEndings || options.autoConvertLineEndings == null) {\n if (hasOnlyWinLineEndings(source) && isUnix(patch)) {\n patch = unixToWin(patch);\n }\n else if (hasOnlyUnixLineEndings(source) && isWin(patch)) {\n patch = winToUnix(patch);\n }\n }\n // Apply the diff to the input\n const lines = source.split('\\n'), hunks = patch.hunks, compareLine = options.compareLine || ((lineNumber, line, operation, patchContent) => line === patchContent), fuzzFactor = options.fuzzFactor || 0;\n let minLine = 0;\n if (fuzzFactor < 0 || !Number.isInteger(fuzzFactor)) {\n throw new Error('fuzzFactor must be a non-negative integer');\n }\n // Special case for empty patch.\n if (!hunks.length) {\n return source;\n }\n // Before anything else, handle EOFNL insertion/removal. If the patch tells us to make a change\n // to the EOFNL that is redundant/impossible - i.e. to remove a newline that's not there, or add a\n // newline that already exists - then we either return false and fail to apply the patch (if\n // fuzzFactor is 0) or simply ignore the problem and do nothing (if fuzzFactor is >0).\n // If we do need to remove/add a newline at EOF, this will always be in the final hunk:\n let prevLine = '', removeEOFNL = false, addEOFNL = false;\n for (let i = 0; i < hunks[hunks.length - 1].lines.length; i++) {\n const line = hunks[hunks.length - 1].lines[i];\n if (line[0] == '\\\\') {\n if (prevLine[0] == '+') {\n removeEOFNL = true;\n }\n else if (prevLine[0] == '-') {\n addEOFNL = true;\n }\n }\n prevLine = line;\n }\n if (removeEOFNL) {\n if (addEOFNL) {\n // This means the final line gets changed but doesn't have a trailing newline in either the\n // original or patched version. In that case, we do nothing if fuzzFactor > 0, and if\n // fuzzFactor is 0, we simply validate that the source file has no trailing newline.\n if (!fuzzFactor && lines[lines.length - 1] == '') {\n return false;\n }\n }\n else if (lines[lines.length - 1] == '') {\n lines.pop();\n }\n else if (!fuzzFactor) {\n return false;\n }\n }\n else if (addEOFNL) {\n if (lines[lines.length - 1] != '') {\n lines.push('');\n }\n else if (!fuzzFactor) {\n return false;\n }\n }\n /**\n * Checks if the hunk can be made to fit at the provided location with at most `maxErrors`\n * insertions, substitutions, or deletions, while ensuring also that:\n * - lines deleted in the hunk match exactly, and\n * - wherever an insertion operation or block of insertion operations appears in the hunk, the\n * immediately preceding and following lines of context match exactly\n *\n * `toPos` should be set such that lines[toPos] is meant to match hunkLines[0].\n *\n * If the hunk can be applied, returns an object with properties `oldLineLastI` and\n * `replacementLines`. Otherwise, returns null.\n */\n function applyHunk(hunkLines, toPos, maxErrors, hunkLinesI = 0, lastContextLineMatched = true, patchedLines = [], patchedLinesLength = 0) {\n let nConsecutiveOldContextLines = 0;\n let nextContextLineMustMatch = false;\n for (; hunkLinesI < hunkLines.length; hunkLinesI++) {\n const hunkLine = hunkLines[hunkLinesI], operation = (hunkLine.length > 0 ? hunkLine[0] : ' '), content = (hunkLine.length > 0 ? hunkLine.substr(1) : hunkLine);\n if (operation === '-') {\n if (compareLine(toPos + 1, lines[toPos], operation, content)) {\n toPos++;\n nConsecutiveOldContextLines = 0;\n }\n else {\n if (!maxErrors || lines[toPos] == null) {\n return null;\n }\n patchedLines[patchedLinesLength] = lines[toPos];\n return applyHunk(hunkLines, toPos + 1, maxErrors - 1, hunkLinesI, false, patchedLines, patchedLinesLength + 1);\n }\n }\n if (operation === '+') {\n if (!lastContextLineMatched) {\n return null;\n }\n patchedLines[patchedLinesLength] = content;\n patchedLinesLength++;\n nConsecutiveOldContextLines = 0;\n nextContextLineMustMatch = true;\n }\n if (operation === ' ') {\n nConsecutiveOldContextLines++;\n patchedLines[patchedLinesLength] = lines[toPos];\n if (compareLine(toPos + 1, lines[toPos], operation, content)) {\n patchedLinesLength++;\n lastContextLineMatched = true;\n nextContextLineMustMatch = false;\n toPos++;\n }\n else {\n if (nextContextLineMustMatch || !maxErrors) {\n return null;\n }\n // Consider 3 possibilities in sequence:\n // 1. lines contains a *substitution* not included in the patch context, or\n // 2. lines contains an *insertion* not included in the patch context, or\n // 3. lines contains a *deletion* not included in the patch context\n // The first two options are of course only possible if the line from lines is non-null -\n // i.e. only option 3 is possible if we've overrun the end of the old file.\n 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));\n }\n }\n }\n // Before returning, trim any unmodified context lines off the end of patchedLines and reduce\n // toPos (and thus oldLineLastI) accordingly. This allows later hunks to be applied to a region\n // that starts in this hunk's trailing context.\n patchedLinesLength -= nConsecutiveOldContextLines;\n toPos -= nConsecutiveOldContextLines;\n patchedLines.length = patchedLinesLength;\n return {\n patchedLines,\n oldLineLastI: toPos - 1\n };\n }\n const resultLines = [];\n // Search best fit offsets for each hunk based on the previous ones\n let prevHunkOffset = 0;\n for (let i = 0; i < hunks.length; i++) {\n const hunk = hunks[i];\n let hunkResult;\n const maxLine = lines.length - hunk.oldLines + fuzzFactor;\n let toPos;\n for (let maxErrors = 0; maxErrors <= fuzzFactor; maxErrors++) {\n toPos = hunk.oldStart + prevHunkOffset - 1;\n const iterator = distanceIterator(toPos, minLine, maxLine);\n for (; toPos !== undefined; toPos = iterator()) {\n hunkResult = applyHunk(hunk.lines, toPos, maxErrors);\n if (hunkResult) {\n break;\n }\n }\n if (hunkResult) {\n break;\n }\n }\n if (!hunkResult) {\n return false;\n }\n // Copy everything from the end of where we applied the last hunk to the start of this hunk\n for (let i = minLine; i < toPos; i++) {\n resultLines.push(lines[i]);\n }\n // Add the lines produced by applying the hunk:\n for (let i = 0; i < hunkResult.patchedLines.length; i++) {\n const line = hunkResult.patchedLines[i];\n resultLines.push(line);\n }\n // Set lower text limit to end of the current hunk, so next ones don't try\n // to fit over already patched text\n minLine = hunkResult.oldLineLastI + 1;\n // Note the offset between where the patch said the hunk should've applied and where we\n // applied it, so we can adjust future hunks accordingly:\n prevHunkOffset = toPos + 1 - hunk.oldStart;\n }\n // Copy over the rest of the lines from the old text\n for (let i = minLine; i < lines.length; i++) {\n resultLines.push(lines[i]);\n }\n return resultLines.join('\\n');\n}\n/**\n * applies one or more patches.\n *\n * `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).\n *\n * 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:\n *\n * - `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.\n * - `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.\n *\n * Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made.\n */\nexport function applyPatches(uniDiff, options) {\n const spDiff = typeof uniDiff === 'string' ? parsePatch(uniDiff) : uniDiff;\n let currentIndex = 0;\n function processIndex() {\n const index = spDiff[currentIndex++];\n if (!index) {\n return options.complete();\n }\n options.loadFile(index, function (err, data) {\n if (err) {\n return options.complete(err);\n }\n const updatedContent = applyPatch(data, index, options);\n options.patched(index, updatedContent, function (err) {\n if (err) {\n return options.complete(err);\n }\n processIndex();\n });\n });\n }\n processIndex();\n}\n","export function reversePatch(structuredPatch) {\n if (Array.isArray(structuredPatch)) {\n // (See comment in unixToWin for why we need the pointless-looking anonymous function here)\n return structuredPatch.map(patch => reversePatch(patch)).reverse();\n }\n return Object.assign(Object.assign({}, structuredPatch), { oldFileName: structuredPatch.newFileName, oldHeader: structuredPatch.newHeader, newFileName: structuredPatch.oldFileName, newHeader: structuredPatch.oldHeader, hunks: structuredPatch.hunks.map(hunk => {\n return {\n oldLines: hunk.newLines,\n oldStart: hunk.newStart,\n newLines: hunk.oldLines,\n newStart: hunk.oldStart,\n lines: hunk.lines.map(l => {\n if (l.startsWith('-')) {\n return `+${l.slice(1)}`;\n }\n if (l.startsWith('+')) {\n return `-${l.slice(1)}`;\n }\n return l;\n })\n };\n }) });\n}\n","import { diffLines } from '../diff/line.js';\nexport function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n let optionsObj;\n if (!options) {\n optionsObj = {};\n }\n else if (typeof options === 'function') {\n optionsObj = { callback: options };\n }\n else {\n optionsObj = options;\n }\n if (typeof optionsObj.context === 'undefined') {\n optionsObj.context = 4;\n }\n // We copy this into its own variable to placate TypeScript, which thinks\n // optionsObj.context might be undefined in the callbacks below.\n const context = optionsObj.context;\n // @ts-expect-error (runtime check for something that is correctly a static type error)\n if (optionsObj.newlineIsToken) {\n throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions');\n }\n if (!optionsObj.callback) {\n return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));\n }\n else {\n const { callback } = optionsObj;\n diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => {\n const patch = diffLinesResultToPatch(diff);\n // TypeScript is unhappy without the cast because it does not understand that `patch` may\n // be undefined here only if `callback` is StructuredPatchCallbackAbortable:\n callback(patch);\n } }));\n }\n function diffLinesResultToPatch(diff) {\n // STEP 1: Build up the patch with no \"\\" lines and with the arrays\n // of lines containing trailing newline characters. We'll tidy up later...\n if (!diff) {\n return;\n }\n diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier\n function contextLines(lines) {\n return lines.map(function (entry) { return ' ' + entry; });\n }\n const hunks = [];\n let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;\n for (let i = 0; i < diff.length; i++) {\n const current = diff[i], lines = current.lines || splitLines(current.value);\n current.lines = lines;\n if (current.added || current.removed) {\n // If we have previous context, start with that\n if (!oldRangeStart) {\n const prev = diff[i - 1];\n oldRangeStart = oldLine;\n newRangeStart = newLine;\n if (prev) {\n curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : [];\n oldRangeStart -= curRange.length;\n newRangeStart -= curRange.length;\n }\n }\n // Output our changes\n for (const line of lines) {\n curRange.push((current.added ? '+' : '-') + line);\n }\n // Track the updated file position\n if (current.added) {\n newLine += lines.length;\n }\n else {\n oldLine += lines.length;\n }\n }\n else {\n // Identical context lines. Track line changes\n if (oldRangeStart) {\n // Close out any changes that have been output (or join overlapping)\n if (lines.length <= context * 2 && i < diff.length - 2) {\n // Overlapping\n for (const line of contextLines(lines)) {\n curRange.push(line);\n }\n }\n else {\n // end the range and output\n const contextSize = Math.min(lines.length, context);\n for (const line of contextLines(lines.slice(0, contextSize))) {\n curRange.push(line);\n }\n const hunk = {\n oldStart: oldRangeStart,\n oldLines: (oldLine - oldRangeStart + contextSize),\n newStart: newRangeStart,\n newLines: (newLine - newRangeStart + contextSize),\n lines: curRange\n };\n hunks.push(hunk);\n oldRangeStart = 0;\n newRangeStart = 0;\n curRange = [];\n }\n }\n oldLine += lines.length;\n newLine += lines.length;\n }\n }\n // Step 2: eliminate the trailing `\\n` from each line of each hunk, and, where needed, add\n // \"\\".\n for (const hunk of hunks) {\n for (let i = 0; i < hunk.lines.length; i++) {\n if (hunk.lines[i].endsWith('\\n')) {\n hunk.lines[i] = hunk.lines[i].slice(0, -1);\n }\n else {\n hunk.lines.splice(i + 1, 0, '\\\');\n i++; // Skip the line we just added, then continue iterating\n }\n }\n }\n return {\n oldFileName: oldFileName, newFileName: newFileName,\n oldHeader: oldHeader, newHeader: newHeader,\n hunks: hunks\n };\n }\n}\n/**\n * creates a unified diff patch.\n * @param patch either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`)\n */\nexport function formatPatch(patch) {\n if (Array.isArray(patch)) {\n return patch.map(formatPatch).join('\\n');\n }\n const ret = [];\n if (patch.oldFileName == patch.newFileName) {\n ret.push('Index: ' + patch.oldFileName);\n }\n ret.push('===================================================================');\n ret.push('--- ' + patch.oldFileName + (typeof patch.oldHeader === 'undefined' ? '' : '\\t' + patch.oldHeader));\n ret.push('+++ ' + patch.newFileName + (typeof patch.newHeader === 'undefined' ? '' : '\\t' + patch.newHeader));\n for (let i = 0; i < patch.hunks.length; i++) {\n const hunk = patch.hunks[i];\n // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n if (hunk.oldLines === 0) {\n hunk.oldStart -= 1;\n }\n if (hunk.newLines === 0) {\n hunk.newStart -= 1;\n }\n ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines\n + ' +' + hunk.newStart + ',' + hunk.newLines\n + ' @@');\n for (const line of hunk.lines) {\n ret.push(line);\n }\n }\n return ret.join('\\n') + '\\n';\n}\nexport function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n if (typeof options === 'function') {\n options = { callback: options };\n }\n if (!(options === null || options === void 0 ? void 0 : options.callback)) {\n const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);\n if (!patchObj) {\n return;\n }\n return formatPatch(patchObj);\n }\n else {\n const { callback } = options;\n structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: patchObj => {\n if (!patchObj) {\n callback(undefined);\n }\n else {\n callback(formatPatch(patchObj));\n }\n } }));\n }\n}\nexport function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {\n return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);\n}\n/**\n * Split `text` into an array of lines, including the trailing newline character (where present)\n */\nfunction splitLines(text) {\n const hasTrailingNl = text.endsWith('\\n');\n const result = text.split('\\n').map(line => line + '\\n');\n if (hasTrailingNl) {\n result.pop();\n }\n else {\n result.push(result.pop().slice(0, -1));\n }\n return result;\n}\n","/**\n * converts a list of change objects to the format returned by Google's [diff-match-patch](https://github.com/google/diff-match-patch) library\n */\nexport function convertChangesToDMP(changes) {\n const ret = [];\n let change, operation;\n for (let i = 0; i < changes.length; i++) {\n change = changes[i];\n if (change.added) {\n operation = 1;\n }\n else if (change.removed) {\n operation = -1;\n }\n else {\n operation = 0;\n }\n ret.push([operation, change.value]);\n }\n return ret;\n}\n","/**\n * converts a list of change objects to a serialized XML format\n */\nexport function convertChangesToXML(changes) {\n const ret = [];\n for (let i = 0; i < changes.length; i++) {\n const change = changes[i];\n if (change.added) {\n ret.push('<ins>');\n }\n else if (change.removed) {\n ret.push('<del>');\n }\n ret.push(escapeHTML(change.value));\n if (change.added) {\n ret.push('</ins>');\n }\n else if (change.removed) {\n ret.push('</del>');\n }\n }\n return ret.join('');\n}\nfunction escapeHTML(s) {\n let n = s;\n n = n.replace(/&/g, '&amp;');\n n = n.replace(/</g, '&lt;');\n n = n.replace(/>/g, '&gt;');\n n = n.replace(/\"/g, '&quot;');\n return n;\n}\n","/**\r\n * Provides the JsDiff library to InPageEdit.\r\n *\r\n * @see https://github.com/kpdecker/jsdiff\r\n */\r\n\r\nimport { InPageEdit } from '@/InPageEdit'\r\nimport * as JsDiff from 'diff'\r\n\r\ndeclare module '@/InPageEdit' {\r\n interface InPageEdit {\r\n jsdiff: JsDiffService\r\n }\r\n}\r\n\r\nexport type JsDiffDiffType =\r\n | 'diffChars'\r\n | 'diffWords'\r\n | 'diffWordsWithSpace'\r\n | 'diffLines'\r\n | 'diffTrimmedLines'\r\n | 'diffSentences'\r\n | 'diffCss'\r\n | 'diffJson'\r\n | 'diffArrays'\r\n | 'createTwoFilesPatch'\r\n\r\nexport class JsDiffService {\r\n constructor(public ctx: InPageEdit) {\r\n this.ctx.set('jsdiff', this)\r\n }\r\n JsDiff = JsDiff\r\n diffChars = JsDiff.diffChars\r\n diffWords = JsDiff.diffWords\r\n diffWordsWithSpace = JsDiff.diffWordsWithSpace\r\n diffLines = JsDiff.diffLines\r\n diffTrimmedLines = JsDiff.diffTrimmedLines\r\n diffSentences = JsDiff.diffSentences\r\n diffCss = JsDiff.diffCss\r\n diffJson = JsDiff.diffJson\r\n diffArrays = JsDiff.diffArrays\r\n createTwoFilesPatch = JsDiff.createTwoFilesPatch\r\n}\r\n","import { InPageEdit } from '@/InPageEdit'\r\n\r\nexport const MwUserLinks = (props: { user: string; target?: string; ctx: InPageEdit }) => {\r\n let { user, target, ctx } = props\r\n const getUrl = ctx.getUrl.bind(ctx)\r\n return (\r\n <span className=\"mw-userlinks\">\r\n <a href={getUrl(`User:${user}`)} className=\"mw-userlink\" target={target}>\r\n {user}\r\n </a>{' '}\r\n <span className=\"mw-usertoollinks\">\r\n (\r\n <a href={getUrl(`User_talk:${user}`)} className=\"mw-usertoollinks-talk\" target={target}>\r\n talk\r\n </a>\r\n {' | '}\r\n <a\r\n href={getUrl(`Special:Contributions/${user}`)}\r\n className=\"mw-usertoollinks-contribs\"\r\n target={target}\r\n >\r\n contribs\r\n </a>\r\n {' | '}\r\n <a\r\n href={getUrl(`Special:Block/${user}`)}\r\n className=\"mw-usertoollinks-block\"\r\n target={target}\r\n >\r\n block\r\n </a>\r\n )\r\n </span>\r\n </span>\r\n )\r\n}\r\n","import './style.scss'\r\nimport { JSX } from 'jsx-dom/jsx-runtime'\r\nimport { CompareApiResponse } from '../PluginQuickDiffCore'\r\nimport { InPageEdit } from '@/InPageEdit'\r\n\r\nexport type DiffTableProps = {\r\n data: Partial<CompareApiResponse['compare']>\r\n ctx: InPageEdit\r\n} & JSX.IntrinsicElements['table']\r\n\r\nexport enum DiffTableEvent {\r\n update = 'ipe:diff-table/update',\r\n edit = 'ipe:diff-table/edit',\r\n}\r\n\r\n// DOM 事件类型定义\r\ndeclare global {\r\n interface HTMLElementEventMap {\r\n [DiffTableEvent.update]: CustomEvent<{\r\n fromrev: number\r\n torev: number\r\n }>\r\n [DiffTableEvent.edit]: CustomEvent<{\r\n revid: number\r\n }>\r\n }\r\n}\r\n\r\nconst formatDate = new Intl.DateTimeFormat(undefined, {\r\n dateStyle: 'medium',\r\n timeStyle: 'medium',\r\n}).format\r\n\r\nconst DiffTableHeader = (props: {\r\n ctx: InPageEdit\r\n type?: 'from' | 'to'\r\n pageid?: number\r\n pagetitle?: string\r\n revid?: number\r\n size?: number\r\n timestamp?: string\r\n username?: string\r\n userid?: number\r\n comment?: string\r\n parsedcomment?: string\r\n}) => {\r\n let classList = ['diff-title']\r\n if (props.type === 'from') {\r\n classList.push('diff-otitle')\r\n } else if (props.type === 'to') {\r\n classList.push('diff-ntitle')\r\n }\r\n if (!props.pageid || !props.userid) {\r\n return (\r\n <td colSpan={2} className={classList}>\r\n <div className=\"mw-diff-title--title\">\r\n {props.type === 'from' ? 'Original content' : props.type === 'to' ? 'Your content' : ''}\r\n </div>\r\n </td>\r\n )\r\n }\r\n const handleEditClick = (e: Event) => {\r\n e.preventDefault()\r\n e.target!.dispatchEvent(\r\n new CustomEvent(DiffTableEvent.edit, {\r\n detail: { revid: props.revid! },\r\n bubbles: true,\r\n })\r\n )\r\n }\r\n return (\r\n <td colSpan={2} className={classList}>\r\n <div className=\"mw-diff-title--title\">\r\n {props.pagetitle || props.timestamp}\r\n {props.revid ? ` (rev#${props.revid})` : ''}\r\n </div>\r\n <div className=\"mw-diff-title--actions\">\r\n <a\r\n href={props.ctx.getUrl('', { action: 'edit', oldid: props.revid! })}\r\n onClick={handleEditClick}\r\n >\r\n <IconQuickEdit style=\"width: 1em; height: 1em\" />\r\n Quick edit\r\n </a>\r\n </div>\r\n <div className=\"mw-diff-title--user\">\r\n {props.username && <MwUserLinks ctx={props.ctx} user={props.username} target=\"_blank\" />}\r\n </div>\r\n <div className=\"mw-diff-title--timestamp\">\r\n {props.timestamp && formatDate(new Date(props.timestamp))}\r\n </div>\r\n <div className=\"mw-diff-title--comment\">\r\n {props.parsedcomment && (\r\n <>\r\n (<i innerHTML={props.parsedcomment}></i>)\r\n </>\r\n )}\r\n </div>\r\n </td>\r\n )\r\n}\r\n\r\nconst DiffTableNavigation = (props: { data: DiffTableProps['data']; ctx: InPageEdit }) => {\r\n const data = props.data\r\n if (!data.prev && !data.next) {\r\n return null\r\n }\r\n\r\n // 统一的事件处理器\r\n const handleNavigationClick = (e: Event, fromrev: number, torev: number) => {\r\n e.preventDefault()\r\n e.target!.dispatchEvent(\r\n new CustomEvent(DiffTableEvent.update, {\r\n detail: { fromrev, torev },\r\n bubbles: true,\r\n })\r\n )\r\n }\r\n\r\n return (\r\n <tr className=\"mw-diff-title--navigation\">\r\n <td colSpan={2}>\r\n {data.prev ? (\r\n <a\r\n href={props.ctx.getUrl('', { diff: data.prev!, oldid: data.fromrevid! })}\r\n onClick={(e) => handleNavigationClick(e, data.prev!, data.fromrevid!)}\r\n >\r\n ← Previous\r\n </a>\r\n ) : (\r\n <i>Oldest version</i>\r\n )}\r\n </td>\r\n <td colSpan={2}>\r\n {data.next ? (\r\n <a\r\n href={props.ctx.getUrl('', { diff: data.next!, oldid: data.torevid! })}\r\n onClick={(e) => handleNavigationClick(e, data.torevid!, data.next!)}\r\n >\r\n Next →\r\n </a>\r\n ) : (\r\n <i>Newest version</i>\r\n )}\r\n </td>\r\n </tr>\r\n )\r\n}\r\n\r\nexport const DiffTable = (props: DiffTableProps) => {\r\n const { data, ...rest } = props\r\n const table = (\r\n <table className={`theme-ipe diff diff-type-table`} data-mw=\"interface\" {...rest}>\r\n <colgroup>\r\n <col className=\"diff-marker\" />\r\n <col className=\"diff-content\" />\r\n <col className=\"diff-marker\" />\r\n <col className=\"diff-content\" />\r\n </colgroup>\r\n <tbody>\r\n <tr>\r\n <DiffTableHeader\r\n ctx={props.ctx}\r\n type=\"from\"\r\n pageid={data.fromid}\r\n pagetitle={data.fromtitle}\r\n revid={data.fromrevid}\r\n size={data.fromsize}\r\n timestamp={data.fromtimestamp}\r\n username={data.fromuser}\r\n userid={data.fromuserid}\r\n comment={data.fromcomment}\r\n parsedcomment={data.fromparsedcomment}\r\n />\r\n <DiffTableHeader\r\n ctx={props.ctx}\r\n type=\"to\"\r\n pageid={data.toid}\r\n pagetitle={data.totitle}\r\n revid={data.torevid}\r\n size={data.tosize}\r\n timestamp={data.totimestamp}\r\n username={data.touser}\r\n userid={data.touserid}\r\n comment={data.tocomment}\r\n parsedcomment={data.toparsedcomment}\r\n />\r\n </tr>\r\n <DiffTableNavigation data={data} ctx={props.ctx} />\r\n <div id=\"diffbody\"></div>\r\n <tr className=\"diff-size\" style={{ textAlign: 'center' }}>\r\n <td colSpan={2} className=\"diff-size-old\">\r\n {data.fromsize !== undefined && `${data.fromsize} bytes`}\r\n </td>\r\n <td colSpan={2} className=\"diff-size-new\">\r\n {data.tosize !== undefined && `${data.tosize} bytes`}\r\n </td>\r\n </tr>\r\n </tbody>\r\n </table>\r\n )\r\n table.querySelector('#diffbody')!.outerHTML =\r\n data.body ||\r\n (\r\n <tr>\r\n <td colSpan={4}>\r\n <div\r\n style={{\r\n display: 'flex',\r\n justifyContent: 'center',\r\n alignItems: 'center',\r\n height: '5rem',\r\n }}\r\n >\r\n <i>No changes</i>\r\n </div>\r\n </td>\r\n </tr>\r\n ).outerHTML\r\n return table\r\n}\r\n","import { CSSProperties, ReactElement } from 'jsx-dom'\r\n\r\nexport const qs = <T extends Element>(\r\n selector: string,\r\n parent: HTMLElement | Document = document\r\n) => {\r\n return parent.querySelector(selector) as T | null\r\n}\r\nexport const qsa = <T extends Element>(\r\n selector: string,\r\n parent: HTMLElement | Document = document\r\n) => {\r\n return parent.querySelectorAll(selector) as NodeListOf<T>\r\n}\r\n\r\nexport const setStyles = (el: HTMLElement | ReactElement, style: CSSProperties) => {\r\n Object.entries(style).forEach(([key, value]) => {\r\n if (typeof value === 'undefined' || value === null) {\r\n el.style.removeProperty(key)\r\n } else {\r\n const isImportant = typeof value === 'string' && value.endsWith('!important')\r\n // @ts-ignore\r\n el.style.setProperty(\r\n key,\r\n value.replace('!important', '').trim(),\r\n isImportant ? 'important' : undefined\r\n )\r\n }\r\n })\r\n return el\r\n}\r\n","import { Inject, InPageEdit, Schema } from '@/InPageEdit'\nimport { type QuickEditEventPayload } from '@/plugins/quick-edit'\nimport { JsDiffDiffType } from './JsDiffService'\n\nimport styles from './styles.module.sass'\nimport { ChangeObject } from 'diff'\nimport { DiffTable, DiffTableEvent } from './components/DiffTable'\nimport { IPEModal, IPEModalOptions } from '@inpageedit/modal'\nimport { MwApiResponse } from 'wiki-saikou'\n\ndeclare module '@/InPageEdit' {\n interface InPageEdit {\n quickDiff: PluginQuickDiffCore\n }\n}\n\nexport interface CompareApiRequestOptions {\n fromtitle: string\n fromid: number\n fromrev: number\n frompst: boolean\n totitle: string\n toid: number\n torev: number\n torelative?: 'cur' | 'prev' | 'next'\n topst: boolean\n prop: string\n difftype: 'table' | 'unified'\n // deprecated, but still works\n fromtext: string\n fromsection: string | number\n fromcontentmodel: string\n totext: string\n tosection: string | number\n tocontentmodel: string\n}\n\nexport interface CompareApiResponse {\n compare: Partial<{\n fromid: number\n fromrevid: number\n fromns: number\n fromtitle: string\n fromsize: number\n fromtimestamp: string\n fromuser: string\n fromuserid: number\n fromcomment: string\n fromparsedcomment?: string\n toid: number\n torevid: number\n tons: number\n totitle: string\n tosize: number\n totimestamp: string\n touser: string\n touserid: number\n tocomment: string\n toparsedcomment: string\n diffsize: number\n prev: number\n next: number\n }> & {\n body: string\n }\n}\n\nconst VALID_DIFF_TYPES = [\n 'diffChars',\n 'diffWords',\n 'diffSentences',\n 'diffLines',\n 'createTwoFilesPatch',\n] as JsDiffDiffType[]\n\n@Inject(['jsdiff', 'wiki', 'getUrl'])\n@RegisterPreferences(\n Schema.object({\n 'quickDiff.preferredCompareMode': Schema.union([Schema.const('jsDiff'), Schema.const('mwApi')])\n .description('The preferred comparison mode for quick diff')\n .default('mwApi'),\n 'quickDiff.jsDiff.defaultType': Schema.union(VALID_DIFF_TYPES.map((type) => Schema.const(type)))\n .description('The default diff type for JsDiff')\n .default('diffSentences'),\n }).description('Quick Diff Preferences'),\n {\n 'quickDiff.preferredCompareMode': 'mwApi',\n 'quickDiff.jsDiff.defaultType': 'diffSentences',\n }\n)\nexport class PluginQuickDiffCore extends BasePlugin {\n VALID_DIFF_TYPES = VALID_DIFF_TYPES\n\n constructor(public ctx: InPageEdit) {\n super(ctx, {}, 'quick-diff')\n }\n\n protected start(): Promise<void> | void {\n this.ctx.set('quickDiff', this)\n this.ctx.on('quick-edit/wiki-page', this.injectQuickEdit.bind(this))\n window.RLQ.push(this.injectHistoryPage.bind(this))\n }\n\n protected stop(): Promise<void> | void {}\n\n private injectHistoryPage() {\n const mwCompareForm = qs<HTMLFormElement>('#mw-history-compare')\n if (!mwCompareForm) {\n return\n }\n const compareButtons = qsa('.mw-history-compareselectedversions-button', mwCompareForm)\n compareButtons.forEach((el) => {\n el.after(\n <button\n className=\"cdx-button\"\n onClick={(e) => {\n e.preventDefault()\n const formData = new FormData(mwCompareForm)\n const fromrev = Number(formData.get('oldid')) || 0\n const torev = Number(formData.get('diff')) || 0\n const title = formData.get('title') as string\n if (!title || !fromrev || !torev) {\n return this.logger.warn('Missing title or revision IDs')\n }\n this.comparePages({\n fromrev,\n torev,\n })\n }}\n >\n Quick Diff\n </button>\n )\n })\n }\n\n private injectQuickEdit({ modal, wikiPage, options }: QuickEditEventPayload) {\n if (wikiPage.pageid === 0 || options.section === 'new') {\n // User is creating a new page, no need to show diff button\n return\n }\n let latestDiffModal: IPEModal | undefined = undefined\n modal.addButton(\n {\n label: 'Diff',\n side: 'left',\n keyPress: 'ctrl-d',\n className: 'btn btn-secondary',\n method: () => {\n const pageTitle = wikiPage.title\n const fromtext = wikiPage.revisions?.[0]?.content || ''\n const totext =\n (modal.get$content().querySelector<HTMLTextAreaElement>('textarea[name=\"text\"]')\n ?.value as string) || ''\n\n if (fromtext === totext) {\n return this.ctx.modal.notify('info', { title: 'Quick Diff', content: 'No changes' })\n }\n\n latestDiffModal = this.comparePages(\n {\n fromtitle: pageTitle,\n fromtext,\n totitle: pageTitle,\n totext,\n topst: true,\n },\n latestDiffModal,\n {\n backdrop: false,\n draggable: true,\n }\n )\n return latestDiffModal\n },\n },\n 2\n )\n modal.on(modal.Event.Close, () => {\n latestDiffModal?.destroy()\n latestDiffModal = undefined\n })\n }\n\n simpleTextDiff(oldText: string, newText: string) {\n const modal = this.ctx.modal.show({\n title: 'Quick Diff',\n className: 'in-page-edit ipe-quickDiff',\n })\n modal.show()\n\n const container = <pre className={styles['diff-container']}></pre>\n const controller = (\n <div\n style={{\n display: 'flex',\n gap: '1em',\n }}\n >\n {this.VALID_DIFF_TYPES.map((type, index) => (\n <RadioBox\n name=\"diffType\"\n value={type}\n label={type}\n inputProps={{\n checked: index === 0,\n }}\n />\n ))}\n </div>\n )\n modal.setContent(\n (\n <section>\n {controller}\n {container}\n </section>\n ) as HTMLElement\n )\n controller.querySelectorAll<HTMLInputElement>('input[name=\"diffType\"]').forEach((input) => {\n input.addEventListener('change', () => {\n const diff = this.renderJsDiff(oldText, newText, input.value as JsDiffDiffType)\n container.textContent = ''\n container.appendChild(diff)\n })\n })\n controller\n .querySelector<HTMLInputElement>('input[name=\"diffType\"]')!\n .dispatchEvent(new Event('change'))\n }\n\n /**\n * TODO: 类型体操\n */\n renderJsDiff(oldStr: string, newStr: string, diffType: JsDiffDiffType = 'diffSentences') {\n const fragment = document.createDocumentFragment()\n\n let diff: (ChangeObject<string> & { chunkHeader?: boolean })[]\n if (diffType === 'createTwoFilesPatch') {\n // 将 patch 结果转化为与 diffChars/diffWords... 类似的结构\n let pastHunkHeader = false\n diff = this.ctx.jsdiff\n .createTwoFilesPatch('original.txt', 'modified.txt', oldStr, newStr)\n .split('\\n')\n .map(function (entry) {\n const line = {\n value: entry + '\\n',\n } as ChangeObject<string> & { chunkHeader: boolean }\n if (entry.startsWith('@@')) {\n line.chunkHeader = true\n pastHunkHeader = true\n } else if (pastHunkHeader) {\n if (entry.startsWith('-')) {\n line.removed = true\n } else if (entry.startsWith('+')) {\n line.added = true\n }\n }\n return line\n })\n } else {\n const handler = this.ctx.jsdiff[diffType] as (\n oldStr: string,\n newStr: string\n ) => ChangeObject<string>[]\n if (!handler) {\n throw new Error(`Missing DiffEngine for ${diffType}`)\n }\n diff = handler(oldStr, newStr)\n }\n\n if (!Array.isArray(diff)) {\n throw new Error('Missing diff result')\n }\n\n // 交换逻辑(一个删除一个新增时)\n for (let i = 0; i < diff.length; i++) {\n if (diff[i].added && diff[i + 1] && diff[i + 1].removed) {\n const swap = diff[i]\n diff[i] = diff[i + 1]\n diff[i + 1] = swap\n }\n\n let node\n if (diff[i].removed) {\n node = document.createElement('del')\n node.appendChild(document.createTextNode(diff[i].value))\n } else if (diff[i].added) {\n node = document.createElement('ins')\n node.appendChild(document.createTextNode(diff[i].value))\n } else if (diff[i].chunkHeader) {\n node = document.createElement('span')\n node.setAttribute('class', 'chunk-header')\n node.appendChild(document.createTextNode(diff[i].value))\n } else {\n node = document.createTextNode(diff[i].value)\n }\n fragment.appendChild(node)\n }\n\n return fragment\n }\n\n readonly COMPARE_API_DEFAULT_OPTIONS: Partial<CompareApiRequestOptions> = {\n prop: [\n 'comment',\n 'diff',\n 'diffsize',\n 'ids',\n 'parsedcomment',\n 'size',\n 'timestamp',\n 'title',\n 'user',\n 'rel',\n ].join('|'),\n difftype: 'table',\n }\n\n comparePages(\n options: Partial<CompareApiRequestOptions>,\n modal?: IPEModal,\n modalOptions?: Partial<IPEModalOptions>\n ) {\n if (!modal || modal.isDestroyed) {\n modal = this.ctx.modal\n .createObject({\n title: 'Loading diff...',\n content: '',\n className: 'quick-diff',\n center: false,\n ...modalOptions,\n })\n .init()\n } else {\n modal.removeButton('*')\n }\n\n modal.setContent(\n <section\n style={{ height: '70vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}\n >\n <ProgressBar />\n </section>\n )\n modal.bringToFront()\n\n if (window.mw && mw.loader.getState('mediawiki.diff.styles') !== 'ready') {\n mw.loader.load(['mediawiki.diff.styles'])\n }\n\n this.ctx.api\n .post<MwApiResponse<CompareApiResponse>>({\n ...this.COMPARE_API_DEFAULT_OPTIONS,\n ...options,\n action: 'compare',\n format: 'json',\n formatversion: 2,\n })\n .then((res) => {\n if (!res.data.compare) {\n throw new Error('No compare data received', { cause: res })\n }\n const {\n data: { compare },\n } = res\n modal.setTitle(\n compare.fromtitle && compare.totitle\n ? `${compare.fromtitle}${compare.fromrevid ? ` (${compare.fromrevid})` : ''} ⇔ ${compare.totitle}${compare.torevid ? ` (${compare.torevid})` : ''}`\n : 'Differences'\n )\n let diffTable!: HTMLElement\n modal.setContent(\n (\n <section\n style={{\n minHeight: '70vh',\n }}\n >\n <DiffTable ref={(ref) => (diffTable = ref)} data={compare} ctx={this.ctx} />\n </section>\n ) as HTMLElement\n )\n diffTable.addEventListener(\n DiffTableEvent.update,\n (e) => {\n e.stopPropagation()\n this.comparePages(\n {\n fromrev: e.detail.fromrev,\n torev: e.detail.torev,\n },\n modal,\n modalOptions\n )\n },\n { once: true }\n )\n\n // TODO: 不应该硬编码,移动到 in-article-links 插件中\n this.ctx.inject(['quickEdit'], (ctx) => {\n const handleQuickEdit = (e: CustomEvent<{ revid: number }>) => {\n e.stopPropagation()\n ctx.quickEdit({ revision: e.detail.revid })\n }\n diffTable.addEventListener(DiffTableEvent.edit, handleQuickEdit)\n modal.on(modal.Event.Close, () => {\n diffTable.removeEventListener(DiffTableEvent.edit, handleQuickEdit)\n })\n })\n\n if (compare.fromrevid && compare.torevid) {\n modal.addButton({\n label: 'Original Compare Page',\n side: 'right',\n className: 'btn btn-secondary',\n method: () => {\n window.location.href = this.ctx.getUrl('', {\n oldid: compare.fromrevid,\n diff: compare.torevid,\n })\n },\n })\n }\n })\n .catch((err) => {\n modal.setContent(\n (\n <MBox title=\"Failed to load diff\" type=\"error\">\n <pre>{err instanceof Error ? err.message : String(err)}</pre>\n </MBox>\n ) as HTMLElement\n )\n })\n\n return modal.show()\n }\n}\n","import { InPageEdit } from '@/InPageEdit'\r\nimport { JsDiffService } from './JsDiffService'\r\nimport { PluginQuickDiffCore } from './PluginQuickDiffCore'\r\n\r\nexport class PluginQuickDiff extends BasePlugin {\r\n static readonly inject = ['api', 'wikiPage', 'modal']\r\n\r\n constructor(public ctx: InPageEdit) {\r\n super(ctx, {}, 'quick-diff-loader')\r\n ctx.plugin(JsDiffService)\r\n ctx.plugin(PluginQuickDiffCore)\r\n }\r\n}\r\n"],"names":["Diff","oldStr","newStr","options","callback","oldString","newString","oldTokens","newTokens","_a","done","value","newLen","oldLen","editLength","maxEditLength","maxExecutionTime","abortAfterTimestamp","bestPath","newPos","minDiagonalToConsider","maxDiagonalToConsider","execEditLength","diagonalPath","basePath","removePath","addPath","canAdd","addPathNewPos","canRemove","exec","ret","path","added","removed","oldPosInc","last","oldPos","commonCount","left","right","array","chars","changeObjects","lastComponent","components","nextComponent","componentLen","componentPos","component","i","oldValue","CharacterDiff","characterDiff","diffChars","longestCommonPrefix","str1","str2","longestCommonSuffix","replacePrefix","string","oldPrefix","newPrefix","replaceSuffix","oldSuffix","newSuffix","removePrefix","removeSuffix","maximumOverlap","string1","string2","overlapCount","a","b","startA","endB","map","k","j","hasOnlyWinLineEndings","hasOnlyUnixLineEndings","trailingWs","leadingWs","match","extendedWordChars","tokenizeIncludingWhitespace","WordDiff","parts","segmenter","segment","tokens","prevPart","part","token","changes","lastKeep","insertion","deletion","change","dedupeWhitespaceInChangeObjects","wordDiff","diffWords","diffWordsWithSpace","startKeep","endKeep","oldWsPrefix","oldWsSuffix","newWsPrefix","newWsSuffix","commonWsPrefix","commonWsSuffix","ws","newWsFull","delWsStart","delWsEnd","newWsStart","newWsEnd","endKeepWsPrefix","deletionWsSuffix","overlap","startKeepWsSuffix","deletionWsPrefix","WordsWithSpaceDiff","regex","wordsWithSpaceDiff","generateOptions","defaults","name","LineDiff","tokenize","lineDiff","diffLines","diffTrimmedLines","retLines","linesAndNewlines","line","isSentenceEndPunct","char","SentenceDiff","result","tokenStartI","sentenceDiff","diffSentences","CssDiff","cssDiff","diffCss","JsonDiff","undefinedReplacement","stringifyReplacer","v","canonicalize","jsonDiff","diffJson","obj","stack","replacementStack","replacer","key","canonicalizedObj","sortedKeys","ArrayDiff","arrayDiff","diffArrays","oldArr","newArr","unixToWin","patch","p","hunk","winToUnix","isUnix","index","isWin","parsePatch","uniDiff","diffstr","list","parseIndex","header","parseFileHeader","parseHunk","fileHeader","data","fileName","chunkHeaderIndex","chunkHeaderLine","chunkHeader","addCount","removeCount","operation","distanceIterator","start","minLine","maxLine","wantForward","backwardExhausted","forwardExhausted","localOffset","iterator","applyPatch","source","patches","applyStructuredPatch","lines","hunks","compareLine","lineNumber","patchContent","fuzzFactor","prevLine","removeEOFNL","addEOFNL","applyHunk","hunkLines","toPos","maxErrors","hunkLinesI","lastContextLineMatched","patchedLines","patchedLinesLength","nConsecutiveOldContextLines","nextContextLineMustMatch","hunkLine","content","resultLines","prevHunkOffset","hunkResult","applyPatches","spDiff","currentIndex","processIndex","err","updatedContent","reversePatch","structuredPatch","l","oldFileName","newFileName","oldHeader","newHeader","optionsObj","context","diff","diffLinesResultToPatch","contextLines","entry","oldRangeStart","newRangeStart","curRange","oldLine","newLine","current","splitLines","prev","contextSize","formatPatch","createTwoFilesPatch","patchObj","createPatch","text","hasTrailingNl","convertChangesToDMP","convertChangesToXML","escapeHTML","s","n","JsDiffService","ctx","JsDiff","JsDiff.diffChars","JsDiff.diffWords","JsDiff.diffWordsWithSpace","JsDiff.diffLines","JsDiff.diffTrimmedLines","JsDiff.diffSentences","JsDiff.diffCss","JsDiff.diffJson","JsDiff.diffArrays","JsDiff.createTwoFilesPatch","MwUserLinks","props","user","target","getUrl","jsxs","jsx","DiffTableEvent","formatDate","DiffTableHeader","classList","handleEditClick","e","IconQuickEdit","Fragment","DiffTableNavigation","handleNavigationClick","fromrev","torev","DiffTable","rest","table","qs","selector","parent","qsa","_PluginQuickDiffCore_decorators","_init","VALID_DIFF_TYPES","Inject","RegisterPreferences","Schema","type","PluginQuickDiffCore","BasePlugin","mwCompareForm","el","formData","modal","wikiPage","latestDiffModal","pageTitle","fromtext","totext","oldText","newText","container","styles","controller","RadioBox","input","diffType","fragment","pastHunkHeader","handler","swap","node","modalOptions","ProgressBar","res","compare","diffTable","ref","handleQuickEdit","MBox","__decoratorStart","__decorateElement","__runInitializers","PluginQuickDiff"],"mappings":";;;;;;AAAe,MAAMA,EAAK;AAAA,EACtB,KAAKC,GAAQC,GAEbC,IAAU,CAAA,GAAI;AACV,QAAIC;AACJ,IAAI,OAAOD,KAAY,cACnBC,IAAWD,GACXA,IAAU,CAAA,KAEL,cAAcA,MACnBC,IAAWD,EAAQ;AAGvB,UAAME,IAAY,KAAK,UAAUJ,GAAQE,CAAO,GAC1CG,IAAY,KAAK,UAAUJ,GAAQC,CAAO,GAC1CI,IAAY,KAAK,YAAY,KAAK,SAASF,GAAWF,CAAO,CAAC,GAC9DK,IAAY,KAAK,YAAY,KAAK,SAASF,GAAWH,CAAO,CAAC;AACpE,WAAO,KAAK,mBAAmBI,GAAWC,GAAWL,GAASC,CAAQ;AAAA,EAC1E;AAAA,EACA,mBAAmBG,GAAWC,GAAWL,GAASC,GAAU;AACx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