universal-plugin-hub 1.5.1 → 1.6.0

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/local.js CHANGED
@@ -1,15 +1,20 @@
1
1
  import { existsSync, readdirSync, statSync, cpSync, copyFileSync, mkdirSync, writeFileSync, mkdtempSync, readFileSync, createWriteStream, rmSync } from 'node:fs'
2
2
  import { join, basename, resolve, dirname, relative, isAbsolute } from 'node:path'
3
3
  import { fileURLToPath } from 'node:url'
4
- import { execFile } from 'node:child_process'
4
+ import { execFile, spawn } from 'node:child_process'
5
5
  import { promisify } from 'node:util'
6
6
  import { load as parseYaml } from 'js-yaml'
7
7
  import { sourceCacheDir, readState, writeState, safeRmDir, slugify } from './store.js'
8
8
  import { safeSegment, pluginPath } from './market.js'
9
- import { parsePluginRowFromDir, parseMarketplaceFromDisk, listSkills, listAgents, readPluginManifest, invalidateMarketplaceCache, invalidateParserCaches, formatDisplayName, normalizeVersion, MARKETPLACE_COMPONENT_KEYS } from './parser.js'
9
+ import {
10
+ parsePluginRowFromDir, parseMarketplaceFromDisk, listSkills, listAgents, readPluginManifest,
11
+ invalidateMarketplaceCache, invalidateParserCaches, readMarketplace, resolveMarketplacePluginDir,
12
+ formatDisplayName, normalizeVersion, MARKETPLACE_COMPONENT_KEYS,
13
+ } from './parser.js'
10
14
  import { installUploadedSkills, takenSkillNames } from './skill-uploads.js'
11
15
  import { invalidateLocalIconCache } from './icons.js'
12
- import { refreshInstalledPluginsFromSource } from './install.js'
16
+ import { invalidateAtPluginsCache } from './at-plugins.js'
17
+ import { refreshInstalledPluginsFromSource, withPluginLock, withSourceLock, removeManagedDirAsync, replaceManagedDirAsync } from './install.js'
13
18
 
14
19
  const execFileAsync = promisify(execFile)
15
20
 
@@ -41,12 +46,92 @@ function sweepTemp() {
41
46
  } catch {}
42
47
  }
43
48
 
49
+ function mapProgressRange(onProgress, startPct, endPct) {
50
+ if (typeof onProgress !== 'function') return null
51
+ return (evt) => {
52
+ const raw = Math.max(0, Math.min(100, Number(evt?.percent) || 0))
53
+ const scaled = Math.round(startPct + (raw / 100) * (endPct - startPct))
54
+ onProgress({ ...evt, percent: scaled })
55
+ }
56
+ }
57
+
44
58
  /** Native archive extraction (Windows bsdtar also handles ZIP). */
