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/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'
@@ -1416,19 +1417,57 @@ export function listPrompts(dir, manifest = readPluginManifest(dir)) {
1416
1417
  return [...new Set(prompts)]
1417
1418
  }
1418
1419
 
1420
+ const CANONICAL_HOOK_EVENTS = {
1421
+ sessionstart: 'SessionStart',
1422
+ sessionend: 'SessionEnd',
1423
+ userpromptsubmit: 'UserPromptSubmit',
1424
+ pretooluse: 'PreToolUse',
1425
+ posttooluse: 'PostToolUse',
1426
+ posttoolusefailure: 'PostToolUseFailure',
1427
+ permissionrequest: 'PermissionRequest',
1428
+ stop: 'Stop',
1429
+ stopfailure: 'StopFailure',
1430
+ subagentstart: 'SubagentStart',
1431
+ subagentstop: 'SubagentStop',
1432
+ precompact: 'PreCompact',
1433
+ postcompact: 'PostCompact',
1434
+ cwdchanged: 'CwdChanged',
1435
+ notification: 'Notification',
1436
+ }
1437
+
1438
+ export function canonicalizeHookEventName(evt) {
1439
+ if (typeof evt !== 'string') return ''
1440
+ const trimmed = evt.trim()
1441
+ if (!trimmed) return ''
1442
+ const key = trimmed.replace(/[\s_-]+/g, '').toLowerCase()
1443
+ return CANONICAL_HOOK_EVENTS[key] || trimmed
1444
+ }
1445
+
1446
+ function isExistingFile(filePath) {
1447
+ try {
1448
+ return statSync(filePath).isFile()
1449
+ } catch {
1450
+ return false
1451
+ }
1452
+ }
1453
+
1419
1454
  function formatHookEventName(evt) {
1455
+ const canonical = canonicalizeHookEventName(evt)
1420
1456
  const map = {
1421
1457
  'PreToolUse': 'Pre-tool use',
1422
1458
  'PostToolUse': 'Post-tool use',
1459
+ 'PostToolUseFailure': 'Post-tool use failure',
1460
+ 'PermissionRequest': 'Permission request',
1461
+ 'UserPromptSubmit': 'User prompt submit',
1423
1462
  'PreCompact': 'Pre-compact',
1424
1463
  'PostCompact': 'Post-compact',
1425
- 'SessionStart': 'SessionStart',
1426
- 'SessionEnd': 'SessionEnd',
1427
- 'Stop': 'Stop',
1428
- 'PostToolUseFailure': 'PostToolUseFailure',
1429
- 'Notification': 'Notification',
1464
+ 'SessionEnd': 'Session end',
1465
+ 'StopFailure': 'Stop failure',
1466
+ 'SubagentStart': 'Subagent start',
1467
+ 'SubagentStop': 'Subagent stop',
1468
+ 'CwdChanged': 'Cwd changed',
1430
1469
  }
1431
- return map[evt] || evt
1470
+ return map[canonical] || canonical
1432
1471
  }
1433
1472
 
