dsh-remote 1.0.1 → 1.1.2

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.
@@ -332,23 +332,70 @@ function handover(file, args, extraEnv) {
332
332
  return child
333
333
  }
334
334
 
335
- /** A compact context banner; metadata must never inject terminal controls. */
336
- function connectionBanner(target, env = process.env) {
337
- const safe = (value) => String(value || '').replace(/[\x00-\x1f\x7f]/g, '')
338
- const user = safe(target.username)
339
- const host = safe(target.alias || target.host)
340
- const port = !target.alias && Number(target.port) && Number(target.port) !== 22 ? ':' + Number(target.port) : ''
341
- const label = 'SSH ' + (user ? user + '@' : '') + host + port
342
- const directory = safe(target.remotePath)
343
- const color = !env.NO_COLOR && env.TERM && env.TERM !== 'dumb'
344
- return '\r\n' + (color ? '\x1b[36m' + label + '\x1b[0m' : label) + '\r\n' + (directory ? ' ' + directory + '\r\n' : '') + '\r\n'
335
+ // A small whale-shaped pixel mark, following the DSH mascot silhouette. Two
336
+ // pixel rows share one terminal row so it stays compact beside a normal prompt.
337
+ // This is terminal text (SGR + block characters), not an image protocol or DOM
338
+ // overlay; it works in the native terminal and never echoes connection secrets.
339
+ const TERMINAL_FISH = [
340
+ ' bbbb b',
341
+ ' bbbbbbbbbb bb',
342
+ ' bbbbbbbbbbbbbb bbb',
343
+ ' bbbbbbbbbbbbbbbbbbbbb',
344
+ 'bbbbbbbbbbbbbbbbbbbb',
345
+ 'bbbbbbebbbbbbbbbbbb',
346
+ 'bbbbbbbbbllllbbbbbb',
347
+ ' bbbbbbblllllbbbbb',
348
+ ' bbbbbbbbbbbbbb',
349
+ ' bbbbbbbb',
350
+ ]
351
+
352
+ /** Render a static welcome mark; a restart prints once, never on a poll/resize.
353
+ * `_target` is deliberately ignored: shell prompts and the workbench already
354
+ * identify the remote, so the decoration must not duplicate host/path metadata.
355
+ */
356
+ function connectionBanner(_target, env = process.env, terminalColumns) {
357
+ const columns = Number(terminalColumns || env.COLUMNS)
358
+ const width = Number.isFinite(columns) && columns > 0 ? Math.floor(columns) : 80
359
+ if (width < 12) return ''
360
+ const color = env.NO_COLOR === undefined && !!env.TERM && env.TERM !== 'dumb'
361
+ const reset = color ? '\x1b[0m' : ''
362
+ // Avoid wrapping the fish in a narrow split terminal. ASCII is the most
363
+ // portable fallback, including terminals without block-character support.
364
+ if (width < 30 || env.TERM === 'dumb') return '\r\n' + (color ? '\x1b[36m' : '') + '><(((o> dsh' + reset + '\r\n\r\n'
365
+ const pixelWidth = 23
366
+ const ink = { b: '36', l: '96', e: '30' }
367
+ const lines = []
368
+ for (let y = 0; y < TERMINAL_FISH.length; y += 2) {
369
+ const upper = TERMINAL_FISH[y].padEnd(pixelWidth)
370
+ const lower = TERMINAL_FISH[y + 1].padEnd(pixelWidth)
371
+ let line = ' ', lastStyle = ''
372
+ for (let x = 0; x < pixelWidth; x++) {
373
+ // In monochrome the eye stays a hole rather than a filled body pixel.
374
+ const top = color ? ink[upper[x]] : upper[x] !== ' ' && upper[x] !== 'e'
375
+ const bottom = color ? ink[lower[x]] : lower[x] !== ' ' && lower[x] !== 'e'
376
+ let glyph = ' ', style = ''
377
+ if (top && bottom) {
378
+ glyph = top === bottom ? '█' : '▀'
379
+ if (color) style = '\x1b[' + top + ';' + (top === bottom ? '49' : String(Number(bottom) + 10)) + 'm'
380
+ } else if (top || bottom) {
381
+ glyph = top ? '▀' : '▄'
382
+ if (color) style = '\x1b[' + (top || bottom) + ';49m'
383
+ } else if (color) style = '\x1b[0m'
384
+ if (style !== lastStyle) { line += style; lastStyle = style }
385
+ line += glyph
386
+ }
387
+ line += reset
388
+ if (y === 4) line += ' dsh'
389
+ lines.push(line.trimEnd())
390
+ }
391
+ return '\r\n' + lines.join('\r\n') + '\r\n\r\n'
345
392
  }
346
393
 
347
394
  /**
348
395
  * Entry point: connect, or explain why a local shell was used instead.
349
396
  * @param {string[]} [argv]
350
397
  * @param {{ cwd?: string, platform?: string, env?: object,
351
- * stdin?: object, fstat?: (fd: number) => any,
398
+ * stdin?: object, columns?: number, fstat?: (fd: number) => any,
352
399
  * write?: (line: string) => void, exit?: (code: number) => any }} [deps]
353
400
  */
354
401
  function main(argv = process.argv.slice(2), deps = {}) {
@@ -375,7 +422,7 @@ function main(argv = process.argv.slice(2), deps = {}) {
375
422
  }
376
423
  const ssh = sshBinary(platform, env)
377
424
  const args = buildSshArgs(resolved.target, resolved.machine)
378
- write(connectionBanner(resolved.target, env))
425
+ write(connectionBanner(resolved.target, env, deps.columns || process.stderr.columns || process.stdout.columns))
379
426
  if (isWindowsRemotePath(resolved.target.remotePath)) {
380
427
  process.stderr.write('[dsh-remote] the remote workspace is a Windows path; opening the remote default shell without changing directory.\n')
381
428
  process.stderr.write('[dsh-remote] 远端工作区是 Windows 路径,已打开默认 shell(未自动切换目录)。\n')
@@ -292,7 +292,7 @@ export function launcherSource(spec) {
292
292
  `DSH_CHILD=${shqPosix(child)}`,
293
293
  `DSH_MACHINES=${shqPosix(machines)}`,
294
294
  // Physical directory of this script: the askpass helper + payload live here.
295
- 'DSH_TERM_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)',
295
+ 'export DSH_TERM_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)',
296
296
  node ? `DSH_NODE=${shqPosix(node)}` : 'DSH_NODE=',
297
297
  'if [ -n "$DSH_NODE" ] && [ -x "$DSH_NODE" ]; then exec "$DSH_NODE" "$DSH_CHILD" --machines "$DSH_MACHINES"; fi',
298
298
  'if command -v node >/dev/null 2>&1; then exec node "$DSH_CHILD" --machines "$DSH_MACHINES"; fi',
@@ -0,0 +1,51 @@
1
+ // Stage complete writes beside their target, check the captured baseline, then
2
+ // replace. This is optimistic conflict detection, not a cross-process CAS.
3
+ import { randomUUID, createHash } from 'node:crypto'
4
+ import { CHANGE_CAPTURE_BYTES } from './file-changes.js'
5
+
6
+ export const missingRemoteFile = error => error?.code === 2 || error?.code === 'ENOENT' || error?.code === 'NO_SUCH_FILE'
7
+ export const remoteRevision = buf => createHash('sha256').update(buf).digest('hex')
8
+ const conflict = () => Object.assign(new Error('Remote file changed while saving; reload and compare before retrying.'), { httpStatus: 409, code: 'REMOTE_FILE_CONFLICT' })
9
+ const statOrMissing = async (sftp, path) => { try { return await sftp.stat(path) } catch (error) { if (!missingRemoteFile(error)) throw error; return null } }
10
+
11
+ export async function captureRemoteFile(sftp, path, { read = false, maxBytes = CHANGE_CAPTURE_BYTES, maxReadBytes = 0 } = {}) {
12
+ const stat = await statOrMissing(sftp, path)
13
+ if (!stat) return { path, target: path, stat: null, bytes: null }
14
+ if (stat.isDirectory?.()) throw new Error('A file path is required, not a directory')
15
+ if (read && maxReadBytes > 0 && stat.size > maxReadBytes) throw Object.assign(new Error('File exceeds the configured editing size limit'), { httpStatus: 413, code: 'REMOTE_FILE_TOO_LARGE' })
16
+ const target = typeof sftp.realpath === 'function' ? await sftp.realpath(path) : path
17
+ let bytes
18
+ if (read || stat.size <= maxBytes) {
19
+ // Production surfaces have a bounded range reader. Request one byte past
20
+ // the observed size to detect growth without reading an arbitrarily large
21
+ // file that changed after stat().
22
+ bytes = typeof sftp.readPartial === 'function'
23
+ ? await sftp.readPartial(target, 0, stat.size + 1)
24
+ : await sftp.readFile(target)
25
+ if (bytes.byteLength !== stat.size) throw conflict()
26
+ }
27
+ return { path, target, stat, bytes }
28
+ }
29
+
30
+ export async function atomicRemoteWrite(sftp, snapshot, content) {
31
+ const { path, target, stat, bytes } = snapshot
32
+ const temporary = `${target}.dsh-remote-edit-${randomUUID()}.tmp`
33
+ try {
34
+ // Passing mode at creation avoids a public temporary copy of a 0600 file.
35
+ await sftp.writeFile(temporary, content, { mode: typeof stat?.mode === 'number' ? stat.mode & 0o777 : 0o666 })
36
+ if (stat && typeof stat.mode === 'number' && typeof sftp.setstat === 'function') await sftp.setstat(temporary, { mode: stat.mode & 0o777 })
37
+ const current = await statOrMissing(sftp, path)
38
+ if (!!stat !== !!current || stat && (stat.size !== current.size || stat.mtime !== current.mtime)) throw conflict()
39
+ if (stat && typeof sftp.realpath === 'function' && await sftp.realpath(path) !== target) throw conflict()
40
+ if (stat && bytes) {
41
+ const latest = typeof sftp.readPartial === 'function'
42
+ ? await sftp.readPartial(target, 0, bytes.byteLength + 1)
43
+ : await sftp.readFile(target)
44
+ if (!Buffer.from(latest).equals(Buffer.from(bytes))) throw conflict()
45
+ }
46
+ if (stat) await sftp.renameOverwrite(temporary, target)
47
+ else await sftp.rename(temporary, target)
48
+ } finally {
49
+ try { await sftp.unlink(temporary) } catch { /* original error wins */ }
50
+ }
51
+ }
package/lib/routes-fs.js CHANGED
@@ -4,12 +4,18 @@
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
+ // URLSearchParams already decodes query paths. Another decoding pass corrupts
8
+ // literal percent characters and names containing sequences such as `%2F`.
7
9
  import { mkdirSync } from 'node:fs'
8
10
  import path from 'node:path'
11
+ import { mirrorDownloadTarget, assertDownloadHasNoSymlinks } from './mirror-paths.js'
12
+ export { mirrorDownloadTarget } from './mirror-paths.js'
13
+ import { createLocalCopyRoutes, localCopyInfo } from './local-copy.js'
9
14
  import {
10
15
  normalizeRemotePath, joinRemotePath, remoteDirname, mkdirRemoteDirs, toDisplayPath,
11
16
  } from './paths.js'
12
17
  import { requestSessionHint } from './binding.js'
18
+ import { captureRemoteFile, atomicRemoteWrite, remoteRevision, missingRemoteFile } from './remote-write.js'
13
19
  import { listDirStructured, listRemoteDrives, removeRemoteTree, previewRemoteFile } from './remote-fs.js'
14
20
 
15
21
  export function createFsRoutes({
@@ -32,7 +38,25 @@ export function createFsRoutes({
32
38
  }
33
39
  }
34
40
 
41
+ const checkExpectedRevision = (body, snapshot) => {
42
+ if (body.expectedRevision != null) {
43
+ if (typeof body.expectedRevision !== 'string' || !/^[a-f0-9]{64}$/.test(body.expectedRevision)) {
44
+ throw Object.assign(new Error('expectedRevision must be a SHA-256 revision returned by a complete file preview'), { httpStatus: 400 })
45
+ }
46
+ if (!snapshot.stat || !snapshot.bytes || remoteRevision(snapshot.bytes) !== body.expectedRevision) {
47
+ throw Object.assign(new Error('远端文件已变化,已放弃保存。请重新读取并比较后重试。'), { httpStatus: 409, code: 'REMOTE_FILE_CONFLICT' })
48
+ }
49
+ }
50
+ if (body.expectedMtime != null) {
51
+ if (!Number.isFinite(Number(body.expectedMtime))) throw Object.assign(new Error('expectedMtime must be a finite timestamp'), { httpStatus: 400 })
52
+ if (!snapshot.stat || snapshot.stat.mtime !== Number(body.expectedMtime)) {
53
+ throw Object.assign(new Error('远端文件已变化,已放弃保存。请重新读取并比较后重试。'), { httpStatus: 409, code: 'REMOTE_FILE_CONFLICT' })
54
+ }
55
+ }
56
+ }
57
+
35
58
  return [
59
+ ...createLocalCopyRoutes({ sendJson, readBody, resolveRequestBinding, config, audit, onRemoteMutation }),
36
60
  {
37
61
  kind: 'exact',
38
62
  path: '/dsh-remote/ls',
@@ -65,7 +89,7 @@ export function createFsRoutes({
65
89
  await b.pool.detect()
66
90
  const q = new URL(req.url, 'http://localhost').searchParams
67
91
  const raw = q.get('path')
68
- ? decodeURIComponent(q.get('path'))
92
+ ? q.get('path')
69
93
  : (body.path ? String(body.path) : (b.ws || ''))
70
94
  const canon = normalizeRemotePath(raw)
71
95
  const win = b.pool.platform === 'windows'
@@ -102,7 +126,7 @@ export function createFsRoutes({
102
126
  if (req.method !== 'GET' && req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method not allowed' })
103
127
  try {
104
128
  const q = new URL(req.url, 'http://localhost').searchParams
105
- let p = q.get('path') ? decodeURIComponent(q.get('path')) : ''
129
+ let p = q.get('path') ? q.get('path') : ''
106
130
  let encoding = ''
107
131
  let maxBytes = 256 * 1024
108
132
  let body = {}
@@ -131,6 +155,14 @@ export function createFsRoutes({
131
155
  })
132
156
  return sendJson(res, 200, preview)
133
157
  } catch (err) {
158
+ if (missingRemoteFile(err)) {
159
+ const localCopy = await localCopyInfo(b, target)
160
+ return sendJson(res, 404, { ok: false, source: 'remote', path: target,
161
+ code: localCopy ? 'REMOTE_FILE_MISSING_LOCAL_COPY' : 'REMOTE_FILE_NOT_FOUND',
162
+ error: localCopy ? '远端不存在此文件。本地镜像有同名副本,但尚未确认上传;可只读查看后显式上传。' : '远端不存在此文件。',
163
+ ...(localCopy ? { localCopy } : {}),
164
+ })
165
+ }
134
166
  return sendJson(res, 500, { ok: false, error: 'read failed: ' + ((err && err.message) || err) })
135
167
  }
136
168
  } catch (err) {
@@ -150,20 +182,17 @@ export function createFsRoutes({
150
182
  const b = await bindOrReply(req, res, body)
151
183
  if (!b) return
152
184
  const sftp = await b.pool.sftp()
153
- let st = null
154
- try { st = await sftp.stat(p) } catch { /* new file */ }
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
- }
185
+ const before = await captureRemoteFile(sftp, p, { read: body.expectedRevision != null, maxReadBytes: 2 * 1024 * 1024 })
186
+ checkExpectedRevision(body, before)
158
187
  const buf = encodeText(String(body.content ?? ''), body.encoding || config.encoding)
159
- if (!st) await mkdirRemoteDirs(sftp, remoteDirname(p))
160
- await sftp.writeFile(p, buf)
188
+ if (!before.stat) await mkdirRemoteDirs(sftp, remoteDirname(p))
189
+ await atomicRemoteWrite(sftp, before, buf)
161
190
  audit('write', `write ${p}`, 0, b)
162
191
  onRemoteMutation()
163
192
  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) })
193
+ return sendJson(res, 200, { ok: true, bytes: buf.byteLength, mtime: st2 ? st2.mtime : Math.floor(Date.now() / 1000), revision: remoteRevision(buf) })
165
194
  } catch (err) {
166
- return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
195
+ return sendJson(res, err.httpStatus || 500, { ok: false, error: String((err && err.message) || err), ...(err.code ? { code: err.code } : {}) })
167
196
  }
168
197
  },
169
198
  },
@@ -212,30 +241,33 @@ export function createFsRoutes({
212
241
  if (op === 'write' || op === 'append') {
213
242
  const p = normalizeRemotePath(String(body.path || ''))
214
243
  if (!p || p === '/') return sendJson(res, 400, { ok: false, error: 'path required' })
215
- let content = ''
216
- if (op === 'append') {
217
- try { content = decodeBuf(await sftp.readFile(p), body.encoding || config.encoding) } catch { /* new */ }
218
- }
244
+ const before = await captureRemoteFile(sftp, p, {
245
+ read: op === 'append' || body.expectedRevision != null,
246
+ maxReadBytes: config.maxFileBytes > 0 ? Math.min(config.maxFileBytes, 2 * 1024 * 1024) : 2 * 1024 * 1024,
247
+ })
248
+ checkExpectedRevision(body, before)
249
+ const content = op === 'append' && before.bytes ? decodeBuf(before.bytes, body.encoding || config.encoding) : ''
219
250
  const buf = encodeText(content + String(body.content ?? ''), body.encoding || config.encoding)
220
- if (op === 'write' && !(await sftp.stat(p).catch(() => null))) await mkdirRemoteDirs(sftp, remoteDirname(p))
221
- await sftp.writeFile(p, buf)
251
+ if (op === 'write' && !before.stat) await mkdirRemoteDirs(sftp, remoteDirname(p))
252
+ await atomicRemoteWrite(sftp, before, buf)
222
253
  audit(op, `${op} ${p}`, 0, b)
223
254
  onRemoteMutation()
224
- return sendJson(res, 200, { ok: true, bytes: buf.byteLength })
255
+ return sendJson(res, 200, { ok: true, bytes: buf.byteLength, revision: remoteRevision(buf) })
225
256
  }
226
257
  if (op === 'download') {
227
258
  const p = normalizeRemotePath(String(body.path || ''))
228
259
  const ws = b.ws
229
260
  if (!p || p === '/') return sendJson(res, 400, { ok: false, error: 'path required' })
230
261
  if (!ws) return sendJson(res, 400, { ok: false, error: 'no remote workspace set' })
231
- const st = await sftp.stat(p).catch(() => null)
262
+ const base = b.mirrorDir || mirrorDirFor(ws, b.host, b.username, b.port)
263
+ const local = mirrorDownloadTarget(base, ws, p)
264
+ const st = await sftp.stat(p).catch(error => { if (missingRemoteFile(error)) return null; throw error })
232
265
  if (!st) return sendJson(res, 404, { ok: false, error: 'not found' })
266
+ if (st.isDirectory?.()) return sendJson(res, 400, { ok: false, error: 'download requires a file' })
233
267
  if (config.maxFileBytes > 0 && st.size > config.maxFileBytes) {
234
268
  return sendJson(res, 400, { ok: false, error: `file is ${st.size} bytes (over ${config.maxFileBytes} cap)` })
235
269
  }
236
- const base = b.mirrorDir || mirrorDirFor(ws, b.host, b.username, b.port)
237
- const rel = p.startsWith(ws) ? p.slice(ws.length).replace(/^\/+/, '') : p.slice(1)
238
- const local = path.join(base, rel)
270
+ assertDownloadHasNoSymlinks(base, local)
239
271
  mkdirSync(path.dirname(local), { recursive: true })
240
272
  await sftp.fastGet(p, local)
241
273
  audit('download', `download ${p}`, 0, b)
@@ -243,7 +275,7 @@ export function createFsRoutes({
243
275
  }
244
276
  return sendJson(res, 400, { ok: false, error: 'unknown op' })
245
277
  } catch (err) {
246
- return sendJson(res, 500, { ok: false, error: String((err && err.message) || err) })
278
+ return sendJson(res, err.httpStatus || 500, { ok: false, error: String((err && err.message) || err), ...(err.code ? { code: err.code } : {}) })
247
279
  }
248
280
  },
249
281
  },
@@ -100,7 +100,23 @@ 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
+ // Recovery publishing must reserve the destination on the SERVER. Never
105
+ // replace an existing file, including one created by a concurrent request.
106
+ createFileExclusive: async (p, data) => {
107
+ let created = false
108
+ try {
109
+ await withTimeout((d, bytes, cb) => {
110
+ sftp.open(d, 'wx', { mode: 0o600 }, (error, handle) => {
111
+ if (error) { error.exclusiveOpenFailed = true; return cb(error) }
112
+ created = true
113
+ sftp.write(handle, bytes, 0, bytes.length, 0, writeError => {
114
+ sftp.close(handle, closeError => cb(writeError || closeError))
115
+ })
116
+ })
117
+ })(P(p), data)
118
+ } catch (error) { error.exclusiveFileCreated = created; throw error }
119
+ },
104
120
  fastGet: (p, lp) => withTimeout((d, l, cb) => sftp.fastGet(d, l, cb))(P(p), lp),
105
121
  fastPut: (lp, p) => withTimeout((l, d, cb) => sftp.fastPut(l, d, cb))(lp, P(p)),
106
122
  // 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,4 @@
1
+ Source: https://www.npmjs.com/package/diff/v/8.0.4
2
+ License: BSD-3-Clause
3
+ Only the ESM structuredPatch dependency closure is included.
4
+ Rebuild: npm ci --legacy-peer-deps && node scripts/vendor-diff.mjs
@@ -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
+ }