45
- export async function extractZip(zipPath, destDir) {
59
+ export async function extractZip(zipPath, destDir, onProgress = null) {
46
60
  sweepTemp()
47
61
  mkdirSync(destDir, { recursive: true })
48
62
  const tar = process.platform === 'win32' ? join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe') : 'tar'
49
- await execFileAsync(tar, ['-xf', zipPath, '-C', destDir], { windowsHide: true })
63
+ if (typeof onProgress !== 'function') {
64
+ await execFileAsync(tar, ['-xf', zipPath, '-C', destDir], { windowsHide: true })
65
+ return
66
+ }
67
+
68
+ let totalEntries = 0
69
+ try {
70
+ const { stdout } = await execFileAsync(tar, ['-tf', zipPath], { windowsHide: true, maxBuffer: 64 * 1024 * 1024 })
71
+ totalEntries = String(stdout || '').split(/\r?\n/).filter((l) => l.trim()).length
72
+ } catch {}
73
+ onProgress({ extracted: 0, totalEntries, ratio: 0 })
74
+
75
+ await new Promise((resolve, reject) => {
76
+ const child = spawn(tar, ['-xvf', zipPath, '-C', destDir], { windowsHide: true })
77
+ let extracted = 0
78
+ let lastEmit = 0
79
+ let stdoutBuf = ''
80
+ let stderrBuf = ''
81
+ const stderrLines = []
82
+
83
+ const emit = (force = false) => {
84
+ const now = Date.now()
85
+ if (!force && now - lastEmit < 40) return
86
+ lastEmit = now
87
+ const capped = totalEntries > 0 ? Math.min(extracted, totalEntries) : extracted
88
+ const ratio = totalEntries > 0 ? Math.min(1, capped / totalEntries) : 0
89
+ onProgress({ extracted: capped, totalEntries, ratio })
90
+ }
91
+
92
+ const consume = (chunk, bufName, isErr) => {
93
+ const next = (bufName === 'out' ? stdoutBuf : stderrBuf) + String(chunk)
94
+ const parts = next.split(/\r?\n/)
95
+ const tail = parts.pop() ?? ''
96
+ if (bufName === 'out') stdoutBuf = tail
97
+ else stderrBuf = tail
98
+
99
+ let added = false
100
+ for (const line of parts) {
101
+ const trimmed = line.trim()
102
+ if (!trimmed) continue
103
+ extracted += 1
104
+ added = true
105
+ if (isErr) {
106
+ stderrLines.push(trimmed)
107
+ if (stderrLines.length > 20) stderrLines.shift()
108
+ }
109
+ }
110
+ if (added) emit(false)
111
+ }
112
+
113
+ child.stdout?.on('data', (d) => consume(d, 'out', false))
114
+ child.stderr?.on('data', (d) => consume(d, 'err', true))
115
+ child.on('error', reject)
116
+ child.on('close', (code) => {
117
+ for (const [tail, isErr] of [[stdoutBuf, false], [stderrBuf, true]]) {
118
+ const trimmed = tail.trim()
119
+ if (trimmed) {
120
+ extracted += 1
121
+ if (isErr) {
122
+ stderrLines.push(trimmed)
123
+ if (stderrLines.length > 20) stderrLines.shift()
124
+ }
125
+ }
126
+ }
127
+ if (code === 0) {
128
+ onProgress({ extracted: totalEntries || extracted, totalEntries, ratio: 1 })
129
+ resolve()
130
+ } else {
131
+ reject(new Error(stderrLines.slice(-4).join(' | ') || `tar exited with code ${code}`))
132
+ }
133
+ })
134
+ })
50
135
  }
51
136
 
52
137
  export const MAX_UPLOAD_BYTES = 500 * 1024 * 1024
@@ -313,7 +398,7 @@ function marketSourceName(dir, fallbackName) {
313
398
  return formatDisplayName(fallbackName) || '本地市场'
314
399
  }
315
400
 
316
- export async function inspectLocalPlugin(rawPath) {
401
+ export async function inspectLocalPlugin(rawPath, { onProgress } = {}) {
317
402
  let targetPath = String(rawPath || '').trim().replace(/^["']|["']$/g, '')
318
403
  if (/^file:/i.test(targetPath)) targetPath = fileURLToPath(targetPath)
319
404
  if (!existsSync(targetPath)) {
@@ -328,7 +413,15 @@ export async function inspectLocalPlugin(rawPath) {
328
413
  mkdirSync(TEMP_ROOT(), { recursive: true })
329
414
  tempExtractDir = mkdtempSync(join(TEMP_ROOT(), 'inspect-'))
330
415
  try {
331
- await extractZip(targetPath, tempExtractDir)
416
+ await extractZip(targetPath, tempExtractDir, typeof onProgress === 'function' ? (p) => {
417
+ onProgress({
418
+ stage: 'extracting',
419
+ extracted: p.extracted,
420
+ totalEntries: p.totalEntries,
421
+ percent: Math.round((p.ratio || 0) * 80),
422
+ detail: p.totalEntries > 0 ? `正在解压 ${p.extracted} / ${p.totalEntries} 个文件` : `已解压 ${p.extracted} 个文件`,
423
+ })
424
+ } : null)
332
425
  inspectDir = tempExtractDir
333
426
  } catch (e) {
334
427
  if (tempExtractDir) safeRmDir(tempExtractDir)
@@ -396,6 +489,7 @@ export async function inspectLocalPlugin(rawPath) {
396
489
  const skills = entries.flatMap((e) => listSkills(e.dir))
397
490
  const agents = entries.flatMap((e) => listAgents(e.dir))
398
491
 
492
+ onProgress?.({ stage: 'analyzing', percent: 88, detail: '正在识别插件清单与冲突…' })
399
493
  const localConflicts = kind === 'skills' ? [] : collectLocalConflicts(entries)
400
494
  const suggestedLabel = kind === 'marketplace' ? marketSourceName(effectiveDir, fallbackName) : ''
401
495
  let exists = false
@@ -434,6 +528,7 @@ export async function inspectLocalPlugin(rawPath) {
434
528
  existingUpdatedAt = localConflicts[0].existingUpdatedAt
435
529
  }
436
530
 
531
+ onProgress?.({ stage: 'analyzing', percent: 95, detail: '正在整理预览信息…' })
437
532
  return {
438
533
  ok: true,
439
534
  kind,
@@ -487,16 +582,18 @@ function collectLocalConflicts(entries) {
487
582
  * Pure skill packages go straight into the Skills tab instead of the plugin
488
583
  * install pipeline: no mirrored copy, no agents/commands conversion.
489
584
  */
490
- export async function importLocalSkills(rawPath, { overwrite = false, overwriteNames = null } = {}) {
491
- const inspectRes = await inspectLocalPlugin(rawPath)
585
+ export async function importLocalSkills(rawPath, { overwrite = false, overwriteNames = null, onProgress = null } = {}) {
586
+ const inspectRes = await inspectLocalPlugin(rawPath, { onProgress: mapProgressRange(onProgress, 0, 70) })
492
587
  if (!inspectRes.ok) throw new Error(inspectRes.error)
493
588
  if (inspectRes.kind !== 'skills') throw new Error('该内容不是纯 Skills 包')
494
589
  const { tempExtractDir, entries, singleFile } = inspectRes
495
590
  try {
591
+ onProgress?.({ stage: 'copying', percent: 82, detail: '正在安装 Skill 到工作区…' })
496
592
  // A bare SKILL.md upload is one flat skill. When the folder it came from is
497
593
  // a collection, the walk up yields several entries, and flattening those
498
594
  // would drop each skill's assets along with its directory.
499
595
  const installed = installUploadedSkills(entries, { overwrite, overwriteNames, singleFile: singleFile && entries.length === 1 })
596
+ onProgress?.({ stage: 'copying', percent: 96, detail: 'Skill 安装完成' })
500
597
  return { ok: true, sourceId: 'skills-local', skills: installed, kind: 'skills' }
501
598
  } finally {
502
599
  if (tempExtractDir) safeRmDir(tempExtractDir)
@@ -561,7 +658,7 @@ function syncPluginManifestMetadata(destDir, row, { stripRootMarketplace = false
561
658
  writeFileSync(out, JSON.stringify(fields, null, 2), 'utf8')
562
659
  }
563
660
 
564
- async function copyEntriesToLocalCache(entries, { overwrite = false, tempExtractDir = null, stripRootMarketplace = false } = {}) {
661
+ async function copyEntriesToLocalCache(entries, { overwrite = false, tempExtractDir = null, stripRootMarketplace = false, onProgress = null } = {}) {
565
662
  const localDir = sourceCacheDir('local')
566
663
  mkdirSync(localDir, { recursive: true })
567
664
  const clashing = []
@@ -582,17 +679,22 @@ async function copyEntriesToLocalCache(entries, { overwrite = false, tempExtract
582
679
  }
583
680
  const importedNames = []
584
681
  try {
585
- for (const { row, dir } of entries) {
682
+ for (let i = 0; i < entries.length; i++) {
683
+ const { row, dir } = entries[i]
586
684
  const cleanName = safeSegment(row.name, 'plugin name')
587
685
  const destDir = join(localDir, cleanName)
588
686
  if (resolve(destDir) !== resolve(dir)) {
589
- safeRmDir(destDir)
590
- cpSync(dir, destDir, { recursive: true, force: true })
687
+ await replaceManagedDirAsync(dir, destDir, undefined, false, { deferCleanup: true, inPlaceFallback: true })
591
688
  }
592
689
  if (stripRootMarketplace) {
593
690
  syncPluginManifestMetadata(destDir, row, { stripRootMarketplace: true })
594
691
  }
595
692
  importedNames.push(cleanName)
693
+ onProgress?.({
694
+ stage: 'copying',
695
+ percent: 55 + Math.round(((i + 1) / entries.length) * 25),
696
+ detail: `正在写入本地插件 (${i + 1} / ${entries.length})`,
697
+ })
596
698
  }
597
699
  } finally {
598
700
  if (tempExtractDir) safeRmDir(tempExtractDir)
@@ -600,10 +702,13 @@ async function copyEntriesToLocalCache(entries, { overwrite = false, tempExtract
600
702
  invalidateMarketplaceCache('local')
601
703
  invalidateParserCaches()
602
704
  invalidateLocalIconCache('local')
705
+ let refreshed = []
603
706
  if (overwrite && importedNames.length > 0) {
604
- await refreshInstalledPluginsFromSource('local', importedNames)
707
+ onProgress?.({ stage: 'refreshing', percent: 85, detail: '正在更新已安装副本…' })
708
+ refreshed = await refreshInstalledPluginsFromSource('local', importedNames)
709
+ onProgress?.({ stage: 'refreshing', percent: 96, detail: '已安装副本更新完成' })
605
710
  }
606
- return importedNames
711
+ return { importedNames, refreshed }
607
712
  }
608
713
 
609
714
  /**
@@ -612,8 +717,8 @@ async function copyEntriesToLocalCache(entries, { overwrite = false, tempExtract
612
717
  * without writing a root marketplace.json; otherwise plugins keep their manifest
613
718
  * layout inside `market/local-<slug>/` as an independent tab.
614
719
  */
615
- export async function importLocalMarketplace(rawPath, { sourceName = '', overwrite = false, target = '' } = {}) {
616
- const inspectRes = await inspectLocalPlugin(rawPath)
720
+ export async function importLocalMarketplace(rawPath, { sourceName = '', overwrite = false, target = '', onProgress = null } = {}) {
721
+ const inspectRes = await inspectLocalPlugin(rawPath, { onProgress: mapProgressRange(onProgress, 0, 55) })
617
722
  if (!inspectRes.ok) throw new Error(inspectRes.error)
618
723
  if (inspectRes.kind !== 'marketplace') throw new Error('该内容不是插件市场')
619
724
  const { effectiveDir, tempExtractDir, entries } = inspectRes
@@ -625,7 +730,7 @@ export async function importLocalMarketplace(rawPath, { sourceName = '', overwri
625
730
  if (tempExtractDir) safeRmDir(tempExtractDir)
626
731
  throw new Error('尚未创建本地插件标签,请先上传单个本地插件或将其作为独立标签页添加')
627
732
  }
628
- await copyEntriesToLocalCache(entries, { overwrite, tempExtractDir, stripRootMarketplace: true })
733
+ const { refreshed } = await copyEntriesToLocalCache(entries, { overwrite, tempExtractDir, stripRootMarketplace: true, onProgress })
629
734
  return {
630
735
  ok: true,
631
736
  kind: 'marketplace',
@@ -633,6 +738,7 @@ export async function importLocalMarketplace(rawPath, { sourceName = '', overwri
633
738
  sourceId: 'local',
634
739
  source: localSource,
635
740
  plugins: entries.map((entry) => entry.row),
741
+ refreshed,
636
742
  }
637
743
  }
638
744
 
@@ -661,7 +767,8 @@ export async function importLocalMarketplace(rawPath, { sourceName = '', overwri
661
767
  try {
662
768
  safeRmDir(dest)
663
769
  mkdirSync(dest, { recursive: true })
664
- for (const { row, dir } of entries) {
770
+ for (let i = 0; i < entries.length; i++) {
771
+ const { row, dir } = entries[i]
665
772
  // Keep each plugin on the path its manifest declares: a rewritten layout
666
773
  // (`plugins/<name>`) would break `./external_plugins/x` and `./`, and the
667
774
  // reader resolves sources against the copied manifest after a restart.
@@ -669,6 +776,11 @@ export async function importLocalMarketplace(rawPath, { sourceName = '', overwri
669
776
  mkdirSync(dirname(targetDir), { recursive: true })
670
777
  if (resolve(targetDir) !== resolve(dest)) cpSync(dir, targetDir, { recursive: true, force: true })
671
778
  else copyTreeContents(dir, targetDir)
779
+ onProgress?.({
780
+ stage: 'copying',
781
+ percent: 55 + Math.round(((i + 1) / entries.length) * 25),
782
+ detail: `正在写入插件市场 (${i + 1} / ${entries.length})`,
783
+ })
672
784
  }
673
785
  // Carry the marketplace manifest itself so the standard reader finds the
674
786
  // same rows on the next start, not only during this upload.
@@ -697,15 +809,18 @@ export async function importLocalMarketplace(rawPath, { sourceName = '', overwri
697
809
  invalidateMarketplaceCache(sourceId)
698
810
  invalidateParserCaches()
699
811
  invalidateLocalIconCache(sourceId)
812
+ let refreshed = []
700
813
  if (overwrite) {
701
- await refreshInstalledPluginsFromSource(sourceId, entries.map((entry) => entry.row.name))
814
+ onProgress?.({ stage: 'refreshing', percent: 85, detail: '正在更新已安装副本…' })
815
+ refreshed = await refreshInstalledPluginsFromSource(sourceId, entries.map((entry) => entry.row.name))
816
+ onProgress?.({ stage: 'refreshing', percent: 96, detail: '已安装副本更新完成' })
702
817
  }
703
- return { ok: true, kind: 'marketplace', sourceId, source: state.sources.find(source => source.id === sourceId), plugins: entries.map(entry => entry.row) }
818
+ return { ok: true, kind: 'marketplace', sourceId, source: state.sources.find(source => source.id === sourceId), plugins: entries.map(entry => entry.row), refreshed }
704
819
  }
705
820
 
706
821
  /** Legacy plugin-pipeline import; the UI routes pure skill packages elsewhere. */
707
- export async function importLocalPlugin({ path: rawPath, overwrite = false, sourceName = '' }) {
708
- const inspectRes = await inspectLocalPlugin(rawPath)
822
+ export async function importLocalPlugin({ path: rawPath, overwrite = false, sourceName = '', onProgress = null }) {
823
+ const inspectRes = await inspectLocalPlugin(rawPath, { onProgress: mapProgressRange(onProgress, 0, 55) })
709
824
  if (!inspectRes.ok) {
710
825
  throw new Error(inspectRes.error)
711
826
  }
@@ -718,7 +833,7 @@ export async function importLocalPlugin({ path: rawPath, overwrite = false, sour
718
833
  throw new Error(`已存在同名插件「${cleanPluginName}」`)
719
834
  }
720
835
 
721
- await copyEntriesToLocalCache(entries, { overwrite, tempExtractDir, stripRootMarketplace: false })
836
+ const { refreshed } = await copyEntriesToLocalCache(entries, { overwrite, tempExtractDir, stripRootMarketplace: false, onProgress })
722
837
 
723
838
  // The tab is named once, on the first import. Later imports land in that
724
839
  // same tab: re-applying a name here would silently rename a tab the user
@@ -742,6 +857,7 @@ export async function importLocalPlugin({ path: rawPath, overwrite = false, sour
742
857
  sourceId: 'local',
743
858
  plugin,
744
859
  plugins: entries.map((e) => e.row),
860
+ refreshed,
745
861
  }
746
862
  }
747
863
 
@@ -795,3 +911,71 @@ export function removeDuplicateLocalMarketTabs() {
795
911
  for (const id of ids) invalidateMarketplaceCache(id)
796
912
  return { removed: ids }
797
913
  }
914
+
915
+ /**
916
+ * Permanently delete an uninstalled plugin from the `local` (`Local Plugins`)
917
+ * source cache. Refuses when the plugin is still installed (409) or missing
918
+ * (404). When the deleted item was the last plugin in `local` and no installed
919
+ * `local` plugin remains, automatically removes the empty `local` tab and cache.
920
+ */
921
+ export async function deleteLocalPlugin(pluginName, { hasActiveStagedUploads, cleanupStagedUploads } = {}) {
922
+ const cleanName = safeSegment(pluginName, 'plugin name')
923
+ return withPluginLock(cleanName, () => withSourceLock('local', async () => {
924
+ const state = readState()
925
+ const cleanLower = cleanName.toLowerCase()
926
+ if ((state.plugins || []).some((p) => p && typeof p.name === 'string' && p.name.toLowerCase() === cleanLower)) {
927
+ const error = new Error('该插件当前已安装,请先卸载后再从本地列表删除')
928
+ error.status = 409
929
+ throw error
930
+ }
931
+
932
+ const localDir = sourceCacheDir('local')
933
+ let targetDir = resolveMarketplacePluginDir('local', cleanName)
934
+ if (!targetDir) {
935
+ const direct = join(localDir, cleanName)
936
+ if (existsSync(direct)) {
937
+ try {
938
+ if (statSync(direct).isDirectory()) targetDir = direct
939
+ } catch {}
940
+ }
941
+ }
942
+ if (!targetDir || !existsSync(targetDir) || !containsPath(localDir, targetDir) || resolve(targetDir) === resolve(localDir)) {
943
+ const error = new Error('本地插件不存在')
944
+ error.status = 404
945
+ throw error
946
+ }
947
+
948
+ await removeManagedDirAsync(targetDir, { allowTrash: false })
949
+ invalidateMarketplaceCache('local')
950
+ invalidateParserCaches()
951
+ invalidateLocalIconCache('local')
952
+ invalidateAtPluginsCache()
953
+
954
+ const remaining = readMarketplace('local')
955
+ const latestState = readState()
956
+ const hasInstalledLocal = (latestState.plugins || []).some((p) => p && p.sourceId === 'local')
957
+ if (remaining.length === 0 && !hasInstalledLocal) {
958
+ if (hasActiveStagedUploads?.()) {
959
+ for (const entry of readdirSync(localDir)) {
960
+ if (entry === '.temp') continue
961
+ await removeManagedDirAsync(join(localDir, entry), { allowTrash: false })
962
+ }
963
+ } else {
964
+ cleanupStagedUploads?.()
965
+ await removeManagedDirAsync(localDir, { allowTrash: false })
966
+ }
967
+ latestState.sources = (latestState.sources || []).filter((s) => s && s.id !== 'local')
968
+ if (Array.isArray(latestState.tabOrder)) {
969
+ latestState.tabOrder = latestState.tabOrder.filter((id) => id !== 'local')
970
+ }
971
+ writeState(latestState)
972
+ invalidateMarketplaceCache('local')
973
+ invalidateParserCaches()
974
+ invalidateLocalIconCache('local')
975
+ invalidateAtPluginsCache()
976
+ return { ok: true, pluginName: cleanName, sourceId: 'local', remainingCount: 0, sourceRemoved: true, plugins: [] }
977
+ }
978
+
979
+ return { ok: true, pluginName: cleanName, sourceId: 'local', remainingCount: remaining.length, sourceRemoved: false, plugins: remaining }
980
+ }))
981
+ }
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`)