dshmarket 1.2.2 → 1.2.3

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/lib/http.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Minimal HTTP helpers shared by every market route: JSON serialization,
3
+ * same-origin enforcement for mutating endpoints, and a size-capped JSON
4
+ * body reader.
5
+ */
6
+ /** Write a JSON payload with no-store caching. */
7
+ export function sendJson(response, status, payload) {
8
+ response.writeHead(status, {
9
+ 'cache-control': 'no-store',
10
+ 'content-type': 'application/json; charset=utf-8',
11
+ });
12
+ response.end(JSON.stringify(payload));
13
+ }
14
+ /** True when the request's Origin matches its Host — required on every POST route. */
15
+ export function sameOrigin(request) {
16
+ const origin = request.headers.origin;
17
+ const host = request.headers.host;
18
+ if (origin === undefined || host === undefined)
19
+ return false;
20
+ try {
21
+ return new URL(origin).host === host;
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ /** Read and parse a JSON request body, rejecting anything over 4 KiB. */
28
+ export async function readJsonBody(request) {
29
+ const chunks = [];
30
+ let size = 0;
31
+ for await (const chunk of request) {
32
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
33
+ size += buffer.length;
34
+ if (size > 4096)
35
+ throw new Error('request body too large');
36
+ chunks.push(buffer);
37
+ }
38
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
39
+ }
package/lib/install.js ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Install orchestration: collection-repo retargeting, post-install
3
+ * validation that keeps broken pieces from bricking the next boot, and
4
+ * update staleness detection. Every function takes the plugin runner as a
5
+ * parameter so tests can substitute a recording fake.
6
+ */
7
+ import { existsSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { classifyPnpmFailure } from './pnpm-compat.js';
10
+ import { entryArtifactExists, hasDshManifest, pluginSubdirs, profileDir, readInstalled } from './profile.js';
11
+ import { logEvent } from './log.js';
12
+ /**
13
+ * Run one plugin command with automatic recovery from the pnpm-major drift
14
+ * failure (#20 bug 2): when the modules directory was built by a different
15
+ * pnpm major, pnpm's documented remedy is one `install` to recreate it —
16
+ * do that silently and retry the original command once. Any recognized
17
+ * failure that survives gets its bilingual explanation appended to stderr
18
+ * so the UI shows an actionable message instead of a wall of text (#20 bug 3).
19
+ */
20
+ export async function withHoistRecovery(run, profile, pluginArgs) {
21
+ let result = await run(profile, pluginArgs);
22
+ const ok = (r) => r.exitCode === 0 && !r.timedOut;
23
+ if (!ok(result) && classifyPnpmFailure(`${result.stderr}\n${result.stdout}`)?.code === 'hoist-pattern-diff') {
24
+ logEvent('warn', 'install', `modules dir was built by a different pnpm major — rebuilding (pnpm install) and retrying once`);
25
+ // --no-frozen-lockfile: the market runs pnpm with CI=true (TTY hangs),
26
+ // where a lockfile written by the old major would otherwise be refused.
27
+ const rebuild = await run(profile, ['install', '--no-frozen-lockfile']);
28
+ if (ok(rebuild))
29
+ result = await run(profile, pluginArgs);
30
+ }
31
+ if (!ok(result)) {
32
+ const failure = classifyPnpmFailure(`${result.stderr}\n${result.stdout}`);
33
+ if (failure !== null)
34
+ result = { ...result, stderr: `${result.stderr}\n\n${failure.message}` };
35
+ }
36
+ return result;
37
+ }
38
+ /**
39
+ * Some registry entries point at collection repos whose actual plugin lives
40
+ * in a subdirectory — the root has no package.json (or a workspace root with
41
+ * no dsh surface), and pnpm installs the bare fileset with exit 0. Detect
42
+ * that junk install, drop it, and re-add each plugin subdirectory through
43
+ * pnpm's `#path:` selector (#18).
44
+ * @returns overall success (true when nothing needed retargeting).
45
+ */
46
+ export async function retargetCollections(run, profile, before, target) {
47
+ if (!target.startsWith('github:'))
48
+ return true;
49
+ const junk = Object.keys(readInstalled(profile)).filter((name) => {
50
+ if (before.has(name))
51
+ return false;
52
+ const root = join(profileDir(profile), 'node_modules', name);
53
+ if (!existsSync(join(root, 'package.json')))
54
+ return true;
55
+ return !hasDshManifest(root);
56
+ });
57
+ let allOk = true;
58
+ for (const name of junk) {
59
+ const root = join(profileDir(profile), 'node_modules', name);
60
+ const candidates = pluginSubdirs(root);
61
+ logEvent('info', 'install', `${name}: collection repo (root declares no dsh manifest); plugins inside: ${candidates.join(', ') || 'none'}`);
62
+ await run(profile, ['remove', name]);
63
+ if (candidates.length === 0) {
64
+ allOk = false;
65
+ continue;
66
+ }
67
+ for (const sub of candidates) {
68
+ const result = await run(profile, ['add', `${target}#path:/${sub}`]);
69
+ if (result.exitCode !== 0 || result.timedOut) {
70
+ allOk = false;
71
+ logEvent('error', 'install', `${target}#path:/${sub}: exit=${String(result.exitCode)}${result.timedOut ? ' TIMEOUT' : ''} — ${(result.stderr || result.stdout).slice(-220)}`);
72
+ }
73
+ }
74
+ }
75
+ return allOk;
76
+ }
77
+ /**
78
+ * Fake-success guard (#18): validate every package the install added. A
79
+ * piece without a dsh manifest or without its declared entry artifact
80
+ * (source-only checkout, build blocked by pnpm allowBuilds) would brick the
81
+ * next boot, so it is removed on the spot.
82
+ * @returns names kept and names removed as broken.
83
+ */
84
+ export async function validateAddedPlugins(run, profile, before) {
85
+ const addedNow = Object.keys(readInstalled(profile)).filter(n => !before.has(n));
86
+ const keep = [];
87
+ const removedBroken = [];
88
+ for (const n of addedNow) {
89
+ const dir = join(profileDir(profile), 'node_modules', n);
90
+ if (hasDshManifest(dir) && entryArtifactExists(dir)) {
91
+ keep.push(n);
92
+ }
93
+ else {
94
+ removedBroken.push(n);
95
+ await run(profile, ['remove', n]);
96
+ }
97
+ }
98
+ return { keep, removedBroken };
99
+ }
100
+ /**
101
+ * Whether a clean-exit update actually changed nothing — pnpm's
102
+ * minimumReleaseAge silently keeps the old version and exits 0 when the new
103
+ * release is "too young" (#13, #22), so a clean exit alone does not mean the
104
+ * update happened.
105
+ */
106
+ export function isStaleUpdate(check) {
107
+ return check.isGit
108
+ ? check.beforeCommit !== null && check.afterCommit === check.beforeCommit
109
+ : check.beforeVersion !== null && check.afterVersion === check.beforeVersion;
110
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * pnpm compatibility layer — everything the market needs to know about how
3
+ * different pnpm majors behave inside a dsh profile directory, kept pure and
4
+ * separately testable (test/unit + test/integration exercise this module
5
+ * against real pnpm 9/10/11).
6
+ *
7
+ * Verified behavior matrix (2026-08, pnpm 9.15.9 / 10.28.2 / 11.21.0):
8
+ * - workspace root, `add` without -w: pnpm 9 fails ERR_PNPM_ADDING_TO_ROOT;
9
+ * pnpm 10/11 succeed.
10
+ * - `add -w` where NO pnpm-workspace.yaml exists: ALL majors fail with
11
+ * "--workspace-root may only be used inside a workspace".
12
+ * - modules dir built by pnpm 9, then pnpm 10/11 mutate it:
13
+ * ERR_PNPM_PUBLIC_HOIST_PATTERN_DIFF (defaults drifted between majors).
14
+ */
15
+ import { existsSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ /**
18
+ * Decide the argv for a `dsh plugin <add|remove> …` call in the given profile.
19
+ *
20
+ * pnpm 9 refuses to add at a workspace root without -w (#17, #20); every
21
+ * pnpm major refuses -w when the directory is NOT a workspace. So the flag
22
+ * is injected exactly when the profile has a pnpm-workspace.yaml.
23
+ * @param profileDir - resolved profile directory (owns pnpm-workspace.yaml, or not).
24
+ * @param pluginArgs - the raw args, e.g. ['add', 'dshmarket@latest'].
25
+ * @returns args with -w injected when — and only when — the profile is a workspace root.
26
+ */
27
+ export function pluginArgsFor(profileDir, pluginArgs) {
28
+ if (pluginArgs[0] !== 'add' && pluginArgs[0] !== 'remove')
29
+ return pluginArgs;
30
+ if (!existsSync(join(profileDir, 'pnpm-workspace.yaml')))
31
+ return pluginArgs;
32
+ return [pluginArgs[0], '-w', ...pluginArgs.slice(1)];
33
+ }
34
+ /**
35
+ * Map a failed pnpm run's combined output to a known failure mode.
36
+ *
37
+ * dsh's own wrapper line ("dsh: pnpm failed in profile directory …") names no
38
+ * cause, so the market must recognize pnpm's real diagnostics itself (#20).
39
+ * @param output - stdout+stderr of the failed run.
40
+ * @returns the classified failure, or null when unrecognized (raw output is then shown as-is).
41
+ */
42
+ export function classifyPnpmFailure(output) {
43
+ if (output.includes('ERR_PNPM_PUBLIC_HOIST_PATTERN_DIFF')) {
44
+ return {
45
+ code: 'hoist-pattern-diff',
46
+ recoverable: true,
47
+ message: 'profile 的 node_modules 是旧版 pnpm 创建的,与当前 pnpm 的默认配置不兼容,需要重建后重试 / this profile\'s node_modules was created by a different pnpm major; it must be rebuilt (pnpm install) before changes can be applied',
48
+ };
49
+ }
50
+ if (output.includes('ERR_PNPM_ADDING_TO_ROOT')) {
51
+ return {
52
+ code: 'adding-to-root',
53
+ recoverable: false,
54
+ message: 'pnpm 拒绝在 workspace 根目录安装(缺少 -w)。这是市场的 bug,请升级 dshmarket 到最新版 / pnpm refused to add at a workspace root (missing -w); this is a market bug — please update dshmarket',
55
+ };
56
+ }
57
+ if (/--workspace-root may only be used inside a workspace/i.test(output)) {
58
+ return {
59
+ code: 'not-a-workspace',
60
+ recoverable: false,
61
+ message: 'profile 目录不是 pnpm workspace,却传入了 -w。这是市场的 bug,请升级 dshmarket 到最新版 / -w was passed but the profile is not a pnpm workspace; this is a market bug — please update dshmarket',
62
+ };
63
+ }
64
+ if (output.includes('pnpm not found on PATH')) {
65
+ return {
66
+ code: 'pnpm-missing',
67
+ recoverable: false,
68
+ message: '找不到 pnpm,请先在市场页顶部一键安装组件 / pnpm is not on PATH — use the one-click setup at the top of the market page',
69
+ };
70
+ }
71
+ return null;
72
+ }
package/lib/profile.js ADDED
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Profile filesystem reads — everything the market learns from a dsh
3
+ * profile directory (manifest, lockfile, installed package trees). Pure
4
+ * functions of the directory contents; no processes, no network.
5
+ */
6
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
7
+ import { homedir } from 'node:os';
8
+ import { join } from 'node:path';
9
+ /** Resolve a profile name to its directory under DSH_HOME (default ~/.dsh). */
10
+ export function profileDir(profile) {
11
+ const home = process.env.DSH_HOME ?? join(homedir(), '.dsh');
12
+ return join(home, 'profiles', profile);
13
+ }
14
+ /** Community dependencies of the profile (official in-box scope filtered out). */
15
+ export function readInstalled(profile) {
16
+ try {
17
+ const manifest = JSON.parse(readFileSync(join(profileDir(profile), 'package.json'), 'utf8'));
18
+ const installed = {};
19
+ for (const [name, spec] of Object.entries(manifest.dependencies ?? {})) {
20
+ if (!name.startsWith('@deepseek-ai/'))
21
+ installed[name] = spec;
22
+ }
23
+ return installed;
24
+ }
25
+ catch {
26
+ return {};
27
+ }
28
+ }
29
+ /** The version actually present in the profile's node_modules, or null. */
30
+ export function readInstalledVersion(profile, name) {
31
+ try {
32
+ const manifest = JSON.parse(readFileSync(join(profileDir(profile), 'node_modules', name, 'package.json'), 'utf8'));
33
+ return manifest.version ?? null;
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ /** Pinned commit per `owner/repo` from the profile lockfile's codeload tarball URLs. */
40
+ export function readLockCommits(profile) {
41
+ const commits = new Map();
42
+ try {
43
+ const lock = readFileSync(join(profileDir(profile), 'pnpm-lock.yaml'), 'utf8');
44
+ for (const m of lock.matchAll(/codeload\.github\.com\/([^/\s]+\/[^/\s]+)\/tar\.gz\/([0-9a-f]{40})/g)) {
45
+ commits.set(m[1].toLowerCase(), m[2]);
46
+ }
47
+ }
48
+ catch { /* no lockfile — no git installs to report */ }
49
+ return commits;
50
+ }
51
+ /** True when the installed package's manifest declares a dsh plugin surface. */
52
+ export function hasDshManifest(dir) {
53
+ try {
54
+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
55
+ return manifest.dsh !== undefined;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ /**
62
+ * True when the package's declared entry artifact actually exists — github
63
+ * source checkouts of build-required plugins ship no lib/, and promoting one
64
+ * into the bundle layer bricks the next boot (ERR_MODULE_NOT_FOUND kills the
65
+ * whole profile, #18).
66
+ */
67
+ export function entryArtifactExists(dir) {
68
+ try {
69
+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
70
+ const candidates = [];
71
+ if (typeof manifest.main === 'string')
72
+ candidates.push(manifest.main);
73
+ const rootExport = typeof manifest.exports === 'string'
74
+ ? manifest.exports
75
+ : manifest.exports?.['.'];
76
+ if (typeof rootExport === 'string')
77
+ candidates.push(rootExport);
78
+ else if (rootExport !== null && typeof rootExport === 'object') {
79
+ for (const value of Object.values(rootExport))
80
+ if (typeof value === 'string')
81
+ candidates.push(value);
82
+ }
83
+ if (candidates.length === 0)
84
+ candidates.push('index.js');
85
+ return candidates.some(rel => existsSync(join(dir, rel)));
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ /** Plugin subdirectories (depth 2) of a collection checkout, as relative paths. */
92
+ export function pluginSubdirs(root) {
93
+ const found = [];
94
+ let level1 = [];
95
+ try {
96
+ level1 = readdirSync(root, { withFileTypes: true })
97
+ .filter(dirent => dirent.isDirectory() && /^[A-Za-z0-9_.-]+$/.test(dirent.name) && dirent.name !== 'node_modules')
98
+ .map(dirent => dirent.name);
99
+ }
100
+ catch {
101
+ return found;
102
+ }
103
+ for (const sub of level1) {
104
+ if (hasDshManifest(join(root, sub))) {
105
+ found.push(sub);
106
+ continue;
107
+ }
108
+ try {
109
+ for (const inner of readdirSync(join(root, sub), { withFileTypes: true })) {
110
+ if (!inner.isDirectory() || !/^[A-Za-z0-9_.-]+$/.test(inner.name) || inner.name === 'node_modules')
111
+ continue;
112
+ if (hasDshManifest(join(root, sub, inner.name)))
113
+ found.push(`${sub}/${inner.name}`);
114
+ }
115
+ }
116
+ catch { /* unreadable level — skip */ }
117
+ if (found.length >= 8)
118
+ break;
119
+ }
120
+ return found.slice(0, 8);
121
+ }