1434
1473
  function extractHookEventMap(raw, isJson) {
@@ -1580,28 +1619,49 @@ function formatHookCmdArg(arg) {
1580
1619
  return /[\s"'\\$`]/.test(arg) ? JSON.stringify(arg) : arg
1581
1620
  }
1582
1621
 
1622
+ const CODEX_ENV_VAR_RE = /(?<![A-Z0-9_])(?:PLUGIN_ROOT|PLUGIN_DATA)\b/
1623
+
1624
+ function valueReferencesCodexEnvVars(val) {
1625
+ if (typeof val === 'string') return CODEX_ENV_VAR_RE.test(val)
1626
+ if (Array.isArray(val)) return val.some(valueReferencesCodexEnvVars)
1627
+ if (val && typeof val === 'object') return Object.values(val).some(valueReferencesCodexEnvVars)
1628
+ return false
1629
+ }
1630
+
1583
1631
  /**
1584
1632
  * Compile all Claude/Codex hook sources (JSON, YAML, inline objects, mixed arrays,
1585
- * `args` arrays, and builtin variables) into a single JSON structure compatible
1586
- * with `@deepseek-ai/dsh-hooks-claude-code`. Returns null if no hook rules exist.
1633
+ * `args` arrays, and builtin variables) into a single normalized JSON structure
1634
+ * consumed by the native Cordis hook runtime (`src/hooks.js`).
1635
+ * Returns null if no hook rules exist.
1587
1636
  */
1588
1637
  export function compileResolvedHooks(pluginRoot, manifest = readPluginManifest(pluginRoot), explicitDataDir) {
1589
1638
  const compiled = {}
1590
1639
  const eventMaps = []
1640
+ const sources = collectHookSources(pluginRoot, manifest)
1641
+ let rawUsesCodexVars = false
1591
1642
 
1592
- for (const src of collectHookSources(pluginRoot, manifest)) {
1643
+ for (const src of sources) {
1593
1644
  if (src.type === 'file') {
1594
1645
  try {
1595
- const map = extractHookEventMap(readFileSync(src.path, 'utf8'), src.isJson)
1596
- if (map) eventMaps.push(map)
1646
+ const rawText = readFileSync(src.path, 'utf8')
1647
+ const map = extractHookEventMap(rawText, src.isJson)
1648
+ if (map) {
1649
+ eventMaps.push(map)
1650
+ // Inspect raw hook definition before expandPluginVars removes variable tokens.
1651
+ if (CODEX_ENV_VAR_RE.test(rawText)) rawUsesCodexVars = true
1652
+ }
1597
1653
  } catch {}
1598
1654
  } else if (src.type === 'inline') {
1599
1655
  eventMaps.push(src.eventMap)
1656
+ // Inspect raw inline definition before expandPluginVars removes variable tokens.
1657
+ if (valueReferencesCodexEnvVars(src.eventMap)) rawUsesCodexVars = true
1600
1658
  }
1601
1659
  }
1602
1660
 
1603
1661
  for (const eventMap of eventMaps) {
1604
- for (const [eventName, val] of Object.entries(eventMap)) {
1662
+ for (const [rawEventName, val] of Object.entries(eventMap)) {
1663
+ const eventName = canonicalizeHookEventName(rawEventName)
1664
+ if (!eventName) continue
1605
1665
  const rules = Array.isArray(val) ? val : (val && typeof val === 'object' ? [val] : [])
1606
1666
  for (const rule of rules) {
1607
1667
  if (!rule || typeof rule !== 'object') continue
@@ -1610,24 +1670,43 @@ export function compileResolvedHooks(pluginRoot, manifest = readPluginManifest(p
1610
1670
  for (const h of rawInner) {
1611
1671
  if (!h || typeof h !== 'object') continue
1612
1672
  if (h.type === undefined || h.type === 'command') {
1673
+ const hasArgs = Array.isArray(h.args) && h.args.length > 0
1613
1674
  let cmd = typeof h.command === 'string' ? expandPluginVars(h.command, pluginRoot, explicitDataDir).trim() : ''
1614
1675
  if (pluginRoot && /^\.\.?[\\/]/.test(cmd)) {
1615
- const m = cmd.match(/^(\S+)([\s\S]*)$/)
1616
- if (m) {
1617
- const resolvedBin = resolvePluginCommand(m[1], pluginRoot, explicitDataDir)
1618
- cmd = resolvedBin ? `${resolvedBin}${m[2]}` : ''
1676
+ if (hasArgs && !h.shell && isExistingFile(resolve(pluginRoot, cmd))) {
1677
+ cmd = resolvePluginCommand(cmd, pluginRoot, explicitDataDir) || ''
1678
+ } else {
1679
+ const m = cmd.match(/^(\S+)([\s\S]*)$/)
1680
+ if (m) {
1681
+ const resolvedBin = resolvePluginCommand(m[1], pluginRoot, explicitDataDir)
1682
+ cmd = resolvedBin ? `${resolvedBin}${m[2]}` : ''
1683
+ }
1619
1684
  }
1620
1685
  }
1621
- if (Array.isArray(h.args) && h.args.length > 0) {
1622
- const extraArgs = h.args.map((a) => {
1623
- const expanded = expandPluginVars(String(a), pluginRoot, explicitDataDir)
1624
- return formatHookCmdArg(expanded)
1625
- })
1626
- cmd = [cmd, ...extraArgs].filter(Boolean).join(' ')
1627
- }
1628
1686
  if (!cmd) continue
1687
+ let preservedArgs
1688
+ if (hasArgs) {
1689
+ const expandedArgs = h.args.map((a) => expandPluginVars(String(a), pluginRoot, explicitDataDir))
1690
+ const relInPlugin = Boolean(pluginRoot && !isAbsolute(cmd) && /[\\/]/.test(cmd) && isExistingFile(resolve(pluginRoot, cmd)))
1691
+ const isExecForm = !h.shell && (!/\s/.test(cmd) || (isAbsolute(cmd) && isExistingFile(cmd)) || relInPlugin)
1692
+ if (isExecForm) {
1693
+ if (relInPlugin) {
1694
+ cmd = resolvePluginCommand(/^\.\.?[\\/]/.test(cmd) ? cmd : `./${cmd}`, pluginRoot, explicitDataDir) || ''
1695
+ if (!cmd) continue
1696
+ }
1697
+ preservedArgs = expandedArgs
1698
+ } else {
1699
+ cmd = [cmd, ...expandedArgs.map(formatHookCmdArg)].filter(Boolean).join(' ')
1700
+ }
1701
+ }
1629
1702
  const { args: _droppedArgs, ...rest } = h
1630
- compiledInner.push({ ...rest, type: 'command', command: cmd })
1703
+ const normalizedEntry = {
1704
+ ...expandPluginVars(rest, pluginRoot, explicitDataDir),
1705
+ type: 'command',
1706
+ command: cmd,
1707
+ ...(preservedArgs !== undefined ? { args: preservedArgs } : {}),
1708
+ }
1709
+ compiledInner.push(normalizedEntry)
1631
1710
  } else {
1632
1711
  compiledInner.push(expandPluginVars(h, pluginRoot, explicitDataDir))
1633
1712
  }
@@ -1636,6 +1715,7 @@ export function compileResolvedHooks(pluginRoot, manifest = readPluginManifest(p
1636
1715
  if (!compiled[eventName]) compiled[eventName] = []
1637
1716
  compiled[eventName].push({
1638
1717
  ...(rule.matcher !== undefined ? { matcher: rule.matcher } : {}),
1718
+ ...(rule.if !== undefined ? { if: rule.if } : {}),
1639
1719
  hooks: compiledInner,
1640
1720
  })
1641
1721
  }
@@ -1643,7 +1723,22 @@ export function compileResolvedHooks(pluginRoot, manifest = readPluginManifest(p
1643
1723
  }
1644
1724
  }
1645
1725
 
1646
- return Object.keys(compiled).length > 0 ? { hooks: compiled } : null
1726
+ if (Object.keys(compiled).length === 0) return null
1727
+
1728
+ const hasClaudeManifest = Boolean(pluginRoot && existsSync(join(pluginRoot, '.claude-plugin', 'plugin.json')))
1729
+ const hasCodexManifest = Boolean(pluginRoot && existsSync(join(pluginRoot, '.codex-plugin', 'plugin.json')))
1730
+ const hasCodexHookFile = sources.some((src) => src.type === 'file' && /codex/i.test(basename(src.path)))
1731
+ const dialect = (!hasClaudeManifest && (hasCodexManifest || hasCodexHookFile)) ? 'codex' : 'claude-code'
1732
+ const usesCodexEnvVars = dialect === 'codex' || rawUsesCodexVars
1733
+ const resolvedDataDir = pluginDataDirForRoot(pluginRoot, explicitDataDir)
1734
+
1735
+ return {
1736
+ hooks: compiled,
1737
+ pluginRoot: pluginRoot ? resolve(pluginRoot) : '',
1738
+ pluginData: resolvedDataDir ? resolve(resolvedDataDir) : '',
1739
+ dialect,
1740
+ usesCodexEnvVars,
1741
+ }
1647
1742
  }
1648
1743
 
1649
1744
  /**
@@ -1887,15 +1982,86 @@ export function pluginDetail(sourceId, pluginName, source, rowFallback) {
1887
1982
  }
1888
1983
 
1889
1984
  /** Recursively copy a directory (plain JS; avoids shell dependency). */
1890
- export function copyDir(from, to) {
1985
+ export function copyDir(from, to, visited = null) {
1986
+ const seen = visited || new Set()
1987
+ if (!visited) {
1988
+ try { seen.add(realpathSync(from)) } catch {}
1989
+ }
1891
1990
  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)
1991
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
1992
+ const src = join(from, entry.name)
1993
+ const dest = join(to, entry.name)
1994
+ if (entry.isDirectory()) {
1995
+ copyDir(src, dest, seen)
1996
+ } else if (entry.isSymbolicLink()) {
1997
+ let st
1998
+ try { st = statSync(src) } catch { continue }
1999
+ if (st.isDirectory()) {
2000
+ let realDir
2001
+ try { realDir = realpathSync(src) } catch { continue }
2002
+ if (seen.has(realDir)) continue
2003
+ seen.add(realDir)
2004
+ copyDir(src, dest, seen)
2005
+ } else if (st.isFile()) {
2006
+ copyFileSync(src, dest)
2007
+ }
1897
2008
  } else {
1898
2009
  copyFileSync(src, dest)
1899
2010
  }
1900
2011
  }
1901
2012
  }
2013
+
2014
+ /** Recursively copy a directory asynchronously using a bounded concurrent worker pool. */
2015
+ export async function copyDirAsync(from, to, { concurrency = 32, excludeNames = null } = {}) {
2016
+ const seen = new Set()
2017
+ try { seen.add(await realpath(from)) } catch {}
2018
+ const dirs = [to]
2019
+ const files = []
2020
+ async function scan(curFrom, curTo) {
2021
+ const entries = await readdir(curFrom, { withFileTypes: true })
2022
+ for (const entry of entries) {
2023
+ if (excludeNames?.has(entry.name)) continue
2024
+ const src = join(curFrom, entry.name)
2025
+ const dest = join(curTo, entry.name)
2026
+ if (entry.isDirectory()) {
2027
+ dirs.push(dest)
2028
+ await scan(src, dest)
2029
+ } else if (entry.isFile()) {
2030
+ files.push([src, dest])
2031
+ } else if (entry.isSymbolicLink()) {
2032
+ let st
2033
+ try { st = await stat(src) } catch { continue }
2034
+ if (st.isDirectory()) {
2035
+ let realDir
2036
+ try { realDir = await realpath(src) } catch { continue }
2037
+ if (seen.has(realDir)) continue
2038
+ seen.add(realDir)
2039
+ dirs.push(dest)
2040
+ await scan(src, dest)
2041
+ } else if (st.isFile()) {
2042
+ files.push([src, dest])
2043
+ }
2044
+ }
2045
+ }
2046
+ }
2047
+ await scan(from, to)
2048
+ for (const dir of dirs) {
2049
+ await mkdir(dir, { recursive: true })
2050
+ }
2051
+ if (files.length === 0) return
2052
+ let firstErr = null
2053
+ let idx = 0
2054
+ const workerCount = Math.max(1, Math.min(concurrency, files.length))
2055
+ async function worker() {
2056
+ while (!firstErr && idx < files.length) {
2057
+ const [src, dest] = files[idx++]
2058
+ try {
2059
+ await copyFile(src, dest)
2060
+ } catch (err) {
2061
+ if (!firstErr) firstErr = err
2062
+ }
2063
+ }
2064
+ }
2065
+ await Promise.all(Array.from({ length: workerCount }, worker))
2066
+ if (firstErr) throw firstErr
2067
+ }