@twinsearth/timemachine-dsh-plugin 0.2.2 → 0.2.5
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/CHANGELOG.md +46 -0
- package/README.md +33 -5
- package/docs/ARCHITECTURE.md +26 -3
- package/docs/REQUIREMENTS.md +15 -1
- package/docs/TESTPLAN.md +29 -3
- package/lib/client.js +161 -47
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/scripts/host-menu-patch.mjs +1 -0
- package/src/plugin-compat.mjs +241 -0
- package/src/plugin.mjs +23 -1
- package/src/plugins.mjs +87 -17
- package/src/point.mjs +26 -2
- package/src/restore.mjs +39 -2
- package/src/service.mjs +2 -0
- package/src/telemetry.mjs +363 -0
- package/src/util/paths.mjs +23 -1
- package/src/version.mjs +2 -0
package/plugin.json
CHANGED
|
@@ -38,6 +38,7 @@ const PATCHED_BLOCK = `\t\t{
|
|
|
38
38
|
\t\t{
|
|
39
39
|
\t\t\tid: "${MARKER}",
|
|
40
40
|
\t\t\tlabel: "${LABEL}",
|
|
41
|
+
\t\t\tvisible: true,
|
|
41
42
|
\t\t\tclick: () => {
|
|
42
43
|
\t\t\t\tconst window = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows().find((candidate) => !candidate.isDestroyed());
|
|
43
44
|
\t\t\t\tif (window === void 0) return;
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DSH plugin compatibility checks used before a third-party install.
|
|
3
|
+
*
|
|
4
|
+
* DSH itself refuses to load a plugin whose `engines.dsh` (or DSH peer
|
|
5
|
+
* dependency) does not include the running runtime. A restore must not install
|
|
6
|
+
* such a plugin only for the next boot to reject it, so this module evaluates
|
|
7
|
+
* the same declaration before invoking the package manager.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import zlib from 'node:zlib';
|
|
13
|
+
|
|
14
|
+
import { readTar } from './archive/tar.mjs';
|
|
15
|
+
|
|
16
|
+
const SEMVER = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/u;
|
|
17
|
+
|
|
18
|
+
/** Parse a complete semantic version, preserving prerelease identifiers. */
|
|
19
|
+
export function parseSemver(value) {
|
|
20
|
+
if (typeof value !== 'string') return null;
|
|
21
|
+
const match = SEMVER.exec(value.trim());
|
|
22
|
+
if (match === null) return null;
|
|
23
|
+
return {
|
|
24
|
+
major: Number(match[1]),
|
|
25
|
+
minor: Number(match[2]),
|
|
26
|
+
patch: Number(match[3]),
|
|
27
|
+
prerelease: match[4] === undefined ? [] : match[4].split('.'),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function compareIdentifier(left, right) {
|
|
32
|
+
const leftNumeric = /^\d+$/u.test(left);
|
|
33
|
+
const rightNumeric = /^\d+$/u.test(right);
|
|
34
|
+
if (leftNumeric && rightNumeric) return Number(left) - Number(right);
|
|
35
|
+
if (leftNumeric) return -1;
|
|
36
|
+
if (rightNumeric) return 1;
|
|
37
|
+
return left.localeCompare(right);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** semver precedence, including prerelease ordering; build metadata is ignored. */
|
|
41
|
+
export function compareSemver(left, right) {
|
|
42
|
+
for (const key of ['major', 'minor', 'patch']) {
|
|
43
|
+
if (left[key] !== right[key]) return left[key] - right[key];
|
|
44
|
+
}
|
|
45
|
+
if (left.prerelease.length === 0 && right.prerelease.length === 0) return 0;
|
|
46
|
+
if (left.prerelease.length === 0) return 1;
|
|
47
|
+
if (right.prerelease.length === 0) return -1;
|
|
48
|
+
const length = Math.max(left.prerelease.length, right.prerelease.length);
|
|
49
|
+
for (let index = 0; index < length; index += 1) {
|
|
50
|
+
const a = left.prerelease[index];
|
|
51
|
+
const b = right.prerelease[index];
|
|
52
|
+
if (a === undefined) return -1;
|
|
53
|
+
if (b === undefined) return 1;
|
|
54
|
+
const compared = compareIdentifier(a, b);
|
|
55
|
+
if (compared !== 0) return compared;
|
|
56
|
+
}
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function partialVersion(value) {
|
|
61
|
+
const text = String(value ?? '').trim();
|
|
62
|
+
const match = /^v?(\d+)(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?$/u.exec(text);
|
|
63
|
+
if (match === null) return null;
|
|
64
|
+
const minor = match[2] === undefined || /^[xX*]$/u.test(match[2]) ? null : Number(match[2]);
|
|
65
|
+
const patch = match[3] === undefined || /^[xX*]$/u.test(match[3]) ? null : Number(match[3]);
|
|
66
|
+
return {
|
|
67
|
+
major: Number(match[1]),
|
|
68
|
+
minor,
|
|
69
|
+
patch,
|
|
70
|
+
prerelease: match[4] === undefined ? [] : match[4].split('.'),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function floorVersion(parts) {
|
|
75
|
+
return { major: parts.major, minor: parts.minor ?? 0, patch: parts.patch ?? 0, prerelease: parts.prerelease };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function comparatorMatches(version, operator, parts) {
|
|
79
|
+
const base = floorVersion(parts);
|
|
80
|
+
const compared = compareSemver(version, base);
|
|
81
|
+
if (operator === '>=') return compared >= 0;
|
|
82
|
+
if (operator === '>') return compared > 0;
|
|
83
|
+
if (operator === '<=') return compared <= 0;
|
|
84
|
+
if (operator === '<') return compared < 0;
|
|
85
|
+
return compared === 0;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function caretRange(parts) {
|
|
89
|
+
const low = floorVersion(parts);
|
|
90
|
+
let high;
|
|
91
|
+
if (parts.minor === null) high = { major: parts.major + 1, minor: 0, patch: 0, prerelease: [] };
|
|
92
|
+
else if (parts.major > 0) high = { major: parts.major + 1, minor: 0, patch: 0, prerelease: [] };
|
|
93
|
+
else if (parts.minor > 0) high = { major: 0, minor: parts.minor + 1, patch: 0, prerelease: [] };
|
|
94
|
+
else if (parts.patch === null) high = { major: 0, minor: 1, patch: 0, prerelease: [] };
|
|
95
|
+
else high = { major: 0, minor: 0, patch: parts.patch + 1, prerelease: [] };
|
|
96
|
+
return { low, high };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function tildeRange(parts) {
|
|
100
|
+
const low = floorVersion(parts);
|
|
101
|
+
const high = parts.minor === null
|
|
102
|
+
? { major: parts.major + 1, minor: 0, patch: 0, prerelease: [] }
|
|
103
|
+
: { major: parts.major, minor: parts.minor + 1, patch: 0, prerelease: [] };
|
|
104
|
+
return { low, high };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function matchesComparator(version, raw) {
|
|
108
|
+
const token = raw.trim();
|
|
109
|
+
if (token === '' || token === '*' || /^[xX]$/u.test(token)) return true;
|
|
110
|
+
const operatorMatch = /^(>=|<=|>|<|=|\^|~)?\s*(.+)$/u.exec(token);
|
|
111
|
+
if (operatorMatch === null) return false;
|
|
112
|
+
const operator = operatorMatch[1] ?? '';
|
|
113
|
+
const parts = partialVersion(operatorMatch[2]);
|
|
114
|
+
if (parts === null) return false;
|
|
115
|
+
if (operator === '^') {
|
|
116
|
+
const range = caretRange(parts);
|
|
117
|
+
return compareSemver(version, range.low) >= 0 && compareSemver(version, range.high) < 0;
|
|
118
|
+
}
|
|
119
|
+
if (operator === '~') {
|
|
120
|
+
const range = tildeRange(parts);
|
|
121
|
+
return compareSemver(version, range.low) >= 0 && compareSemver(version, range.high) < 0;
|
|
122
|
+
}
|
|
123
|
+
if (parts.minor === null || parts.patch === null) {
|
|
124
|
+
const low = floorVersion(parts);
|
|
125
|
+
const high = parts.minor === null
|
|
126
|
+
? { major: parts.major + 1, minor: 0, patch: 0, prerelease: [] }
|
|
127
|
+
: { major: parts.major, minor: parts.minor + 1, patch: 0, prerelease: [] };
|
|
128
|
+
if (operator === '>=') return compareSemver(version, low) >= 0;
|
|
129
|
+
if (operator === '>') return compareSemver(version, high) >= 0;
|
|
130
|
+
if (operator === '<') return compareSemver(version, low) < 0;
|
|
131
|
+
if (operator === '<=') return compareSemver(version, high) < 0;
|
|
132
|
+
return compareSemver(version, low) >= 0 && compareSemver(version, high) < 0;
|
|
133
|
+
}
|
|
134
|
+
return comparatorMatches(version, operator === '' ? '=' : operator, parts);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* A dependency-free subset of semver that covers every range shape used by DSH
|
|
139
|
+
* plugins: exact, comparators, `||`, caret, tilde, wildcards and hyphen ranges.
|
|
140
|
+
* Prereleases participate, matching DSH's `includePrerelease: true`.
|
|
141
|
+
*/
|
|
142
|
+
export function satisfiesRange(version, range) {
|
|
143
|
+
const parsedVersion = parseSemver(version);
|
|
144
|
+
if (parsedVersion === null || typeof range !== 'string' || range.trim() === '') return false;
|
|
145
|
+
for (const alternative of range.split('||')) {
|
|
146
|
+
const text = alternative.trim().replace(/(>=|<=|>|<|=|\^|~)\s+/gu, '$1');
|
|
147
|
+
if (text === '') continue;
|
|
148
|
+
const hyphen = /^(\S+)\s+-\s+(\S+)$/u.exec(text);
|
|
149
|
+
if (hyphen !== null) {
|
|
150
|
+
const low = partialVersion(hyphen[1]);
|
|
151
|
+
const high = partialVersion(hyphen[2]);
|
|
152
|
+
if (low === null || high === null) continue;
|
|
153
|
+
const lowVersion = floorVersion(low);
|
|
154
|
+
const highVersion = floorVersion(high);
|
|
155
|
+
if (compareSemver(parsedVersion, lowVersion) >= 0 && compareSemver(parsedVersion, highVersion) <= 0) return true;
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const comparators = text.split(/\s+/u).filter((token) => token !== '');
|
|
159
|
+
if (comparators.every((token) => matchesComparator(parsedVersion, token))) return true;
|
|
160
|
+
}
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Return the DSH requirements a manifest does not satisfy. An own
|
|
166
|
+
* `engines.dsh` decides alone, matching DSH's app-boot behavior.
|
|
167
|
+
*/
|
|
168
|
+
export function unmetDshRequirements(manifest, runtimeVersion) {
|
|
169
|
+
if (manifest === null || typeof manifest !== 'object') return {};
|
|
170
|
+
const engines = manifest.engines;
|
|
171
|
+
if (engines !== null && typeof engines === 'object' && Object.hasOwn(engines, 'dsh')) {
|
|
172
|
+
const range = engines.dsh;
|
|
173
|
+
if (typeof range !== 'string') return { 'engines.dsh': String(range) };
|
|
174
|
+
return satisfiesRange(runtimeVersion, range) ? {} : { 'engines.dsh': range };
|
|
175
|
+
}
|
|
176
|
+
const peers = manifest.peerDependencies;
|
|
177
|
+
if (peers === null || typeof peers !== 'object') return {};
|
|
178
|
+
const unmet = {};
|
|
179
|
+
for (const [name, range] of Object.entries(peers)) {
|
|
180
|
+
if (name !== '@deepseek-ai/dsh' && !name.startsWith('@deepseek-ai/dsh-')) continue;
|
|
181
|
+
if (typeof range !== 'string') {
|
|
182
|
+
unmet[name] = String(range);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const effective = ['workspace:^', 'workspace:~', 'workspace:*'].includes(range) ? runtimeVersion : range;
|
|
186
|
+
if (!satisfiesRange(runtimeVersion, effective)) unmet[name] = range;
|
|
187
|
+
}
|
|
188
|
+
return unmet;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Read `package/package.json` from an npm `.tgz` without spawning tar. */
|
|
192
|
+
export function readPackageManifestFromTarball(file) {
|
|
193
|
+
const archive = zlib.gunzipSync(fs.readFileSync(file));
|
|
194
|
+
for (const entry of readTar(archive)) {
|
|
195
|
+
if (entry.name === 'package/package.json' || entry.name.endsWith('/package/package.json')) {
|
|
196
|
+
return JSON.parse(entry.data.toString('utf8'));
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
throw new Error('the saved package has no package/package.json');
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function runtimeVersionFromJson(file) {
|
|
203
|
+
try {
|
|
204
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
205
|
+
const value = typeof raw?.desktopVersion === 'string' ? raw.desktopVersion : raw?.version;
|
|
206
|
+
return parseSemver(value) === null ? null : value;
|
|
207
|
+
} catch {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Resolve the running DSH version. The desktop runtime writes it to
|
|
214
|
+
* `resources/runtime/primary-runtime/runtime.json`; tests and embedders can
|
|
215
|
+
* pass an explicit version. Returns `null` when no trustworthy version exists.
|
|
216
|
+
*/
|
|
217
|
+
export function resolveDshRuntimeVersion(input = {}) {
|
|
218
|
+
const explicit = input.version ?? process.env.DSH_VERSION ?? process.env.DSH_CLIENT_VERSION;
|
|
219
|
+
if (parseSemver(explicit) !== null) return String(explicit).trim();
|
|
220
|
+
const execPath = input.execPath ?? process.execPath;
|
|
221
|
+
const dir = path.dirname(execPath);
|
|
222
|
+
const candidates = [
|
|
223
|
+
path.join(dir, 'resources', 'runtime', 'primary-runtime', 'runtime.json'),
|
|
224
|
+
path.join(dir, 'runtime', 'primary-runtime', 'runtime.json'),
|
|
225
|
+
// The DSH host may run the plugin under the bundled Node binary:
|
|
226
|
+
// resources/runtime/primary-runtime/node/node.exe -> ../runtime.json
|
|
227
|
+
path.join(dir, '..', 'runtime.json'),
|
|
228
|
+
path.join(dir, '..', '..', 'runtime', 'primary-runtime', 'runtime.json'),
|
|
229
|
+
];
|
|
230
|
+
if (typeof input.profileDir === 'string' && input.profileDir !== '') {
|
|
231
|
+
candidates.push(
|
|
232
|
+
path.join(input.profileDir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json'),
|
|
233
|
+
path.join(input.profileDir, 'node_modules', '@deepseek-ai', 'dsh-app-boot', 'package.json'),
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
for (const file of candidates) {
|
|
237
|
+
const version = runtimeVersionFromJson(file);
|
|
238
|
+
if (version !== null) return version;
|
|
239
|
+
}
|
|
240
|
+
return null;
|
|
241
|
+
}
|
package/src/plugin.mjs
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
*
|
|
8
8
|
* GET /api/twinsearth/timemachine/health
|
|
9
9
|
* GET /api/twinsearth/timemachine/status
|
|
10
|
+
* GET /api/twinsearth/timemachine/stats
|
|
10
11
|
* GET /api/twinsearth/timemachine/estimate
|
|
11
12
|
* POST /api/twinsearth/timemachine/create
|
|
12
13
|
* POST /api/twinsearth/timemachine/plan
|
|
@@ -32,6 +33,8 @@ import {
|
|
|
32
33
|
saveSettings,
|
|
33
34
|
startAutoScheduler,
|
|
34
35
|
} from './service.mjs';
|
|
36
|
+
import { startTelemetry } from './telemetry.mjs';
|
|
37
|
+
import { PLUGIN_VERSION } from './version.mjs';
|
|
35
38
|
|
|
36
39
|
export const name = 'timemachine';
|
|
37
40
|
export const inject = [];
|
|
@@ -40,6 +43,7 @@ export const ROUTE_PREFIX = '/api/twinsearth/timemachine';
|
|
|
40
43
|
export const ROUTE_PATHS = Object.freeze({
|
|
41
44
|
health: `${ROUTE_PREFIX}/health`,
|
|
42
45
|
status: `${ROUTE_PREFIX}/status`,
|
|
46
|
+
stats: `${ROUTE_PREFIX}/stats`,
|
|
43
47
|
estimate: `${ROUTE_PREFIX}/estimate`,
|
|
44
48
|
create: `${ROUTE_PREFIX}/create`,
|
|
45
49
|
plan: `${ROUTE_PREFIX}/plan`,
|
|
@@ -111,8 +115,16 @@ export function registerRoutes(ctx, rawConfig, deps = {}) {
|
|
|
111
115
|
});
|
|
112
116
|
};
|
|
113
117
|
|
|
114
|
-
register('GET', ROUTE_PATHS.health, async () => json({ ok: true, plugin: name, mounted: true }));
|
|
118
|
+
register('GET', ROUTE_PATHS.health, async () => json({ ok: true, plugin: name, version: PLUGIN_VERSION, mounted: true }));
|
|
115
119
|
register('GET', ROUTE_PATHS.status, async () => json(getStatus(rawConfig, deps)));
|
|
120
|
+
register('GET', ROUTE_PATHS.stats, async () => json(await (deps.telemetry?.getStats?.() ?? {
|
|
121
|
+
ok: false,
|
|
122
|
+
version: PLUGIN_VERSION,
|
|
123
|
+
online: null,
|
|
124
|
+
sevenDay: null,
|
|
125
|
+
installs: null,
|
|
126
|
+
error: 'telemetry unavailable',
|
|
127
|
+
})));
|
|
116
128
|
register('GET', ROUTE_PATHS.estimate, async () => json({ ok: true, ...getEstimate(rawConfig, deps) }));
|
|
117
129
|
register('POST', ROUTE_PATHS.create, async (request) => guarded('create', async () => {
|
|
118
130
|
const body = await readBody(request);
|
|
@@ -186,6 +198,14 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
186
198
|
}
|
|
187
199
|
},
|
|
188
200
|
};
|
|
201
|
+
if (runtimeDeps.telemetry === undefined) {
|
|
202
|
+
try {
|
|
203
|
+
runtimeDeps.telemetry = startTelemetry({ logger: ctx.logger });
|
|
204
|
+
} catch (error) {
|
|
205
|
+
runtimeDeps.telemetry = null;
|
|
206
|
+
ctx.logger?.warn?.(`${name}: telemetry did not start: ${error instanceof Error ? error.message : String(error)}`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
189
209
|
const routes = registerRoutes(ctx, config, runtimeDeps);
|
|
190
210
|
ctx.logger?.info?.(`${name}: routes ${routes.mounted ? 'mounted' : `not mounted (${routes.reason})`}`);
|
|
191
211
|
const stopScheduler = startAutoScheduler({
|
|
@@ -200,10 +220,12 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
200
220
|
ctx.effect?.(() => () => {
|
|
201
221
|
disposed = true;
|
|
202
222
|
stopScheduler();
|
|
223
|
+
runtimeDeps.telemetry?.stop?.();
|
|
203
224
|
});
|
|
204
225
|
const dispose = () => {
|
|
205
226
|
disposed = true;
|
|
206
227
|
stopScheduler();
|
|
228
|
+
runtimeDeps.telemetry?.stop?.();
|
|
207
229
|
};
|
|
208
230
|
for (const [key, value] of Object.entries({
|
|
209
231
|
ok: true,
|
package/src/plugins.mjs
CHANGED
|
@@ -10,6 +10,8 @@ import fs from 'node:fs';
|
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import { spawn } from 'node:child_process';
|
|
12
12
|
|
|
13
|
+
import { readPackageManifestFromTarball, resolveDshRuntimeVersion, unmetDshRequirements } from './plugin-compat.mjs';
|
|
14
|
+
|
|
13
15
|
/** The package doing the restore must never reinstall itself while running. */
|
|
14
16
|
export const SELF_PLUGIN = '@twinsearth/timemachine-dsh-plugin';
|
|
15
17
|
|
|
@@ -221,9 +223,15 @@ export function resolvePnpm(execPath = process.execPath) {
|
|
|
221
223
|
/**
|
|
222
224
|
* Install third-party plugins. pnpm is preferred; npm is a fallback that uses
|
|
223
225
|
* `--no-save` so the archived package.json is not rewritten by an installer.
|
|
226
|
+
*
|
|
227
|
+
* One package failing must not abort the whole restore: every package is
|
|
228
|
+
* attempted, failures are collected for the yellow UI warning, and the caller
|
|
229
|
+
* continues with the file/config restore.
|
|
230
|
+
*
|
|
224
231
|
* @param {{
|
|
225
232
|
* profileDir: string, plugins: Array<{name: string, version?: string|null}>,
|
|
226
|
-
* packages?: Record<string,string>,
|
|
233
|
+
* packages?: Record<string,string>, dshVersion?: string|null, manifests?: Record<string, object>,
|
|
234
|
+
* checkCompatibility?: boolean, runner?: typeof runProcess,
|
|
227
235
|
* timeout_ms?: number, pnpmFile?: string|null, onProgress?: (event: object) => void,
|
|
228
236
|
* }} input
|
|
229
237
|
*/
|
|
@@ -233,13 +241,15 @@ export async function reinstallPlugins(input) {
|
|
|
233
241
|
const installed = [];
|
|
234
242
|
const failed = [];
|
|
235
243
|
const skipped = [];
|
|
244
|
+
const warnings = [];
|
|
236
245
|
const plugins = Array.isArray(input.plugins) ? input.plugins : [];
|
|
237
|
-
if (plugins.length === 0) return { ok: true, manager: 'none', installed, failed, skipped };
|
|
246
|
+
if (plugins.length === 0) return { ok: true, complete: true, manager: 'none', runtime_version: null, installed, failed, skipped, warnings };
|
|
238
247
|
if (!fs.existsSync(input.profileDir)) {
|
|
239
|
-
return { ok: false, reason_code: 'RESTORE_PROFILE_NOT_FOUND', detail: input.profileDir, manager: 'none', installed, failed, skipped };
|
|
248
|
+
return { ok: false, reason_code: 'RESTORE_PROFILE_NOT_FOUND', detail: input.profileDir, manager: 'none', installed, failed, skipped, warnings };
|
|
240
249
|
}
|
|
241
250
|
const pnpmFile = input.pnpmFile === undefined ? resolvePnpm() : input.pnpmFile;
|
|
242
251
|
const manager = pnpmFile !== null && pnpmFile !== undefined ? 'pnpm' : 'npm';
|
|
252
|
+
const runtimeVersion = input.dshVersion ?? resolveDshRuntimeVersion({ profileDir: input.profileDir });
|
|
243
253
|
for (const plugin of plugins) {
|
|
244
254
|
const name = plugin?.name;
|
|
245
255
|
if (!isSafePackageName(name)) {
|
|
@@ -252,16 +262,61 @@ export async function reinstallPlugins(input) {
|
|
|
252
262
|
}
|
|
253
263
|
const tarball = packages[name];
|
|
254
264
|
const spec = typeof tarball === 'string' && tarball !== '' ? `file:${tarball}` : `${name}@latest`;
|
|
265
|
+
|
|
266
|
+
if (input.checkCompatibility !== false) {
|
|
267
|
+
let manifest = input.manifests?.[name];
|
|
268
|
+
if (manifest === undefined && typeof tarball === 'string' && tarball !== '') {
|
|
269
|
+
try {
|
|
270
|
+
manifest = readPackageManifestFromTarball(tarball);
|
|
271
|
+
} catch (error) {
|
|
272
|
+
warnings.push(`${name}:无法读取离线安装包的版本要求(${error instanceof Error ? error.message : String(error)}),继续安装。`);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (manifest === undefined && (typeof tarball !== 'string' || tarball === '')) {
|
|
276
|
+
const viewed = await readRegistryManifest(runner, input.profileDir, name, input.timeout_ms);
|
|
277
|
+
if (viewed.ok) manifest = viewed.manifest;
|
|
278
|
+
else warnings.push(`${name}:无法读取 npm 版本要求(${viewed.detail}),继续安装。`);
|
|
279
|
+
}
|
|
280
|
+
if (manifest !== undefined && manifest !== null) {
|
|
281
|
+
if (runtimeVersion === null) {
|
|
282
|
+
warnings.push(`${name}:无法确认当前 DSH 客户端版本,未做兼容性检查。`);
|
|
283
|
+
} else {
|
|
284
|
+
const unmet = unmetDshRequirements(manifest, runtimeVersion);
|
|
285
|
+
if (Object.keys(unmet).length > 0) {
|
|
286
|
+
const requirement = Object.entries(unmet).map(([field, range]) => `${field} ${range}`).join('、');
|
|
287
|
+
const detail = `要求 ${requirement},当前 DSH ${runtimeVersion}`;
|
|
288
|
+
skipped.push({
|
|
289
|
+
name,
|
|
290
|
+
spec,
|
|
291
|
+
reason_code: 'PLUGIN_DSH_INCOMPATIBLE',
|
|
292
|
+
reason: detail,
|
|
293
|
+
manifest_version: typeof manifest.version === 'string' ? manifest.version : null,
|
|
294
|
+
requirements: unmet,
|
|
295
|
+
runtime_version: runtimeVersion,
|
|
296
|
+
});
|
|
297
|
+
warnings.push(`${name}:与当前 DSH 不兼容(${detail}),已跳过安装。`);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
255
304
|
const args = manager === 'pnpm'
|
|
256
305
|
? ['--dir', input.profileDir, 'add', spec, '--reporter=append-only', '--prefer-online']
|
|
257
306
|
: ['install', '--no-save', '--package-lock=false', '--omit=dev', '--prefer-online', spec];
|
|
258
307
|
const command = manager === 'pnpm' ? process.execPath : npmCommand();
|
|
259
308
|
const argv = manager === 'pnpm' ? [pnpmFile, ...args] : args;
|
|
260
309
|
input.onProgress?.({ phase: 'install', name, spec, manager });
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
310
|
+
let result;
|
|
311
|
+
try {
|
|
312
|
+
result = await runner(command, argv, {
|
|
313
|
+
cwd: input.profileDir,
|
|
314
|
+
timeout_ms: input.timeout_ms ?? 240_000,
|
|
315
|
+
});
|
|
316
|
+
} catch (error) {
|
|
317
|
+
result = { code: null, stdout: '', stderr: '', error: error instanceof Error ? error.message : String(error) };
|
|
318
|
+
}
|
|
319
|
+
result = result ?? { code: null, stdout: '', stderr: '' };
|
|
265
320
|
const row = {
|
|
266
321
|
name,
|
|
267
322
|
spec,
|
|
@@ -275,15 +330,7 @@ export async function reinstallPlugins(input) {
|
|
|
275
330
|
installed.push(row);
|
|
276
331
|
} else {
|
|
277
332
|
failed.push({ ...row, error: result.error ?? null });
|
|
278
|
-
|
|
279
|
-
ok: false,
|
|
280
|
-
reason_code: 'RESTORE_PLUGIN_INSTALL_FAILED',
|
|
281
|
-
detail: `${name}: ${manager} exited ${String(result.code)}${result.timed_out === true ? ' (timeout)' : ''}`,
|
|
282
|
-
manager,
|
|
283
|
-
installed,
|
|
284
|
-
failed,
|
|
285
|
-
skipped,
|
|
286
|
-
};
|
|
333
|
+
warnings.push(`${name}:安装失败,请自行手动安装!`);
|
|
287
334
|
}
|
|
288
335
|
}
|
|
289
336
|
if (manager === 'npm') {
|
|
@@ -303,7 +350,30 @@ export async function reinstallPlugins(input) {
|
|
|
303
350
|
fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
|
|
304
351
|
} catch { /* a package.json write failure is reported by the next status, not here */ }
|
|
305
352
|
}
|
|
306
|
-
return { ok: true, manager, installed, failed, skipped };
|
|
353
|
+
return { ok: true, complete: failed.length === 0, manager, runtime_version: runtimeVersion, installed, failed, skipped, warnings };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async function readRegistryManifest(runner, cwd, name, timeoutMs) {
|
|
357
|
+
let result;
|
|
358
|
+
try {
|
|
359
|
+
result = await runner(npmCommand(), ['view', `${name}@latest`, 'version', 'engines', 'peerDependencies', '--json'], {
|
|
360
|
+
cwd,
|
|
361
|
+
timeout_ms: Math.min(timeoutMs ?? 60_000, 60_000),
|
|
362
|
+
});
|
|
363
|
+
} catch (error) {
|
|
364
|
+
return { ok: false, detail: `npm view failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
365
|
+
}
|
|
366
|
+
if (result?.code !== 0) {
|
|
367
|
+
return { ok: false, detail: `npm view exited ${String(result?.code)}${result?.timed_out === true ? ' (timeout)' : ''}` };
|
|
368
|
+
}
|
|
369
|
+
try {
|
|
370
|
+
const parsed = JSON.parse(String(result.stdout ?? '').trim());
|
|
371
|
+
const manifest = Array.isArray(parsed) ? parsed[0] : parsed;
|
|
372
|
+
if (manifest === null || typeof manifest !== 'object') return { ok: false, detail: 'npm view returned no manifest' };
|
|
373
|
+
return { ok: true, manifest };
|
|
374
|
+
} catch {
|
|
375
|
+
return { ok: false, detail: 'npm view returned invalid JSON' };
|
|
376
|
+
}
|
|
307
377
|
}
|
|
308
378
|
|
|
309
379
|
/**
|
package/src/point.mjs
CHANGED
|
@@ -29,7 +29,7 @@ import { scanExclusions, scanHome } from './scan.mjs';
|
|
|
29
29
|
import { packPluginTarballs, readProfilePlugins, SELF_PLUGIN } from './plugins.mjs';
|
|
30
30
|
import { buildPointTree } from './tree.mjs';
|
|
31
31
|
import { atomicWriteFile, ensureDir, formatBytes, isSafeArchiveName, readJson, sha256, stamp } from './util/fs.mjs';
|
|
32
|
-
import { encodeSegment, profileDir, projectKey, resolveDshHome } from './util/paths.mjs';
|
|
32
|
+
import { encodeSegment, missingDriveForPath, profileDir, projectKey, resolveDshHome } from './util/paths.mjs';
|
|
33
33
|
|
|
34
34
|
export const POINT_SCHEMA = 'twinsearth-timemachine-point/1';
|
|
35
35
|
export const MANIFEST_SCHEMA = 'twinsearth-timemachine-manifest/1';
|
|
@@ -633,6 +633,21 @@ export function importRestorePoint(input) {
|
|
|
633
633
|
if (source.startsWith(`${path.resolve(root)}${path.sep}`)) {
|
|
634
634
|
return { ok: false, reason_code: CODES.IMPORT_FAILED, detail: 'the source file is already inside the restore-point root' };
|
|
635
635
|
}
|
|
636
|
+
const pathIssues = [];
|
|
637
|
+
const seenDrives = new Set();
|
|
638
|
+
for (const workspace of row.point?.workspaces ?? []) {
|
|
639
|
+
const workspacePath = typeof workspace?.path === 'string' ? workspace.path : '';
|
|
640
|
+
const drive = missingDriveForPath(workspacePath);
|
|
641
|
+
if (drive === null || seenDrives.has(`${drive}|${workspacePath}`)) continue;
|
|
642
|
+
seenDrives.add(`${drive}|${workspacePath}`);
|
|
643
|
+
pathIssues.push({
|
|
644
|
+
code: 'TIMEMACHINE_PATH_DRIVE_MISSING',
|
|
645
|
+
drive,
|
|
646
|
+
source_path: workspacePath,
|
|
647
|
+
target_path: workspacePath,
|
|
648
|
+
message: `本机没有 ${drive} 盘,还原点中的工作区“${workspace.title ?? workspacePath}”无法直接落到 ${workspacePath};请修改工作区文件夹。`,
|
|
649
|
+
});
|
|
650
|
+
}
|
|
636
651
|
const writable = ensureWritableRoot(root);
|
|
637
652
|
if (writable !== null) return { ok: false, reason_code: CODES.ROOT_UNWRITABLE, detail: writable };
|
|
638
653
|
const folder = categoryDir(root, 'imported');
|
|
@@ -648,7 +663,16 @@ export function importRestorePoint(input) {
|
|
|
648
663
|
} catch (error) {
|
|
649
664
|
return { ok: false, reason_code: CODES.IMPORT_FAILED, detail: error instanceof Error ? error.message : String(error) };
|
|
650
665
|
}
|
|
651
|
-
return {
|
|
666
|
+
return {
|
|
667
|
+
ok: true,
|
|
668
|
+
file: target,
|
|
669
|
+
source,
|
|
670
|
+
point: row.point,
|
|
671
|
+
bytes: row.bytes,
|
|
672
|
+
sha256: row.sha256,
|
|
673
|
+
path_issues: pathIssues,
|
|
674
|
+
warnings: pathIssues.map((issue) => issue.message),
|
|
675
|
+
};
|
|
652
676
|
}
|
|
653
677
|
|
|
654
678
|
/** Estimate what a point will contain, without writing. */
|
package/src/restore.mjs
CHANGED
|
@@ -18,12 +18,13 @@ import { inspectSessionBuffer, isV4Header, remapSessionCwd } from './session-log
|
|
|
18
18
|
import { normalizeRegistry } from './scan.mjs';
|
|
19
19
|
import { reinstallPlugins, SELF_PLUGIN } from './plugins.mjs';
|
|
20
20
|
import { atomicWriteFile, atomicWriteJson, copyFileDurable, ensureDir, isInside, readJson, safeSegment, sha256, stamp } from './util/fs.mjs';
|
|
21
|
-
import { encodeSegment, projectKey, profileDir, resolveDshHome, sessionDir } from './util/paths.mjs';
|
|
21
|
+
import { encodeSegment, missingDriveForPath, projectKey, profileDir, resolveDshHome, sessionDir } from './util/paths.mjs';
|
|
22
22
|
|
|
23
23
|
export const RESTORE_CODES = Object.freeze({
|
|
24
24
|
SESSION_INVALID: 'TIMEMACHINE_SESSION_INVALID',
|
|
25
25
|
SESSION_MISSING: 'TIMEMACHINE_SESSION_MISSING',
|
|
26
26
|
PATH_INVALID: 'TIMEMACHINE_PATH_INVALID',
|
|
27
|
+
PATH_DRIVE_MISSING: 'TIMEMACHINE_PATH_DRIVE_MISSING',
|
|
27
28
|
VERIFY_FAILED: 'TIMEMACHINE_VERIFY_FAILED',
|
|
28
29
|
APPLY_FAILED: 'TIMEMACHINE_APPLY_FAILED',
|
|
29
30
|
PLUGIN_INSTALL_FAILED: 'TIMEMACHINE_PLUGIN_INSTALL_FAILED',
|
|
@@ -104,6 +105,7 @@ export function planRestore(input) {
|
|
|
104
105
|
const targetDocument = registryDocument(targetRegistryRaw);
|
|
105
106
|
|
|
106
107
|
const warnings = [];
|
|
108
|
+
const pathIssues = [];
|
|
107
109
|
if (point.source_platform !== undefined && point.source_platform !== process.platform) {
|
|
108
110
|
warnings.push(`还原点来自 ${point.source_platform},本机是 ${process.platform};工作区路径必须重新映射。`);
|
|
109
111
|
}
|
|
@@ -204,6 +206,18 @@ export function planRestore(input) {
|
|
|
204
206
|
const existing = targetDocument.tables.workspaces[targetId];
|
|
205
207
|
const targetPathExists = fs.existsSync(workspace.target_path);
|
|
206
208
|
if (!targetPathExists) warnings.push(`工作区目录不存在,将按映射路径创建:${workspace.target_path}`);
|
|
209
|
+
const missingDrive = missingDriveForPath(workspace.target_path);
|
|
210
|
+
if (missingDrive !== null) {
|
|
211
|
+
const message = `本机没有 ${missingDrive} 盘,无法还原工作区“${workspace.source_title}”到 ${workspace.target_path};请修改工作区文件夹。`;
|
|
212
|
+
pathIssues.push({
|
|
213
|
+
code: RESTORE_CODES.PATH_DRIVE_MISSING,
|
|
214
|
+
drive: missingDrive,
|
|
215
|
+
source_path: workspace.source_path,
|
|
216
|
+
target_path: workspace.target_path,
|
|
217
|
+
message,
|
|
218
|
+
});
|
|
219
|
+
warnings.push(message);
|
|
220
|
+
}
|
|
207
221
|
workspacePlan.push({
|
|
208
222
|
source_id: workspace.source_id,
|
|
209
223
|
source_path: workspace.source_path,
|
|
@@ -319,6 +333,7 @@ export function planRestore(input) {
|
|
|
319
333
|
added_sessions: merged.added_sessions,
|
|
320
334
|
},
|
|
321
335
|
workspaces: workspacePlan,
|
|
336
|
+
path_issues: pathIssues,
|
|
322
337
|
plugins,
|
|
323
338
|
plugin_packages: pluginPackages,
|
|
324
339
|
will: {
|
|
@@ -376,6 +391,14 @@ function backupExisting(target, rel, backupDir) {
|
|
|
376
391
|
*/
|
|
377
392
|
export function applyRestore(plan, options = {}) {
|
|
378
393
|
if (!plan?.ok) return plan;
|
|
394
|
+
if (Array.isArray(plan.path_issues) && plan.path_issues.length > 0) {
|
|
395
|
+
return {
|
|
396
|
+
ok: false,
|
|
397
|
+
reason_code: RESTORE_CODES.PATH_DRIVE_MISSING,
|
|
398
|
+
detail: plan.path_issues.map((row) => row.message).join(';'),
|
|
399
|
+
path_issues: plan.path_issues,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
379
402
|
// plan carries absolute targets; resolve the live home from the registry file.
|
|
380
403
|
const home = path.dirname(path.dirname(plan.registry.target_file));
|
|
381
404
|
const backupDir = options.backupDir ?? backupDirFor(home);
|
|
@@ -659,6 +682,16 @@ export async function registerRestoredWorkspaces(workspaceRegistry, plan) {
|
|
|
659
682
|
export async function restorePoint(input) {
|
|
660
683
|
const plan = planRestore(input);
|
|
661
684
|
if (!plan.ok) return plan;
|
|
685
|
+
if (Array.isArray(plan.path_issues) && plan.path_issues.length > 0) {
|
|
686
|
+
return {
|
|
687
|
+
ok: false,
|
|
688
|
+
reason_code: RESTORE_CODES.PATH_DRIVE_MISSING,
|
|
689
|
+
detail: plan.path_issues.map((row) => row.message).join(';'),
|
|
690
|
+
stage: 'preflight',
|
|
691
|
+
path_issues: plan.path_issues,
|
|
692
|
+
plan_ready: true,
|
|
693
|
+
};
|
|
694
|
+
}
|
|
662
695
|
const dshHome = dshHomeForPlan(plan);
|
|
663
696
|
const profile = typeof input.profile === 'string' && input.profile !== '' ? input.profile : plan.point.profile;
|
|
664
697
|
const profilePath = profileDir(dshHome, profile);
|
|
@@ -688,6 +721,9 @@ export async function restorePoint(input) {
|
|
|
688
721
|
packages,
|
|
689
722
|
runner: input.runner,
|
|
690
723
|
pnpmFile: input.pnpmFile,
|
|
724
|
+
dshVersion: input.dshVersion,
|
|
725
|
+
manifests: input.manifests,
|
|
726
|
+
checkCompatibility: input.checkCompatibility,
|
|
691
727
|
onProgress: input.onProgress,
|
|
692
728
|
});
|
|
693
729
|
} catch (error) {
|
|
@@ -747,7 +783,7 @@ export async function restorePoint(input) {
|
|
|
747
783
|
backupDir,
|
|
748
784
|
skipRegistry: liveRegistry !== null,
|
|
749
785
|
});
|
|
750
|
-
if (!applied.ok) return { ...applied, stage: 'file-restore', plugins: install };
|
|
786
|
+
if (!applied.ok) return { ...applied, stage: 'file-restore', plugins: install, plugin_warnings: Array.isArray(install?.warnings) ? install.warnings : [] };
|
|
751
787
|
|
|
752
788
|
let live = null;
|
|
753
789
|
if (liveRegistry !== null) {
|
|
@@ -759,6 +795,7 @@ export async function restorePoint(input) {
|
|
|
759
795
|
point: plan.point,
|
|
760
796
|
stage: 'restored',
|
|
761
797
|
plugins: install,
|
|
798
|
+
plugin_warnings: Array.isArray(install?.warnings) ? install.warnings : [],
|
|
762
799
|
restore: applied,
|
|
763
800
|
workspaces: live?.workspaces ?? applied.workspaces,
|
|
764
801
|
display: live?.display ?? null,
|
package/src/service.mjs
CHANGED
|
@@ -29,6 +29,7 @@ import { planRestore, restorePoint } from './restore.mjs';
|
|
|
29
29
|
import { normalizeRegistry } from './scan.mjs';
|
|
30
30
|
import { atomicWriteJson, ensureDir, readJson } from './util/fs.mjs';
|
|
31
31
|
import { profileDir, resolveDshHome } from './util/paths.mjs';
|
|
32
|
+
import { PLUGIN_VERSION } from './version.mjs';
|
|
32
33
|
|
|
33
34
|
export const DEFAULT_SETTINGS = Object.freeze({
|
|
34
35
|
root: '',
|
|
@@ -198,6 +199,7 @@ export function getStatus(rawConfig, options = {}) {
|
|
|
198
199
|
const registry = normalizeRegistry(readJson(path.join(dshHome, 'storages', 'workspace.json'), null));
|
|
199
200
|
return {
|
|
200
201
|
ok: true,
|
|
202
|
+
version: PLUGIN_VERSION,
|
|
201
203
|
platform: process.platform,
|
|
202
204
|
platform_label: process.platform === 'win32' ? 'Windows' : process.platform === 'darwin' ? 'macOS' : 'Linux',
|
|
203
205
|
dsh_home: dshHome,
|