dsh-remote 1.0.1 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +38 -318
- package/README.md +36 -298
- package/lib/binding.js +4 -2
- package/lib/client.js +828 -62
- package/lib/file-changes.js +57 -0
- package/lib/index.js +29 -38
- package/lib/remote-fs.js +8 -2
- package/lib/remote-git.js +127 -0
- package/lib/remote-shell-child.cjs +59 -12
- package/lib/remote-shell.js +1 -1
- package/lib/remote-write.js +51 -0
- package/lib/routes-fs.js +72 -24
- package/lib/sftp-surface.js +1 -1
- package/lib/vendor/jsdiff/LICENSE +29 -0
- package/lib/vendor/jsdiff/SOURCE.md +4 -0
- package/lib/vendor/jsdiff/diff/base.js +254 -0
- package/lib/vendor/jsdiff/diff/line.js +66 -0
- package/lib/vendor/jsdiff/patch/create.js +229 -0
- package/lib/vendor/jsdiff/util/params.js +15 -0
- package/lib/workspace-search.js +219 -0
- package/package.json +6 -5
package/lib/routes-fs.js
CHANGED
|
@@ -4,14 +4,45 @@
|
|
|
4
4
|
// the active-machine pool. Session-scoped callers (explorer / file tab) MUST
|
|
5
5
|
// pass sessionId (or local=mirror cwd); those requests resolve through the
|
|
6
6
|
// same mirror binding as rw_* tools and never fall back to the active machine.
|
|
7
|
-
|
|
7
|
+
// URLSearchParams already decodes query paths. Another decoding pass corrupts
|
|
8
|
+
// literal percent characters and names containing sequences such as `%2F`.
|
|
9
|
+
import { lstatSync, mkdirSync } from 'node:fs'
|
|
8
10
|
import path from 'node:path'
|
|
9
11
|
import {
|
|
10
12
|
normalizeRemotePath, joinRemotePath, remoteDirname, mkdirRemoteDirs, toDisplayPath,
|
|
11
13
|
} from './paths.js'
|
|
12
14
|
import { requestSessionHint } from './binding.js'
|
|
15
|
+
import { captureRemoteFile, atomicRemoteWrite, remoteRevision, missingRemoteFile } from './remote-write.js'
|
|
13
16
|
import { listDirStructured, listRemoteDrives, removeRemoteTree, previewRemoteFile } from './remote-fs.js'
|
|
14
17
|
|
|
18
|
+
const unsafeDownload = () => Object.assign(new Error('The download destination must be a regular file inside this workspace mirror'), { httpStatus: 403 })
|
|
19
|
+
|
|
20
|
+
// Remote POSIX names may contain backslashes that become separators on a
|
|
21
|
+
// Windows host. Resolve in each filesystem's own grammar, never by prefix.
|
|
22
|
+
export function mirrorDownloadTarget(base, workspace, remote, localPath = path) {
|
|
23
|
+
const remotePath = /^(?:[a-z]:[\\/]|\\\\)/i.test(workspace) ? path.win32 : path.posix
|
|
24
|
+
const relative = remotePath.relative(normalizeRemotePath(workspace), normalizeRemotePath(remote))
|
|
25
|
+
if (!relative || remotePath.isAbsolute(relative) || relative.split(remotePath.sep).some(part => part === '..') || relative.includes('\0')) throw unsafeDownload()
|
|
26
|
+
const parts = relative.split(remotePath.sep)
|
|
27
|
+
// This local-only record determines the session's remote identity.
|
|
28
|
+
if (parts.length === 1 && (localPath.sep === '\\' ? parts[0].toLowerCase() : parts[0]) === '.dsh-remote-meta.json') throw unsafeDownload()
|
|
29
|
+
if (localPath.sep === '\\' && parts.some(part => /[<>:"|?*\\\x00-\x1f]/.test(part) || /[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) throw unsafeDownload()
|
|
30
|
+
const root = localPath.resolve(base), target = localPath.resolve(root, ...parts)
|
|
31
|
+
const within = localPath.relative(root, target)
|
|
32
|
+
if (!within || localPath.isAbsolute(within) || within.split(localPath.sep).some(part => part === '..')) throw unsafeDownload()
|
|
33
|
+
return target
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function assertDownloadHasNoSymlinks(base, target) {
|
|
37
|
+
const root = path.resolve(base)
|
|
38
|
+
let current = root
|
|
39
|
+
for (const segment of ['', ...path.relative(root, target).split(path.sep)]) {
|
|
40
|
+
if (segment) current = path.join(current, segment)
|
|
41
|
+
try { if (lstatSync(current).isSymbolicLink()) throw unsafeDownload() }
|
|
42
|
+
catch (error) { if (error.code !== 'ENOENT') throw error }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
15
46
|
export function createFsRoutes({
|
|
16
47
|
sendJson,
|
|
17
48
|
readBody,
|
|
@@ -32,6 +63,23 @@ export function createFsRoutes({
|
|
|
32
63
|
}
|
|
33
64
|
}
|
|
34
65
|
|
|
66
|
+
const checkExpectedRevision = (body, snapshot) => {
|
|
67
|
+
if (body.expectedRevision != null) {
|
|
68
|
+
if (typeof body.expectedRevision !== 'string' || !/^[a-f0-9]{64}$/.test(body.expectedRevision)) {
|
|
69
|
+
throw Object.assign(new Error('expectedRevision must be a SHA-256 revision returned by a complete file preview'), { httpStatus: 400 })
|
|
70
|
+
}
|
|
71
|
+
if (!snapshot.stat || !snapshot.bytes || remoteRevision(snapshot.bytes) !== body.expectedRevision) {
|
|
72
|
+
throw Object.assign(new Error('远端文件已变化,已放弃保存。请重新读取并比较后重试。'), { httpStatus: 409, code: 'REMOTE_FILE_CONFLICT' })
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (body.expectedMtime != null) {
|
|
76
|
+
if (!Number.isFinite(Number(body.expectedMtime))) throw Object.assign(new Error('expectedMtime must be a finite timestamp'), { httpStatus: 400 })
|
|
77
|
+
if (!snapshot.stat || snapshot.stat.mtime !== Number(body.expectedMtime)) {
|
|
78
|
+
throw Object.assign(new Error('远端文件已变化,已放弃保存。请重新读取并比较后重试。'), { httpStatus: 409, code: 'REMOTE_FILE_CONFLICT' })
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
35
83
|
return [
|
|
36
84
|
{
|
|
37
85
|
kind: 'exact',
|
|
@@ -65,7 +113,7 @@ export function createFsRoutes({
|
|
|
65
113
|
await b.pool.detect()
|
|
66
114
|
const q = new URL(req.url, 'http://localhost').searchParams
|
|
67
115
|
const raw = q.get('path')
|
|
68
|
-
?
|
|
116
|
+
? q.get('path')
|
|
69
117
|
: (body.path ? String(body.path) : (b.ws || ''))
|
|
70
118
|
const canon = normalizeRemotePath(raw)
|
|
71
119
|
const win = b.pool.platform === 'windows'
|
|
@@ -102,7 +150,7 @@ export function createFsRoutes({
|
|
|
102
150
|
if (req.method !== 'GET' && req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
|
|
103
151
|
try {
|
|
104
152
|
const q = new URL(req.url, 'http://localhost').searchParams
|
|
105
|
-
let p = q.get('path') ?
|
|
153
|
+
let p = q.get('path') ? q.get('path') : ''
|
|
106
154
|
let encoding = ''
|
|
107
155
|
let maxBytes = 256 * 1024
|
|
108
156
|
let body = {}
|
|
@@ -150,20 +198,17 @@ export function createFsRoutes({
|
|
|
150
198
|
const b = await bindOrReply(req, res, body)
|
|
151
199
|
if (!b) return
|
|
152
200
|
const sftp = await b.pool.sftp()
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
if (body.expectedMtime != null && st && st.mtime !== Number(body.expectedMtime)) {
|
|
156
|
-
return sendJson(res, 409, { ok: false, error: `远端文件已变化(mtime ${st.mtime} ≠ ${body.expectedMtime}),已放弃保存——请重新读取后再编辑` })
|
|
157
|
-
}
|
|
201
|
+
const before = await captureRemoteFile(sftp, p, { read: body.expectedRevision != null, maxReadBytes: 2 * 1024 * 1024 })
|
|
202
|
+
checkExpectedRevision(body, before)
|
|
158
203
|
const buf = encodeText(String(body.content ?? ''), body.encoding || config.encoding)
|
|
159
|
-
if (!
|
|
160
|
-
await sftp
|
|
204
|
+
if (!before.stat) await mkdirRemoteDirs(sftp, remoteDirname(p))
|
|
205
|
+
await atomicRemoteWrite(sftp, before, buf)
|
|
161
206
|
audit('write', `write ${p}`, 0, b)
|
|
162
207
|
onRemoteMutation()
|
|
163
208
|
const st2 = await sftp.stat(p).catch(() => null)
|
|
164
|
-
return sendJson(res, 200, { ok: true, bytes: buf.byteLength, mtime: st2 ? st2.mtime : Math.floor(Date.now() / 1000) })
|
|
209
|
+
return sendJson(res, 200, { ok: true, bytes: buf.byteLength, mtime: st2 ? st2.mtime : Math.floor(Date.now() / 1000), revision: remoteRevision(buf) })
|
|
165
210
|
} catch (err) {
|
|
166
|
-
return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
|
|
211
|
+
return sendJson(res, err.httpStatus || 500, { ok: false, error: String((err && err.message) || err), ...(err.code ? { code: err.code } : {}) })
|
|
167
212
|
}
|
|
168
213
|
},
|
|
169
214
|
},
|
|
@@ -212,30 +257,33 @@ export function createFsRoutes({
|
|
|
212
257
|
if (op === 'write' || op === 'append') {
|
|
213
258
|
const p = normalizeRemotePath(String(body.path || ''))
|
|
214
259
|
if (!p || p === '/') return sendJson(res, 400, { ok: false, error: 'path required' })
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
}
|
|
260
|
+
const before = await captureRemoteFile(sftp, p, {
|
|
261
|
+
read: op === 'append' || body.expectedRevision != null,
|
|
262
|
+
maxReadBytes: config.maxFileBytes > 0 ? Math.min(config.maxFileBytes, 2 * 1024 * 1024) : 2 * 1024 * 1024,
|
|
263
|
+
})
|
|
264
|
+
checkExpectedRevision(body, before)
|
|
265
|
+
const content = op === 'append' && before.bytes ? decodeBuf(before.bytes, body.encoding || config.encoding) : ''
|
|
219
266
|
const buf = encodeText(content + String(body.content ?? ''), body.encoding || config.encoding)
|
|
220
|
-
if (op === 'write' && !
|
|
221
|
-
await sftp
|
|
267
|
+
if (op === 'write' && !before.stat) await mkdirRemoteDirs(sftp, remoteDirname(p))
|
|
268
|
+
await atomicRemoteWrite(sftp, before, buf)
|
|
222
269
|
audit(op, `${op} ${p}`, 0, b)
|
|
223
270
|
onRemoteMutation()
|
|
224
|
-
return sendJson(res, 200, { ok: true, bytes: buf.byteLength })
|
|
271
|
+
return sendJson(res, 200, { ok: true, bytes: buf.byteLength, revision: remoteRevision(buf) })
|
|
225
272
|
}
|
|
226
273
|
if (op === 'download') {
|
|
227
274
|
const p = normalizeRemotePath(String(body.path || ''))
|
|
228
275
|
const ws = b.ws
|
|
229
276
|
if (!p || p === '/') return sendJson(res, 400, { ok: false, error: 'path required' })
|
|
230
277
|
if (!ws) return sendJson(res, 400, { ok: false, error: 'no remote workspace set' })
|
|
231
|
-
const
|
|
278
|
+
const base = b.mirrorDir || mirrorDirFor(ws, b.host, b.username, b.port)
|
|
279
|
+
const local = mirrorDownloadTarget(base, ws, p)
|
|
280
|
+
const st = await sftp.stat(p).catch(error => { if (missingRemoteFile(error)) return null; throw error })
|
|
232
281
|
if (!st) return sendJson(res, 404, { ok: false, error: 'not found' })
|
|
282
|
+
if (st.isDirectory?.()) return sendJson(res, 400, { ok: false, error: 'download requires a file' })
|
|
233
283
|
if (config.maxFileBytes > 0 && st.size > config.maxFileBytes) {
|
|
234
284
|
return sendJson(res, 400, { ok: false, error: `file is ${st.size} bytes (over ${config.maxFileBytes} cap)` })
|
|
235
285
|
}
|
|
236
|
-
|
|
237
|
-
const rel = p.startsWith(ws) ? p.slice(ws.length).replace(/^\/+/, '') : p.slice(1)
|
|
238
|
-
const local = path.join(base, rel)
|
|
286
|
+
assertDownloadHasNoSymlinks(base, local)
|
|
239
287
|
mkdirSync(path.dirname(local), { recursive: true })
|
|
240
288
|
await sftp.fastGet(p, local)
|
|
241
289
|
audit('download', `download ${p}`, 0, b)
|
|
@@ -243,7 +291,7 @@ export function createFsRoutes({
|
|
|
243
291
|
}
|
|
244
292
|
return sendJson(res, 400, { ok: false, error: 'unknown op' })
|
|
245
293
|
} catch (err) {
|
|
246
|
-
return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
|
|
294
|
+
return sendJson(res, err.httpStatus || 500, { ok: false, error: String((err && err.message) || err), ...(err.code ? { code: err.code } : {}) })
|
|
247
295
|
}
|
|
248
296
|
},
|
|
249
297
|
},
|
package/lib/sftp-surface.js
CHANGED
|
@@ -100,7 +100,7 @@ export function buildSftpSurface(sftp, { commandTimeoutMs, onTimeout }) {
|
|
|
100
100
|
// atomic rename replace (issue #65).
|
|
101
101
|
setstat: (p, attrs) => withTimeout((d, a, cb) => sftp.setstat(d, a, cb))(P(p), attrs),
|
|
102
102
|
readFile: (p) => withTimeout((d, cb) => sftp.readFile(d, cb))(P(p)),
|
|
103
|
-
writeFile: (p, data) => withTimeout((d, data2, cb) => sftp.writeFile(d, data2, cb))(P(p), data),
|
|
103
|
+
writeFile: (p, data, options) => withTimeout((d, data2, cb) => options ? sftp.writeFile(d, data2, options, cb) : sftp.writeFile(d, data2, cb))(P(p), data),
|
|
104
104
|
fastGet: (p, lp) => withTimeout((d, l, cb) => sftp.fastGet(d, l, cb))(P(p), lp),
|
|
105
105
|
fastPut: (lp, p) => withTimeout((l, d, cb) => sftp.fastPut(l, d, cb))(lp, P(p)),
|
|
106
106
|
// Range read for oversized previews: never downloads the whole file.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2009-2015, Kevin Decker <kpdecker@gmail.com>
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without
|
|
7
|
+
modification, are permitted provided that the following conditions are met:
|
|
8
|
+
|
|
9
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
10
|
+
list of conditions and the following disclaimer.
|
|
11
|
+
|
|
12
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
13
|
+
this list of conditions and the following disclaimer in the documentation
|
|
14
|
+
and/or other materials provided with the distribution.
|
|
15
|
+
|
|
16
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
17
|
+
contributors may be used to endorse or promote products derived from
|
|
18
|
+
this software without specific prior written permission.
|
|
19
|
+
|
|
20
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
21
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
22
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
23
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
24
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
25
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
26
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
27
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
28
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
29
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
// Vendored unchanged from jsdiff 8.0.4; BSD-3-Clause. See lib/vendor/jsdiff/LICENSE.
|
|
2
|
+
export default class Diff {
|
|
3
|
+
diff(oldStr, newStr,
|
|
4
|
+
// Type below is not accurate/complete - see above for full possibilities - but it compiles
|
|
5
|
+
options = {}) {
|
|
6
|
+
let callback;
|
|
7
|
+
if (typeof options === 'function') {
|
|
8
|
+
callback = options;
|
|
9
|
+
options = {};
|
|
10
|
+
}
|
|
11
|
+
else if ('callback' in options) {
|
|
12
|
+
callback = options.callback;
|
|
13
|
+
}
|
|
14
|
+
// Allow subclasses to massage the input prior to running
|
|
15
|
+
const oldString = this.castInput(oldStr, options);
|
|
16
|
+
const newString = this.castInput(newStr, options);
|
|
17
|
+
const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
|
|
18
|
+
const newTokens = this.removeEmpty(this.tokenize(newString, options));
|
|
19
|
+
return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
|
|
20
|
+
}
|
|
21
|
+
diffWithOptionsObj(oldTokens, newTokens, options, callback) {
|
|
22
|
+
var _a;
|
|
23
|
+
const done = (value) => {
|
|
24
|
+
value = this.postProcess(value, options);
|
|
25
|
+
if (callback) {
|
|
26
|
+
setTimeout(function () { callback(value); }, 0);
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
const newLen = newTokens.length, oldLen = oldTokens.length;
|
|
34
|
+
let editLength = 1;
|
|
35
|
+
let maxEditLength = newLen + oldLen;
|
|
36
|
+
if (options.maxEditLength != null) {
|
|
37
|
+
maxEditLength = Math.min(maxEditLength, options.maxEditLength);
|
|
38
|
+
}
|
|
39
|
+
const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity;
|
|
40
|
+
const abortAfterTimestamp = Date.now() + maxExecutionTime;
|
|
41
|
+
const bestPath = [{ oldPos: -1, lastComponent: undefined }];
|
|
42
|
+
// Seed editLength = 0, i.e. the content starts with the same values
|
|
43
|
+
let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
|
|
44
|
+
if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
|
|
45
|
+
// Identity per the equality and tokenizer
|
|
46
|
+
return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
|
|
47
|
+
}
|
|
48
|
+
// Once we hit the right edge of the edit graph on some diagonal k, we can
|
|
49
|
+
// definitely reach the end of the edit graph in no more than k edits, so
|
|
50
|
+
// there's no point in considering any moves to diagonal k+1 any more (from
|
|
51
|
+
// which we're guaranteed to need at least k+1 more edits).
|
|
52
|
+
// Similarly, once we've reached the bottom of the edit graph, there's no
|
|
53
|
+
// point considering moves to lower diagonals.
|
|
54
|
+
// We record this fact by setting minDiagonalToConsider and
|
|
55
|
+
// maxDiagonalToConsider to some finite value once we've hit the edge of
|
|
56
|
+
// the edit graph.
|
|
57
|
+
// This optimization is not faithful to the original algorithm presented in
|
|
58
|
+
// Myers's paper, which instead pointlessly extends D-paths off the end of
|
|
59
|
+
// the edit graph - see page 7 of Myers's paper which notes this point
|
|
60
|
+
// explicitly and illustrates it with a diagram. This has major performance
|
|
61
|
+
// implications for some common scenarios. For instance, to compute a diff
|
|
62
|
+
// where the new text simply appends d characters on the end of the
|
|
63
|
+
// original text of length n, the true Myers algorithm will take O(n+d^2)
|
|
64
|
+
// time while this optimization needs only O(n+d) time.
|
|
65
|
+
let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
|
|
66
|
+
// Main worker method. checks all permutations of a given edit length for acceptance.
|
|
67
|
+
const execEditLength = () => {
|
|
68
|
+
for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
|
|
69
|
+
let basePath;
|
|
70
|
+
const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
|
|
71
|
+
if (removePath) {
|
|
72
|
+
// No one else is going to attempt to use this value, clear it
|
|
73
|
+
// @ts-expect-error - perf optimisation. This type-violating value will never be read.
|
|
74
|
+
bestPath[diagonalPath - 1] = undefined;
|
|
75
|
+
}
|
|
76
|
+
let canAdd = false;
|
|
77
|
+
if (addPath) {
|
|
78
|
+
// what newPos will be after we do an insertion:
|
|
79
|
+
const addPathNewPos = addPath.oldPos - diagonalPath;
|
|
80
|
+
canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
|
|
81
|
+
}
|
|
82
|
+
const canRemove = removePath && removePath.oldPos + 1 < oldLen;
|
|
83
|
+
if (!canAdd && !canRemove) {
|
|
84
|
+
// If this path is a terminal then prune
|
|
85
|
+
// @ts-expect-error - perf optimisation. This type-violating value will never be read.
|
|
86
|
+
bestPath[diagonalPath] = undefined;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
// Select the diagonal that we want to branch from. We select the prior
|
|
90
|
+
// path whose position in the old string is the farthest from the origin
|
|
91
|
+
// and does not pass the bounds of the diff graph
|
|
92
|
+
if (!canRemove || (canAdd && removePath.oldPos < addPath.oldPos)) {
|
|
93
|
+
basePath = this.addToPath(addPath, true, false, 0, options);
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
basePath = this.addToPath(removePath, false, true, 1, options);
|
|
97
|
+
}
|
|
98
|
+
newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
|
|
99
|
+
if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
|
|
100
|
+
// If we have hit the end of both strings, then we are done
|
|
101
|
+
return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
bestPath[diagonalPath] = basePath;
|
|
105
|
+
if (basePath.oldPos + 1 >= oldLen) {
|
|
106
|
+
maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
|
|
107
|
+
}
|
|
108
|
+
if (newPos + 1 >= newLen) {
|
|
109
|
+
minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
editLength++;
|
|
114
|
+
};
|
|
115
|
+
// Performs the length of edit iteration. Is a bit fugly as this has to support the
|
|
116
|
+
// sync and async mode which is never fun. Loops over execEditLength until a value
|
|
117
|
+
// is produced, or until the edit length exceeds options.maxEditLength (if given),
|
|
118
|
+
// in which case it will return undefined.
|
|
119
|
+
if (callback) {
|
|
120
|
+
(function exec() {
|
|
121
|
+
setTimeout(function () {
|
|
122
|
+
if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
|
|
123
|
+
return callback(undefined);
|
|
124
|
+
}
|
|
125
|
+
if (!execEditLength()) {
|
|
126
|
+
exec();
|
|
127
|
+
}
|
|
128
|
+
}, 0);
|
|
129
|
+
}());
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
|
|
133
|
+
const ret = execEditLength();
|
|
134
|
+
if (ret) {
|
|
135
|
+
return ret;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
addToPath(path, added, removed, oldPosInc, options) {
|
|
141
|
+
const last = path.lastComponent;
|
|
142
|
+
if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
|
|
143
|
+
return {
|
|
144
|
+
oldPos: path.oldPos + oldPosInc,
|
|
145
|
+
lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent }
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
return {
|
|
150
|
+
oldPos: path.oldPos + oldPosInc,
|
|
151
|
+
lastComponent: { count: 1, added: added, removed: removed, previousComponent: last }
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
|
|
156
|
+
const newLen = newTokens.length, oldLen = oldTokens.length;
|
|
157
|
+
let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
|
|
158
|
+
while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
|
|
159
|
+
newPos++;
|
|
160
|
+
oldPos++;
|
|
161
|
+
commonCount++;
|
|
162
|
+
if (options.oneChangePerToken) {
|
|
163
|
+
basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (commonCount && !options.oneChangePerToken) {
|
|
167
|
+
basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
|
|
168
|
+
}
|
|
169
|
+
basePath.oldPos = oldPos;
|
|
170
|
+
return newPos;
|
|
171
|
+
}
|
|
172
|
+
equals(left, right, options) {
|
|
173
|
+
if (options.comparator) {
|
|
174
|
+
return options.comparator(left, right);
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
return left === right
|
|
178
|
+
|| (!!options.ignoreCase && left.toLowerCase() === right.toLowerCase());
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
removeEmpty(array) {
|
|
182
|
+
const ret = [];
|
|
183
|
+
for (let i = 0; i < array.length; i++) {
|
|
184
|
+
if (array[i]) {
|
|
185
|
+
ret.push(array[i]);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return ret;
|
|
189
|
+
}
|
|
190
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
191
|
+
castInput(value, options) {
|
|
192
|
+
return value;
|
|
193
|
+
}
|
|
194
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
195
|
+
tokenize(value, options) {
|
|
196
|
+
return Array.from(value);
|
|
197
|
+
}
|
|
198
|
+
join(chars) {
|
|
199
|
+
// Assumes ValueT is string, which is the case for most subclasses.
|
|
200
|
+
// When it's false, e.g. in diffArrays, this method needs to be overridden (e.g. with a no-op)
|
|
201
|
+
// Yes, the casts are verbose and ugly, because this pattern - of having the base class SORT OF
|
|
202
|
+
// assume tokens and values are strings, but not completely - is weird and janky.
|
|
203
|
+
return chars.join('');
|
|
204
|
+
}
|
|
205
|
+
postProcess(changeObjects,
|
|
206
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
207
|
+
options) {
|
|
208
|
+
return changeObjects;
|
|
209
|
+
}
|
|
210
|
+
get useLongestToken() {
|
|
211
|
+
return false;
|
|
212
|
+
}
|
|
213
|
+
buildValues(lastComponent, newTokens, oldTokens) {
|
|
214
|
+
// First we convert our linked list of components in reverse order to an
|
|
215
|
+
// array in the right order:
|
|
216
|
+
const components = [];
|
|
217
|
+
let nextComponent;
|
|
218
|
+
while (lastComponent) {
|
|
219
|
+
components.push(lastComponent);
|
|
220
|
+
nextComponent = lastComponent.previousComponent;
|
|
221
|
+
delete lastComponent.previousComponent;
|
|
222
|
+
lastComponent = nextComponent;
|
|
223
|
+
}
|
|
224
|
+
components.reverse();
|
|
225
|
+
const componentLen = components.length;
|
|
226
|
+
let componentPos = 0, newPos = 0, oldPos = 0;
|
|
227
|
+
for (; componentPos < componentLen; componentPos++) {
|
|
228
|
+
const component = components[componentPos];
|
|
229
|
+
if (!component.removed) {
|
|
230
|
+
if (!component.added && this.useLongestToken) {
|
|
231
|
+
let value = newTokens.slice(newPos, newPos + component.count);
|
|
232
|
+
value = value.map(function (value, i) {
|
|
233
|
+
const oldValue = oldTokens[oldPos + i];
|
|
234
|
+
return oldValue.length > value.length ? oldValue : value;
|
|
235
|
+
});
|
|
236
|
+
component.value = this.join(value);
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
component.value = this.join(newTokens.slice(newPos, newPos + component.count));
|
|
240
|
+
}
|
|
241
|
+
newPos += component.count;
|
|
242
|
+
// Common case
|
|
243
|
+
if (!component.added) {
|
|
244
|
+
oldPos += component.count;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
|
|
249
|
+
oldPos += component.count;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return components;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Vendored unchanged from jsdiff 8.0.4; BSD-3-Clause. See lib/vendor/jsdiff/LICENSE.
|
|
2
|
+
import Diff from './base.js';
|
|
3
|
+
import { generateOptions } from '../util/params.js';
|
|
4
|
+
class LineDiff extends Diff {
|
|
5
|
+
constructor() {
|
|
6
|
+
super(...arguments);
|
|
7
|
+
this.tokenize = tokenize;
|
|
8
|
+
}
|
|
9
|
+
equals(left, right, options) {
|
|
10
|
+
// If we're ignoring whitespace, we need to normalise lines by stripping
|
|
11
|
+
// whitespace before checking equality. (This has an annoying interaction
|
|
12
|
+
// with newlineIsToken that requires special handling: if newlines get their
|
|
13
|
+
// own token, then we DON'T want to trim the *newline* tokens down to empty
|
|
14
|
+
// strings, since this would cause us to treat whitespace-only line content
|
|
15
|
+
// as equal to a separator between lines, which would be weird and
|
|
16
|
+
// inconsistent with the documented behavior of the options.)
|
|
17
|
+
if (options.ignoreWhitespace) {
|
|
18
|
+
if (!options.newlineIsToken || !left.includes('\n')) {
|
|
19
|
+
left = left.trim();
|
|
20
|
+
}
|
|
21
|
+
if (!options.newlineIsToken || !right.includes('\n')) {
|
|
22
|
+
right = right.trim();
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
|
|
26
|
+
if (left.endsWith('\n')) {
|
|
27
|
+
left = left.slice(0, -1);
|
|
28
|
+
}
|
|
29
|
+
if (right.endsWith('\n')) {
|
|
30
|
+
right = right.slice(0, -1);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return super.equals(left, right, options);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export const lineDiff = new LineDiff();
|
|
37
|
+
export function diffLines(oldStr, newStr, options) {
|
|
38
|
+
return lineDiff.diff(oldStr, newStr, options);
|
|
39
|
+
}
|
|
40
|
+
export function diffTrimmedLines(oldStr, newStr, options) {
|
|
41
|
+
options = generateOptions(options, { ignoreWhitespace: true });
|
|
42
|
+
return lineDiff.diff(oldStr, newStr, options);
|
|
43
|
+
}
|
|
44
|
+
// Exported standalone so it can be used from jsonDiff too.
|
|
45
|
+
export function tokenize(value, options) {
|
|
46
|
+
if (options.stripTrailingCr) {
|
|
47
|
+
// remove one \r before \n to match GNU diff's --strip-trailing-cr behavior
|
|
48
|
+
value = value.replace(/\r\n/g, '\n');
|
|
49
|
+
}
|
|
50
|
+
const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
|
|
51
|
+
// Ignore the final empty token that occurs if the string ends with a new line
|
|
52
|
+
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
|
|
53
|
+
linesAndNewlines.pop();
|
|
54
|
+
}
|
|
55
|
+
// Merge the content and line separators into single tokens
|
|
56
|
+
for (let i = 0; i < linesAndNewlines.length; i++) {
|
|
57
|
+
const line = linesAndNewlines[i];
|
|
58
|
+
if (i % 2 && !options.newlineIsToken) {
|
|
59
|
+
retLines[retLines.length - 1] += line;
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
retLines.push(line);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return retLines;
|
|
66
|
+
}
|