universal-plugin-hub 1.5.0 → 1.5.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/src/market.js CHANGED
@@ -135,7 +135,14 @@ function hasSourceCheckout(dir) {
135
135
  return existsSync(join(git, 'uph-clone-complete')) || existsSync(join(git, 'index'))
136
136
  }
137
137
 
138
- async function cloneRepoToCache(dir, url, { branch, timeoutMs } = {}) {
138
+ function safeSparsePath(root, pathValue) {
139
+ if (typeof pathValue !== 'string' || !pathValue) return ''
140
+ const resolved = pluginPath(root, pathValue)
141
+ const rel = relative(resolve(root), resolved).replace(/\\/g, '/').replace(/^\/+|\/+$/g, '')
142
+ return rel === '.' ? '' : rel
143
+ }
144
+
145
+ async function cloneRepoToCache(dir, url, { branch, timeoutMs, sparsePath } = {}) {
139
146
  const hadCheckout = hasSourceCheckout(dir)
140
147
  if (hadCheckout && readCheckoutOrigin(dir) === url) return false
141
148
 
@@ -144,10 +151,29 @@ async function cloneRepoToCache(dir, url, { branch, timeoutMs } = {}) {
144
151
  mkdirSync(parent, { recursive: true })
145
152
  const staging = mkdtempSync(join(parent, '.clone-'))
146
153
  try {
147
- const args = ['clone', '--depth', '1']
154
+ const normalizedSparse = safeSparsePath(staging, sparsePath)
155
+ const args = ['clone', '--depth', '1', '--single-branch']
148
156
  if (branch) args.push('--branch', String(branch))
149
157
  args.push(url, staging)
150
- await runGit(args, undefined, timeoutMs)
158
+
159
+ let cloned = false
160
+ if (normalizedSparse && /^https?:\/\//i.test(String(url))) {
161
+ try {
162
+ const sparseArgs = ['clone', '--depth', '1', '--single-branch', '--filter=blob:none', '--no-checkout']
163
+ if (branch) sparseArgs.push('--branch', String(branch))
164
+ sparseArgs.push(url, staging)
165
+ await runGit(sparseArgs, undefined, timeoutMs)
166
+ await runGit(['sparse-checkout', 'set', '--cone', '--', normalizedSparse], staging, timeoutMs)
167
+ await runGit(['checkout'], staging, timeoutMs)
168
+ cloned = true
169
+ } catch {
170
+ safeRmDir(staging)
171
+ mkdirSync(staging, { recursive: true })
172
+ }
173
+ }
174
+ if (!cloned) {
175
+ await runGit(args, undefined, timeoutMs)
176
+ }
151
177
  // Empty repositories can be cloned successfully without an index.
152
178
  writeFileSync(join(staging, '.git', 'uph-clone-complete'), '')
153
179
  // The slug can collide with an abandoned preview from another repository.
@@ -212,7 +238,7 @@ export async function pullSource(sourceId) {
212
238
  * Returns { dir } of a materialized checkout for the plugin, or throws with
213
239
  * a user-facing message.
214
240
  */
215
- export async function materializePlugin(sourceId, pluginName, source, { refresh = false } = {}) {
241
+ export async function materializePlugin(sourceId, pluginName, source, { refresh = false, sourcePulled = false, allowStaleFallback = false } = {}) {
216
242
  safeSegment(sourceId, 'source id')
217
243
  safeSegment(pluginName, 'plugin name')
218
244
 
@@ -236,17 +262,37 @@ export async function materializePlugin(sourceId, pluginName, source, { refresh
236
262
  if (typeof normalized.url !== 'string' || !/^https?:\/\//.test(normalized.url)) {
237
263
  throw new Error(`plugin ${pluginName}: unsupported remote url`)
238
264
  }
265
+ const sourceCache = sourceCacheDir(sourceId)
266
+ const ownDir = sourceRepositoryDir(sourceCache, normalized)
267
+ if (ownDir) {
268
+ if (refresh && !sourcePulled && existsSync(join(sourceCache, '.git'))) {
269
+ try {
270
+ await pullSource(sourceId)
271
+ } catch (err) {
272
+ if (!allowStaleFallback) throw err
273
+ }
274
+ const refreshedDir = sourceRepositoryDir(sourceCache, normalized)
275
+ if (refreshedDir) return { dir: refreshedDir }
276
+ } else {
277
+ return { dir: ownDir }
278
+ }
279
+ }
239
280
  const remoteKey = remoteCheckoutKey(normalized.url, normalized.ref)
240
281
  const checkout = join(sourceCacheDir('remote'), remoteKey)
241
282
  await withGitLock(`remote:${remoteKey}`, async () => {
242
- const cloned = await cloneRepoToCache(checkout, normalized.url, { branch: normalized.ref })
283
+ const sparsePath = normalized.source === 'git-subdir' ? normalized.path : undefined
284
+ const cloned = await cloneRepoToCache(checkout, normalized.url, { branch: normalized.ref, sparsePath })
243
285
  if (!cloned && refresh) {
244
286
  // The cached checkout is otherwise reused forever, so updates would
245
287
  // reinstall the first clone's commit. Re-fetch the tracked ref.
246
- const args = ['fetch', '--depth', '1', 'origin']
247
- if (normalized.ref) args.push(String(normalized.ref))
248
- await runGit(args, checkout)
249
- await runGit(['reset', '--hard', 'FETCH_HEAD'], checkout)
288
+ try {
289
+ const args = ['fetch', '--depth', '1', 'origin']
290
+ if (normalized.ref) args.push(String(normalized.ref))
291
+ await runGit(args, checkout)
292
+ await runGit(['reset', '--hard', 'FETCH_HEAD'], checkout)
293
+ } catch (err) {
294
+ if (!allowStaleFallback) throw err
295
+ }
250
296
  }
251
297
  if (normalized.sha && /^[0-9a-f]{7,64}$/i.test(String(normalized.sha))) {
252
298
  try {
@@ -257,6 +303,17 @@ export async function materializePlugin(sourceId, pluginName, source, { refresh
257
303
  }
258
304
  } catch {}
259
305
  }
306
+ if (!cloned && existsSync(join(checkout, '.git', 'info', 'sparse-checkout'))) {
307
+ const posixPath = safeSparsePath(checkout, normalized.path)
308
+ if (posixPath) {
309
+ const targetPath = pluginPath(checkout, posixPath)
310
+ if (!existsSync(targetPath)) {
311
+ await runGit(['sparse-checkout', 'add', '--', posixPath], checkout)
312
+ }
313
+ } else {
314
+ await runGit(['sparse-checkout', 'disable'], checkout)
315
+ }
316
+ }
260
317
  })
261
318
  const dir = normalized.path ? pluginPath(checkout, normalized.path) : checkout
262
319
  if (!existsSync(dir)) throw new Error(`plugin ${pluginName}: path ${normalized.path} not found in remote repo`)
package/src/parser.js CHANGED
@@ -8,7 +8,8 @@
8
8
  * 4. Multi-plugin Monorepos (plugins/*, skills/*, packages/*, tools/*, extensions/*)
9
9
  * 5. Single-plugin Standalone Repositories (root SKILL.md, plugin.json, skills/, commands/, agents/, .cursorrules)
10
10
  */
11
- import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, copyFileSync } from 'node:fs'
11
+ import { existsSync, readFileSync, readdirSync, statSync, realpathSync, mkdirSync, copyFileSync } from 'node:fs'
12
+ import { readdir, mkdir, copyFile, stat, realpath } from 'node:fs/promises'
12
13
  import { join, basename, dirname, isAbsolute, relative, resolve } from 'node:path'
13
14
  import { load as parseYaml } from 'js-yaml'
14
15
  import { sourceCacheDir, installedDir, pluginDataDir } from './store.js'
@@ -1887,15 +1888,86 @@ export function pluginDetail(sourceId, pluginName, source, rowFallback) {
1887
1888
  }
1888
1889
 
1889
1890
  /** Recursively copy a directory (plain JS; avoids shell dependency). */
1890
- export function copyDir(from, to) {
1891
+ export function copyDir(from, to, visited = null) {
1892
+ const seen = visited || new Set()
1893
+ if (!visited) {
1894
+ try { seen.add(realpathSync(from)) } catch {}
1895
+ }
1891
1896
  mkdirSync(to, { recursive: true })
1892
- for (const entry of readdirSync(from)) {
1893
- const src = join(from, entry)
1894
- const dest = join(to, entry)
1895
- if (statSync(src).isDirectory()) {
1896
- copyDir(src, dest)
1897
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
1898
+ const src = join(from, entry.name)
1899
+ const dest = join(to, entry.name)
1900
+ if (entry.isDirectory()) {
1901
+ copyDir(src, dest, seen)
1902
+ } else if (entry.isSymbolicLink()) {
1903
+ let st
1904
+ try { st = statSync(src) } catch { continue }
1905
+ if (st.isDirectory()) {
1906
+ let realDir
1907
+ try { realDir = realpathSync(src) } catch { continue }
1908
+ if (seen.has(realDir)) continue
1909
+ seen.add(realDir)
1910
+ copyDir(src, dest, seen)
1911
+ } else if (st.isFile()) {
1912
+ copyFileSync(src, dest)
1913
+ }
1897
1914
  } else {
1898
1915
  copyFileSync(src, dest)
1899
1916
  }
1900
1917
  }
1901
1918
  }
1919
+
1920
+ /** Recursively copy a directory asynchronously using a bounded concurrent worker pool. */
1921
+ export async function copyDirAsync(from, to, { concurrency = 32, excludeNames = null } = {}) {
1922
+ const seen = new Set()
1923
+ try { seen.add(await realpath(from)) } catch {}
1924
+ const dirs = [to]
1925
+ const files = []
1926
+ async function scan(curFrom, curTo) {
1927
+ const entries = await readdir(curFrom, { withFileTypes: true })
1928
+ for (const entry of entries) {
1929
+ if (excludeNames?.has(entry.name)) continue
1930
+ const src = join(curFrom, entry.name)
1931
+ const dest = join(curTo, entry.name)
1932
+ if (entry.isDirectory()) {
1933
+ dirs.push(dest)
1934
+ await scan(src, dest)
1935
+ } else if (entry.isFile()) {
1936
+ files.push([src, dest])
1937
+ } else if (entry.isSymbolicLink()) {
1938
+ let st
1939
+ try { st = await stat(src) } catch { continue }
1940
+ if (st.isDirectory()) {
1941
+ let realDir
1942
+ try { realDir = await realpath(src) } catch { continue }
1943
+ if (seen.has(realDir)) continue
1944
+ seen.add(realDir)
1945
+ dirs.push(dest)
1946
+ await scan(src, dest)
1947
+ } else if (st.isFile()) {
1948
+ files.push([src, dest])
1949
+ }
1950
+ }
1951
+ }
1952
+ }
1953
+ await scan(from, to)
1954
+ for (const dir of dirs) {
1955
+ await mkdir(dir, { recursive: true })
1956
+ }
1957
+ if (files.length === 0) return
1958
+ let firstErr = null
1959
+ let idx = 0
1960
+ const workerCount = Math.max(1, Math.min(concurrency, files.length))
1961
+ async function worker() {
1962
+ while (!firstErr && idx < files.length) {
1963
+ const [src, dest] = files[idx++]
1964
+ try {
1965
+ await copyFile(src, dest)
1966
+ } catch (err) {
1967
+ if (!firstErr) firstErr = err
1968
+ }
1969
+ }
1970
+ }
1971
+ await Promise.all(Array.from({ length: workerCount }, worker))
1972
+ if (firstErr) throw firstErr
1973
+ }
package/src/routes.js CHANGED
@@ -588,7 +588,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile
588
588
  const cfg = item.config || {}
589
589
  const ownership = pluginTools?.[`user-mcp::${cfg.serverName}`]
590
590
  if (ownership?.pluginConnectorOwned || (ownership?.pluginOAuthOwned && remoteConfigFromEntry(cfg))) continue
591
- if (cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
591
+ if (typeof cfg.serverName === 'string' && cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
592
592
  state.userMcps.push(userMcpConfig(cfg.serverName, {
593
593
  transport: cfg.transport, url: cfg.url, command: cfg.command,
594
594
  args: Array.isArray(cfg.args) ? cfg.args : [], cwd: cfg.cwd,
package/src/store.js CHANGED
@@ -66,6 +66,16 @@ function unlinkReparsePointsSync(dir) {
66
66
  }
67
67
  }
68
68
 
69
+ function unlinkSymlinkPath(dir) {
70
+ try {
71
+ unlinkSync(dir)
72
+ } catch {
73
+ try { rmdirSync(dir) } catch {
74
+ try { rmSync(dir, { recursive: true, force: true }) } catch {}
75
+ }
76
+ }
77
+ }
78
+
69
79
  /** Robust directory deletion handling Windows readonly/locked files. */
70
80
  export function safeRmDir(dir, { allowTrash = true, quarantineRoot = trashRoot() } = {}) {
71
81
  if (!dir) return
@@ -75,13 +85,7 @@ export function safeRmDir(dir, { allowTrash = true, quarantineRoot = trashRoot()
75
85
  let lstatErr = null
76
86
  try { entry = lstatSync(dir, { throwIfNoEntry: false }) } catch (err) { lstatErr = err }
77
87
  if (entry?.isSymbolicLink()) {
78
- try {
79
- unlinkSync(dir)
80
- } catch {
81
- try { rmdirSync(dir) } catch {
82
- try { rmSync(dir, { recursive: true, force: true }) } catch {}
83
- }
84
- }
88
+ unlinkSymlinkPath(dir)
85
89
  return
86
90
  }
87
91
  if (!entry && !lstatErr && !existsSync(dir)) return
@@ -130,23 +134,45 @@ export function safeRmDir(dir, { allowTrash = true, quarantineRoot = trashRoot()
130
134
  /** Remove managed files before forgetting the record needed to retry cleanup. */
131
135
  export function removeManagedDir(dir, { allowTrash = false, deferCleanup = false } = {}) {
132
136
  if (deferCleanup) {
133
- try {
134
- if (!lstatSync(dir, { throwIfNoEntry: false })) return
135
- // Detach the checkout as a unit. An open Windows handle can block the
136
- // move, in which case the caller retries while the checkout stays intact.
137
- const quarantineRoot = trashRoot()
138
- const trashed = moveToTrash(dir, quarantineRoot)
139
- void rm(trashed, { recursive: true, force: true }).then(
140
- () => { try { rmdirSync(quarantineRoot) } catch {} },
141
- () => scheduleTrashSweep(trashed),
142
- )
143
- return
144
- } catch (cause) {
145
- throw Object.assign(new Error(`无法清理目录:${dir}`, { cause }), {
146
- code: cause.code,
147
- syscall: cause.syscall,
148
- path: dir,
149
- })
137
+ let entry
138
+ let lstatErr = null
139
+ try { entry = lstatSync(dir, { throwIfNoEntry: false }) } catch (err) { lstatErr = err }
140
+ if (!entry && !lstatErr) return
141
+ if (entry?.isSymbolicLink()) {
142
+ unlinkSymlinkPath(dir)
143
+ try {
144
+ if (!lstatSync(dir, { throwIfNoEntry: false })) return
145
+ } catch {}
146
+ }
147
+ const quarantineRoot = trashRoot()
148
+ if (
149
+ !lstatErr &&
150
+ entry?.isDirectory() &&
151
+ !isSameOrInsidePath(dir, quarantineRoot) &&
152
+ !isSameOrInsidePath(quarantineRoot, dir)
153
+ ) {
154
+ try {
155
+ // Detach the checkout as a unit. An open Windows handle can block the
156
+ // move, in which case the caller retries while the checkout stays intact.
157
+ const trashed = moveToTrash(dir, quarantineRoot)
158
+ PENDING_TRASH_PATHS.add(trashed)
159
+ void rm(trashed, { recursive: true, force: true }).then(
160
+ () => {
161
+ PENDING_TRASH_PATHS.delete(trashed)
162
+ try { rmdirSync(quarantineRoot) } catch {}
163
+ },
164
+ () => scheduleTrashSweep(trashed),
165
+ )
166
+ return
167
+ } catch (cause) {
168
+ if (cause?.code !== 'EXDEV') {
169
+ throw Object.assign(new Error(`无法清理目录:${dir}`, { cause }), {
170
+ code: cause.code,
171
+ syscall: cause.syscall,
172
+ path: dir,
173
+ })
174
+ }
175
+ }
150
176
  }
151
177
  }
152
178
  safeRmDir(dir, { allowTrash })