dsh-remote 1.2.0 → 1.2.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 +10 -2
- package/README.md +10 -2
- package/lib/binding.js +26 -2
- package/lib/boot.js +4 -31
- package/lib/client.js +408 -66
- package/lib/connect-summary.js +52 -0
- package/lib/forwards.js +285 -35
- package/lib/index.js +20 -4615
- package/lib/main.js +4660 -0
- package/lib/openssh.js +59 -8
- package/lib/routes-forwards.js +24 -4
- package/lib/self-heal.js +58 -5
- package/lib/sshconfig.js +6 -0
- package/lib/update.js +95 -33
- package/lib/vendor/jsdiff/SOURCE.md +1 -1
- package/lib/vendor/jsdiff/diff/base.js +1 -1
- package/lib/vendor/jsdiff/diff/line.js +1 -1
- package/lib/vendor/jsdiff/patch/create.js +147 -18
- package/lib/vendor/jsdiff/util/params.js +1 -1
- package/package.json +4 -4
package/lib/openssh.js
CHANGED
|
@@ -317,6 +317,9 @@ export class OpenSshConnection extends EventEmitter {
|
|
|
317
317
|
* Local forward: carry bytes to <destHost>:<destPort> as seen FROM the
|
|
318
318
|
* remote, through `ssh -W`.
|
|
319
319
|
*
|
|
320
|
+
* The channel is handed over as soon as the child is running — NOT when
|
|
321
|
+
* `ssh -W` exits. See the body for why that distinction is load-bearing.
|
|
322
|
+
*
|
|
320
323
|
* @returns {boolean} true synchronously, so capability probes can be sync.
|
|
321
324
|
*/
|
|
322
325
|
forwardOut(_srcHost, _srcPort, destHost, destPort, cb) {
|
|
@@ -327,26 +330,68 @@ export class OpenSshConnection extends EventEmitter {
|
|
|
327
330
|
setImmediate(() => cb(err))
|
|
328
331
|
return true
|
|
329
332
|
}
|
|
330
|
-
// `ssh -W`
|
|
331
|
-
//
|
|
333
|
+
// `ssh -W` is the tunnel itself: for as long as the channel is usable the
|
|
334
|
+
// child stays ALIVE and only exits when the peer or the caller closes it.
|
|
335
|
+
// Waiting for 'close' to declare success therefore never resolves for a
|
|
336
|
+
// healthy tunnel; the caller never writes the first byte and the peer times
|
|
337
|
+
// out. Hand the channel over on the next tick instead — ssh buffers stdin
|
|
338
|
+
// until the remote channel opens — and report failures by destroying it.
|
|
339
|
+
//
|
|
340
|
+
// The one-tick delay is load-bearing: a spawn error (bad binary, EACCES)
|
|
341
|
+
// arrives in that same window, and the calling Promise only attaches its
|
|
342
|
+
// handlers in the microtask after `cb`. Without the delay the error would
|
|
343
|
+
// be emitted into the no-op listener and the caller would receive an
|
|
344
|
+
// already-destroyed channel (the local socket would hang forever).
|
|
332
345
|
let stderr = ''
|
|
333
346
|
let handed = false
|
|
347
|
+
let failed = false
|
|
348
|
+
let closing = false
|
|
349
|
+
let ended = false
|
|
334
350
|
const channel = new Duplex({
|
|
335
351
|
read() {},
|
|
336
352
|
write(chunk, _enc, done) { try { child.stdin.write(chunk, done) } catch (e) { done(e) } },
|
|
337
353
|
final(done) { try { child.stdin.end(done) } catch { done() } },
|
|
338
354
|
destroy(err, done) { try { child.kill() } catch {} ; done(err) },
|
|
339
355
|
})
|
|
340
|
-
channel.close = () => { try { child.kill() } catch {} }
|
|
356
|
+
channel.close = () => { closing = true; try { child.kill() } catch {} }
|
|
357
|
+
// Until the caller attaches its own 'error' handler (one microtask after
|
|
358
|
+
// cb) a failure must not become an unhandled 'error' event.
|
|
359
|
+
channel.on('error', () => { /* callers attach their own kill handler */ })
|
|
360
|
+
const endReadable = () => {
|
|
361
|
+
if (ended) return
|
|
362
|
+
ended = true
|
|
363
|
+
try { channel.push(null) } catch { /* already gone */ }
|
|
364
|
+
}
|
|
365
|
+
const fail = (err) => {
|
|
366
|
+
if (failed) return
|
|
367
|
+
failed = true
|
|
368
|
+
if (handed) channel.destroy(err)
|
|
369
|
+
else { handed = true; cb(err) }
|
|
370
|
+
}
|
|
341
371
|
child.stderr.on('data', (d) => { stderr += d })
|
|
342
372
|
child.stdout.on('data', (d) => channel.push(d))
|
|
343
|
-
|
|
344
|
-
|
|
373
|
+
// stdout's EOF is deliberately NOT forwarded yet: a non-zero exit can
|
|
374
|
+
// follow it (truncated response), and ending first would let the caller's
|
|
375
|
+
// pipe close the socket as if the stream had finished cleanly. Only the
|
|
376
|
+
// child's exit verdict decides: code 0 (or a caller close) means EOF.
|
|
377
|
+
child.on('error', fail)
|
|
345
378
|
child.on('close', (code) => {
|
|
346
|
-
if (
|
|
379
|
+
if (failed) return
|
|
380
|
+
if (!handed) {
|
|
381
|
+
// Exited before the deferred success handover: keep the old contract.
|
|
382
|
+
if (code === 0) { handed = true; cb(null, channel); endReadable(); return }
|
|
383
|
+
handed = true
|
|
384
|
+
cb(new Error(`ssh -W to ${destHost}:${destPort} failed (exit ${code})${stderr ? ': ' + stderr.trim() : ''}`))
|
|
385
|
+
return
|
|
386
|
+
}
|
|
387
|
+
if (closing) { endReadable(); return }
|
|
388
|
+
if (code === 0) { endReadable(); return }
|
|
389
|
+
channel.destroy(new Error(`ssh -W to ${destHost}:${destPort} failed (exit ${code})${stderr ? ': ' + stderr.trim() : ''}`))
|
|
390
|
+
})
|
|
391
|
+
setImmediate(() => {
|
|
392
|
+
if (handed || failed) return
|
|
347
393
|
handed = true
|
|
348
|
-
|
|
349
|
-
cb(new Error(`ssh -W to ${destHost}:${destPort} failed (exit ${code})${stderr ? ': ' + stderr.trim() : ''}`))
|
|
394
|
+
cb(null, channel)
|
|
350
395
|
})
|
|
351
396
|
return true
|
|
352
397
|
}
|
|
@@ -559,6 +604,12 @@ export class SystemOpenSshPool {
|
|
|
559
604
|
const probe = await this._runSsh(['--', this.destination(), 'true'], { timeoutMs: this.config.connectTimeoutMs || 15000 })
|
|
560
605
|
if (!isCurrent()) throw new Error('ssh target changed during connect')
|
|
561
606
|
if (probe.code !== 0) {
|
|
607
|
+
// dsh-remote-fix3: _runSsh reports its own timer as code -1 / signal
|
|
608
|
+
// TIMEOUT with empty stderr, so the old message degraded to a bare
|
|
609
|
+
// `ssh failed (exit -1)` and told the settings page nothing actionable.
|
|
610
|
+
if (probe.signal === 'TIMEOUT') {
|
|
611
|
+
throw new Error(`ssh timed out after ${this.config.connectTimeoutMs || 15000}ms (no reply from the host — raise the connect timeout if this link is just slow)`)
|
|
612
|
+
}
|
|
562
613
|
throw new Error(`ssh failed (exit ${probe.code})${String(probe.stderr || '').trim() ? ': ' + String(probe.stderr).trim() : ''}`)
|
|
563
614
|
}
|
|
564
615
|
void secret
|
package/lib/routes-forwards.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* @param {object} deps.store - machine-registry store (`currentId` tags new definitions).
|
|
14
14
|
* @returns {Array<object>} route descriptors for registerHttpTransports.
|
|
15
15
|
*/
|
|
16
|
-
export function createForwardRoutes({ sendJson, readBody, forwards, store }) {
|
|
16
|
+
export function createForwardRoutes({ sendJson, readBody, forwards, store, activeMachineId }) {
|
|
17
17
|
return [
|
|
18
18
|
{
|
|
19
19
|
kind: 'exact',
|
|
@@ -43,18 +43,38 @@ export function createForwardRoutes({ sendJson, readBody, forwards, store }) {
|
|
|
43
43
|
targetHost: body.targetHost || '127.0.0.1',
|
|
44
44
|
targetPort,
|
|
45
45
|
autoStart: !!body.autoStart,
|
|
46
|
-
|
|
46
|
+
// Tag what the ACTIVE POOL is actually on (ephemeral included),
|
|
47
|
+
// not the registry's currentId: rw_connect(save:false) keeps
|
|
48
|
+
// currentId on the old machine while the pool talks to the new one.
|
|
49
|
+
machineId: typeof activeMachineId === 'function' ? activeMachineId() : store.currentId,
|
|
47
50
|
})
|
|
48
51
|
return sendJson(res, 200, { ok: true, forward: d, forwards: forwards.list() })
|
|
49
52
|
}
|
|
53
|
+
if (action === 'update') {
|
|
54
|
+
// Mutable fields of an existing definition — currently the 自动重连
|
|
55
|
+
// checkbox shown on each row. Requires an explicit boolean: a
|
|
56
|
+
// missing field must not silently flip the flag to false.
|
|
57
|
+
if (typeof body.autoStart !== 'boolean') {
|
|
58
|
+
return sendJson(res, 400, { ok: false, error: 'autoStart 必须是布尔值' })
|
|
59
|
+
}
|
|
60
|
+
const d = forwards.update(String(body.id || ''), { autoStart: body.autoStart })
|
|
61
|
+
if (!d) return sendJson(res, 404, { ok: false, error: 'forward not found', forwards: forwards.list() })
|
|
62
|
+
return sendJson(res, 200, { ok: true, forward: d, forwards: forwards.list() })
|
|
63
|
+
}
|
|
50
64
|
if (action === 'start' || action === 'stop') {
|
|
51
65
|
const d = forwards.list().find((f) => f.id === body.id)
|
|
52
66
|
if (!d) return sendJson(res, 404, { ok: false, error: 'forward not found' })
|
|
53
67
|
if (action === 'start') {
|
|
54
68
|
const r = await forwards.start(d)
|
|
55
|
-
|
|
69
|
+
// Always return the CURRENT list, even on failure: a start that
|
|
70
|
+
// lost a race but found the tunnel already listening (see
|
|
71
|
+
// ForwardManager.start) must let the UI leave 启动 instead of
|
|
72
|
+
// staying on a stale row until the next click.
|
|
73
|
+
if (!r.ok) return sendJson(res, 500, { ok: false, error: r.error, forwards: forwards.list() })
|
|
56
74
|
} else {
|
|
57
|
-
|
|
75
|
+
// A user stop is intentional: clear the persisted "was running"
|
|
76
|
+
// flag so 自动重连 does not bring it back on the next connect.
|
|
77
|
+
forwards.stop(d.id, { forget: true })
|
|
58
78
|
}
|
|
59
79
|
return sendJson(res, 200, { ok: true, forwards: forwards.list() })
|
|
60
80
|
}
|
package/lib/self-heal.js
CHANGED
|
@@ -17,10 +17,11 @@
|
|
|
17
17
|
// self-contained). Any richer import could itself be the file that is missing,
|
|
18
18
|
// and then the guard dies together with the guarded.
|
|
19
19
|
|
|
20
|
-
import { readFileSync } from 'node:fs'
|
|
20
|
+
import { readFileSync, realpathSync } from 'node:fs'
|
|
21
21
|
import path from 'node:path'
|
|
22
|
+
import { fileURLToPath } from 'node:url'
|
|
22
23
|
|
|
23
|
-
import {
|
|
24
|
+
import { isInstalledCopy, diskVersion } from './update.js'
|
|
24
25
|
|
|
25
26
|
/**
|
|
26
27
|
* Whether `err` is the specific crash a half-applied update produces: Node
|
|
@@ -54,6 +55,13 @@ export function isMissingOwnModuleError(err) {
|
|
|
54
55
|
* when options.dir is set, the version is read from THAT directory's
|
|
55
56
|
* package.json rather than this package's own install dir.
|
|
56
57
|
*/
|
|
58
|
+
async function applyFreshUpdate(version, options) {
|
|
59
|
+
// A previous updater may already be in the ESM cache. Load the newly laid
|
|
60
|
+
// update.js with a fresh URL so repair never reuses that stale updater.
|
|
61
|
+
const { applyUpdate } = await import('./update.js?self-heal=' + Date.now())
|
|
62
|
+
return applyUpdate(version, options)
|
|
63
|
+
}
|
|
64
|
+
|
|
57
65
|
export async function repairInstall(options = {}) {
|
|
58
66
|
let version = diskVersion()
|
|
59
67
|
if (options.dir) {
|
|
@@ -66,7 +74,7 @@ export async function repairInstall(options = {}) {
|
|
|
66
74
|
if (!/^\d+\.\d+\.\d+/.test(version)) {
|
|
67
75
|
throw new Error(`cannot self-repair: on-disk package.json version is unusable (${JSON.stringify(version)})`)
|
|
68
76
|
}
|
|
69
|
-
return
|
|
77
|
+
return applyFreshUpdate(version, options)
|
|
70
78
|
}
|
|
71
79
|
|
|
72
80
|
/** Actionable suffix attached to every failure we hand back to the user. */
|
|
@@ -93,7 +101,7 @@ const REINSTALL_HINT = 'please reinstall the plugin once (e.g. `dsh plugin --pro
|
|
|
93
101
|
* forwarded to applyUpdate; log defaults to console.warn.
|
|
94
102
|
*/
|
|
95
103
|
export async function importWithSelfHeal(importer, options = {}) {
|
|
96
|
-
const { log = console.warn, ...repairOpts } = options || {}
|
|
104
|
+
const { log = console.warn, retryImporter, ...repairOpts } = options || {}
|
|
97
105
|
let firstErr
|
|
98
106
|
try {
|
|
99
107
|
return { module: await importer(), repaired: false }
|
|
@@ -119,7 +127,9 @@ export async function importWithSelfHeal(importer, options = {}) {
|
|
|
119
127
|
log(`[dsh-remote] startup repair applied ${repairOutcome.changed?.length ?? 0} file(s); retrying the load`)
|
|
120
128
|
|
|
121
129
|
try {
|
|
122
|
-
|
|
130
|
+
// Node 22 can cache a failed ESM resolution. Retry with a fresh URL when
|
|
131
|
+
// the caller supplies one, rather than reusing the negative cache.
|
|
132
|
+
return { module: await (retryImporter || importer)(), repaired: true }
|
|
123
133
|
} catch (secondErr) {
|
|
124
134
|
const wrapped = new Error(
|
|
125
135
|
`[dsh-remote] the install was re-laid from npm but loading still fails: ${(secondErr && secondErr.message) || secondErr}. ${REINSTALL_HINT}`,
|
|
@@ -128,3 +138,46 @@ export async function importWithSelfHeal(importer, options = {}) {
|
|
|
128
138
|
throw wrapped
|
|
129
139
|
}
|
|
130
140
|
}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* External repair entry point. It deliberately lives in this shallow module,
|
|
145
|
+
* not in index/main: a broken static dependency graph must not be needed to
|
|
146
|
+
* repair itself. `--dir` and `--tarball` are also useful for offline recovery
|
|
147
|
+
* and deterministic tests; normal users only need `node lib/self-heal.js`.
|
|
148
|
+
*/
|
|
149
|
+
const cliFile = (value) => {
|
|
150
|
+
try { return realpathSync(value) } catch { return path.resolve(value) }
|
|
151
|
+
}
|
|
152
|
+
const isMainModule = process.argv[1] && (() => {
|
|
153
|
+
const actual = cliFile(process.argv[1])
|
|
154
|
+
const self = cliFile(fileURLToPath(import.meta.url))
|
|
155
|
+
return process.platform === 'win32' ? actual.toLowerCase() === self.toLowerCase() : actual === self
|
|
156
|
+
})()
|
|
157
|
+
if (isMainModule) {
|
|
158
|
+
const args = process.argv.slice(2)
|
|
159
|
+
const valueFor = (flag) => {
|
|
160
|
+
const i = args.indexOf(flag)
|
|
161
|
+
return i >= 0 && i + 1 < args.length ? args[i + 1] : ''
|
|
162
|
+
}
|
|
163
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
164
|
+
console.log('Usage: node lib/self-heal.js [--version x.y.z] [--dir <package dir>] [--tarball <local tgz>]')
|
|
165
|
+
} else {
|
|
166
|
+
const dir = valueFor('--dir') || undefined
|
|
167
|
+
const tarballPath = valueFor('--tarball') || undefined
|
|
168
|
+
const version = valueFor('--version')
|
|
169
|
+
try {
|
|
170
|
+
if (version && !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {
|
|
171
|
+
throw new Error(`invalid version: ${JSON.stringify(version)}`)
|
|
172
|
+
}
|
|
173
|
+
const result = version
|
|
174
|
+
? await applyFreshUpdate(version, { dir, tarballPath })
|
|
175
|
+
: await repairInstall({ dir, tarballPath })
|
|
176
|
+
console.log(`[dsh-remote] repair completed: ${result.to}, ${result.changed?.length ?? 0} file(s) changed. Restart DSH to load the repaired package.`)
|
|
177
|
+
} catch (error) {
|
|
178
|
+
console.error(`[dsh-remote] repair failed: ${(error && error.message) || error}`)
|
|
179
|
+
console.error(REINSTALL_HINT)
|
|
180
|
+
process.exitCode = 1
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
package/lib/sshconfig.js
CHANGED
|
@@ -476,6 +476,10 @@ function targetFromResolved(resolved, text, { defaultPort }) {
|
|
|
476
476
|
port: resolved.port || defaultPort,
|
|
477
477
|
username: resolved.user || '',
|
|
478
478
|
privateKeyPath: identityPath(resolved.identityFile, ctx),
|
|
479
|
+
// Preserve raw connection settings for client-side effective-config
|
|
480
|
+
// grouping; the normalized privateKeyPath/proxy above stays unchanged.
|
|
481
|
+
identityFile: resolved.identityFile,
|
|
482
|
+
proxyCommand: resolved.proxyCommand,
|
|
479
483
|
agentSocket: identityAgentPath(resolved.identityAgent, ctx),
|
|
480
484
|
identitiesOnly: /^yes$/i.test(resolved.identitiesOnly || ''),
|
|
481
485
|
proxy,
|
|
@@ -583,6 +587,8 @@ export function resolveMachineSshConfig(machine, opts = {}) {
|
|
|
583
587
|
port: Number(port) || 22,
|
|
584
588
|
username: String(username || ''),
|
|
585
589
|
privateKeyPath,
|
|
590
|
+
identityFile: target.identityFile,
|
|
591
|
+
proxyCommand: target.proxyCommand,
|
|
586
592
|
agentSocket: target.agentSocket,
|
|
587
593
|
identitiesOnly: target.identitiesOnly,
|
|
588
594
|
proxy,
|
package/lib/update.js
CHANGED
|
@@ -175,21 +175,30 @@ export async function applyUpdate(targetVersion, options = {}) {
|
|
|
175
175
|
throw new Error('refusing to self-update: this copy is not under node_modules (link/dev install) — update it from its source repo instead')
|
|
176
176
|
}
|
|
177
177
|
const tarballUrl = `https://registry.npmjs.org/${NPM_PACKAGE}/-/${NPM_PACKAGE}-${targetVersion}.tgz`
|
|
178
|
-
const dir = options.dir || selfDir()
|
|
178
|
+
const dir = path.resolve(options.dir || selfDir())
|
|
179
179
|
const doFetch = options.fetchImpl || fetch
|
|
180
|
+
const writeAtomic = options.writeFileAtomic || writeFileAtomic
|
|
181
|
+
const restoreFile = options.restoreFile || copyFileSync
|
|
180
182
|
const tmpRoot = path.join(dir, `.dsh-remote-update-${Date.now()}`)
|
|
181
183
|
const tmpPkg = path.join(tmpRoot, 'package')
|
|
184
|
+
let preserveBackup = false
|
|
182
185
|
try {
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
186
|
+
let buf
|
|
187
|
+
if (options.tarballPath) {
|
|
188
|
+
// Offline repair must not contact the registry at all.
|
|
189
|
+
buf = readFileSync(options.tarballPath)
|
|
190
|
+
} else {
|
|
191
|
+
const controller = new AbortController()
|
|
192
|
+
const timer = setTimeout(() => controller.abort(), 60000)
|
|
193
|
+
let res
|
|
194
|
+
try {
|
|
195
|
+
res = await doFetch(tarballUrl, { signal: controller.signal })
|
|
196
|
+
} finally {
|
|
197
|
+
clearTimeout(timer)
|
|
198
|
+
}
|
|
199
|
+
if (!res.ok) throw new Error(`download failed (HTTP ${res.status})`)
|
|
200
|
+
buf = Buffer.from(await res.arrayBuffer())
|
|
190
201
|
}
|
|
191
|
-
if (!res.ok) throw new Error(`download failed (HTTP ${res.status})`)
|
|
192
|
-
const buf = Buffer.from(await res.arrayBuffer())
|
|
193
202
|
// npm tarballs are gzipped tar; extract the package/ directory.
|
|
194
203
|
const { gunzipSync } = await import('node:zlib')
|
|
195
204
|
const tar = gunzipSync(buf)
|
|
@@ -197,10 +206,15 @@ export async function applyUpdate(targetVersion, options = {}) {
|
|
|
197
206
|
mkdirSync(tmpPkg, { recursive: true })
|
|
198
207
|
let extracted = 0
|
|
199
208
|
for (const f of files) {
|
|
200
|
-
const rel = f.name.replace(/^package\//, '')
|
|
209
|
+
const rel = f.name.replace(/^package\//, '').replace(/\\/g, '/')
|
|
201
210
|
if (!rel || rel === 'package/' || rel.endsWith('/')) continue
|
|
202
211
|
if (rel !== 'package.json' && rel !== 'cordis.patch.yml' && !rel.startsWith('lib/')) continue
|
|
203
|
-
const
|
|
212
|
+
const unsafe = rel.startsWith('/') || /^[a-zA-Z]:/.test(rel) || rel.split('/').includes('..')
|
|
213
|
+
if (unsafe) throw new Error(`unsafe tarball path: ${f.name}`)
|
|
214
|
+
const dest = path.resolve(tmpPkg, rel)
|
|
215
|
+
if (dest !== tmpPkg && !dest.startsWith(tmpPkg + path.sep)) {
|
|
216
|
+
throw new Error(`unsafe tarball path: ${f.name}`)
|
|
217
|
+
}
|
|
204
218
|
mkdirSync(path.dirname(dest), { recursive: true })
|
|
205
219
|
writeFileSync(dest, f.data)
|
|
206
220
|
extracted++
|
|
@@ -213,41 +227,89 @@ export async function applyUpdate(targetVersion, options = {}) {
|
|
|
213
227
|
// break the next boot — check the file size and that it is not empty).
|
|
214
228
|
const newIndex = path.join(tmpPkg, 'lib', 'index.js')
|
|
215
229
|
if (!existsSync(newIndex) || statSize(newIndex) < 100) throw new Error('tarball missing lib/index.js')
|
|
216
|
-
// Swap the installed files one at a time: atomic, and idempotent.
|
|
217
|
-
//
|
|
218
|
-
//
|
|
219
|
-
// half
|
|
220
|
-
// every 500 ms, a torn write would be re-hashed and served mid-copy.
|
|
221
|
-
// Skipping byte-identical files keeps a re-apply of the same version from
|
|
222
|
-
// churning mtimes (and the host half from reloading for nothing).
|
|
230
|
+
// Swap the installed files one at a time: atomic, and idempotent. The
|
|
231
|
+
// manifest also makes the whole operation transactional: a failed write or
|
|
232
|
+
// a silent content mismatch restores the previous tree instead of leaving
|
|
233
|
+
// a half-applied package that cannot import itself.
|
|
223
234
|
const installLib = path.join(dir, 'lib')
|
|
224
235
|
const tmpLib = path.join(tmpPkg, 'lib')
|
|
236
|
+
const manifest = []
|
|
237
|
+
for (const rel of listFilesRecursive(tmpLib)) {
|
|
238
|
+
manifest.push({ src: path.join(tmpLib, rel), dest: path.join(installLib, rel) })
|
|
239
|
+
}
|
|
240
|
+
for (const rel of ['package.json', 'cordis.patch.yml']) {
|
|
241
|
+
const src = path.join(tmpPkg, rel)
|
|
242
|
+
if (existsSync(src)) manifest.push({ src, dest: path.join(dir, rel) })
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const backupRoot = path.join(tmpRoot, 'backup')
|
|
246
|
+
const backups = new Map()
|
|
225
247
|
const changed = []
|
|
248
|
+
let mutationStarted = false
|
|
249
|
+
let rollbackError = ''
|
|
250
|
+
const backup = (dest) => {
|
|
251
|
+
if (backups.has(dest)) return
|
|
252
|
+
const existed = existsSync(dest)
|
|
253
|
+
let backupPath = ''
|
|
254
|
+
if (existed) {
|
|
255
|
+
backupPath = path.join(backupRoot, String(backups.size))
|
|
256
|
+
mkdirSync(path.dirname(backupPath), { recursive: true })
|
|
257
|
+
copyFileSync(dest, backupPath)
|
|
258
|
+
}
|
|
259
|
+
backups.set(dest, { existed, path: backupPath })
|
|
260
|
+
}
|
|
226
261
|
const install = (src, dest) => {
|
|
227
262
|
const bytes = readFileSync(src)
|
|
263
|
+
backup(dest)
|
|
228
264
|
if (sameFileContent(dest, bytes)) return
|
|
229
265
|
try { mkdirSync(path.dirname(dest), { recursive: true }) } catch {}
|
|
230
|
-
|
|
266
|
+
mutationStarted = true
|
|
267
|
+
writeAtomic(dest, bytes)
|
|
231
268
|
changed.push(path.relative(dir, dest).split(path.sep).join('/'))
|
|
232
269
|
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
270
|
+
const rollback = () => {
|
|
271
|
+
if (!mutationStarted) return
|
|
272
|
+
for (const [dest, saved] of [...backups].reverse()) {
|
|
273
|
+
try {
|
|
274
|
+
try { mkdirSync(path.dirname(dest), { recursive: true }) } catch {}
|
|
275
|
+
if (saved.existed) restoreFile(saved.path, dest)
|
|
276
|
+
else rmSync(dest, { force: true })
|
|
277
|
+
} catch (error) {
|
|
278
|
+
rollbackError = `rollback failed at ${path.relative(dir, dest)}: ${(error && error.message) || error}; backup retained at ${backupRoot}`
|
|
279
|
+
break
|
|
280
|
+
}
|
|
281
|
+
}
|
|
240
282
|
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
283
|
+
|
|
284
|
+
try {
|
|
285
|
+
for (const { src, dest } of manifest) install(src, dest)
|
|
286
|
+
// Do not trust the writes alone: verify every selected tarball file after
|
|
287
|
+
// the install, including nested .cjs/.js files and package metadata.
|
|
288
|
+
for (const { src, dest } of manifest) {
|
|
289
|
+
const expected = readFileSync(src)
|
|
290
|
+
let actual
|
|
291
|
+
try { actual = readFileSync(dest) } catch (error) {
|
|
292
|
+
throw new Error(`applied file missing: ${path.relative(dir, dest)} (${(error && error.message) || error})`)
|
|
293
|
+
}
|
|
294
|
+
if (!actual.equals(expected)) throw new Error(`applied file mismatch: ${path.relative(dir, dest)}`)
|
|
295
|
+
}
|
|
296
|
+
const marker = path.join(dir, '.dsh-remote-updated')
|
|
297
|
+
backup(marker)
|
|
298
|
+
mutationStarted = true
|
|
299
|
+
writeAtomic(marker, Buffer.from(String(targetVersion)))
|
|
300
|
+
return { ok: true, to: targetVersion, changed }
|
|
301
|
+
} catch (error) {
|
|
302
|
+
rollback()
|
|
303
|
+
if (rollbackError) {
|
|
304
|
+
preserveBackup = true
|
|
305
|
+
throw new Error(`${(error && error.message) || error}; ${rollbackError}`)
|
|
306
|
+
}
|
|
307
|
+
throw error
|
|
244
308
|
}
|
|
245
|
-
writeFileSync(path.join(dir, '.dsh-remote-updated'), String(targetVersion))
|
|
246
|
-
return { ok: true, to: targetVersion, changed }
|
|
247
309
|
} catch (err) {
|
|
248
310
|
throw new Error('update failed: ' + ((err && err.message) || err))
|
|
249
311
|
} finally {
|
|
250
|
-
try { rmSync(tmpRoot, { recursive: true, force: true }) } catch {}
|
|
312
|
+
if (!preserveBackup) { try { rmSync(tmpRoot, { recursive: true, force: true }) } catch {} }
|
|
251
313
|
}
|
|
252
314
|
}
|
|
253
315
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Vendored unchanged from jsdiff
|
|
1
|
+
// Vendored unchanged from jsdiff 9.0.0; BSD-3-Clause. See lib/vendor/jsdiff/LICENSE.
|
|
2
2
|
export default class Diff {
|
|
3
3
|
diff(oldStr, newStr,
|
|
4
4
|
// Type below is not accurate/complete - see above for full possibilities - but it compiles
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Vendored unchanged from jsdiff
|
|
1
|
+
// Vendored unchanged from jsdiff 9.0.0; BSD-3-Clause. See lib/vendor/jsdiff/LICENSE.
|
|
2
2
|
import Diff from './base.js';
|
|
3
3
|
import { generateOptions } from '../util/params.js';
|
|
4
4
|
class LineDiff extends Diff {
|