@visulima/vis 1.0.0-alpha.8 → 1.0.0-alpha.9

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.
Files changed (280) hide show
  1. package/CHANGELOG.md +90 -57
  2. package/LICENSE.md +44 -1
  3. package/README.md +56 -0
  4. package/dist/bin.js +1 -1003
  5. package/dist/config.d.ts +1073 -68
  6. package/dist/config.js +1 -1
  7. package/dist/generate/index.d.ts +155 -30
  8. package/dist/packem_chunks/handler.js +1 -0
  9. package/dist/packem_chunks/handler10.js +1 -0
  10. package/dist/packem_chunks/handler11.js +1 -0
  11. package/dist/packem_chunks/handler12.js +153 -0
  12. package/dist/packem_chunks/handler13.js +1 -0
  13. package/dist/packem_chunks/handler14.js +3 -0
  14. package/dist/packem_chunks/handler15.js +1 -0
  15. package/dist/packem_chunks/handler16.js +2 -0
  16. package/dist/packem_chunks/handler17.js +7 -0
  17. package/dist/packem_chunks/handler18.js +1 -0
  18. package/dist/packem_chunks/handler19.js +19 -0
  19. package/dist/packem_chunks/handler2.js +1 -0
  20. package/dist/packem_chunks/handler20.js +428 -0
  21. package/dist/packem_chunks/handler21.js +22 -0
  22. package/dist/packem_chunks/handler22.js +3 -0
  23. package/dist/packem_chunks/handler23.js +5 -0
  24. package/dist/packem_chunks/handler24.js +1 -0
  25. package/dist/packem_chunks/handler25.js +20 -0
  26. package/dist/packem_chunks/handler26.js +1 -0
  27. package/dist/packem_chunks/handler27.js +1 -0
  28. package/dist/packem_chunks/handler28.js +1 -0
  29. package/dist/packem_chunks/handler29.js +2 -0
  30. package/dist/packem_chunks/handler3.js +2 -0
  31. package/dist/packem_chunks/handler30.js +22 -0
  32. package/dist/packem_chunks/handler31.js +1 -0
  33. package/dist/packem_chunks/handler32.js +1 -0
  34. package/dist/packem_chunks/handler33.js +37 -0
  35. package/dist/packem_chunks/handler34.js +3 -0
  36. package/dist/packem_chunks/handler35.js +23 -0
  37. package/dist/packem_chunks/handler36.js +5 -0
  38. package/dist/packem_chunks/handler37.js +27 -0
  39. package/dist/packem_chunks/handler38.js +1 -0
  40. package/dist/packem_chunks/handler39.js +2 -0
  41. package/dist/packem_chunks/handler4.js +5 -0
  42. package/dist/packem_chunks/handler40.js +1 -0
  43. package/dist/packem_chunks/handler41.js +5 -0
  44. package/dist/packem_chunks/handler42.js +1 -0
  45. package/dist/packem_chunks/handler43.js +24 -0
  46. package/dist/packem_chunks/handler44.js +3 -0
  47. package/dist/packem_chunks/handler45.js +1 -0
  48. package/dist/packem_chunks/handler5.js +4 -0
  49. package/dist/packem_chunks/handler6.js +2 -0
  50. package/dist/packem_chunks/handler7.js +24 -0
  51. package/dist/packem_chunks/handler8.js +6 -0
  52. package/dist/packem_chunks/handler9.js +8 -0
  53. package/dist/packem_shared/VisUpdateApp-BBx3idMI.js +1 -0
  54. package/dist/packem_shared/ai-analysis-DDqXRFxY.js +67 -0
  55. package/dist/packem_shared/bin-BaZZ32BK.js +93 -0
  56. package/dist/packem_shared/cache-directory-DL8hfXeG.js +1 -0
  57. package/dist/packem_shared/catalog-CuSpuB_R.js +12 -0
  58. package/dist/packem_shared/dependency-scan-BoLG2Fez.js +1 -0
  59. package/dist/packem_shared/docker-BcfqH4Av.js +2 -0
  60. package/dist/packem_shared/flakiness-DSIHZGBT.js +1 -0
  61. package/dist/packem_shared/otelPlugin-DxyvBcXO.js +1 -0
  62. package/dist/packem_shared/runtime-check-CGHal8SO.js +1 -0
  63. package/dist/packem_shared/selectors-CfH9ZY08.js +3 -0
  64. package/dist/packem_shared/symbols-CIMw60-G.js +1 -0
  65. package/dist/packem_shared/toolchain-C3ZG0o_X.js +5 -0
  66. package/dist/packem_shared/typosquats-Bpq4zcWL.js +1 -0
  67. package/dist/packem_shared/utils-DrNg0XTR.js +1 -0
  68. package/index.js +555 -727
  69. package/package.json +27 -19
  70. package/schemas/project.schema.json +1 -1
  71. package/schemas/vis-config.schema.json +47 -1
  72. package/dist/ai-analysis.d.ts +0 -26
  73. package/dist/ai-cache.d.ts +0 -21
  74. package/dist/ai-types.d.ts +0 -16
  75. package/dist/audit-config.d.ts +0 -24
  76. package/dist/bin.d.ts +0 -1
  77. package/dist/cache-directory.d.ts +0 -73
  78. package/dist/catalog.d.ts +0 -136
  79. package/dist/codeowners.d.ts +0 -30
  80. package/dist/commands/action-graph.d.ts +0 -8
  81. package/dist/commands/add.d.ts +0 -3
  82. package/dist/commands/affected.d.ts +0 -3
  83. package/dist/commands/ai.d.ts +0 -3
  84. package/dist/commands/analyze.d.ts +0 -3
  85. package/dist/commands/approve-builds.d.ts +0 -3
  86. package/dist/commands/audit.d.ts +0 -23
  87. package/dist/commands/cache.d.ts +0 -86
  88. package/dist/commands/check.d.ts +0 -3
  89. package/dist/commands/ci.d.ts +0 -19
  90. package/dist/commands/clean.d.ts +0 -3
  91. package/dist/commands/create/discovery.d.ts +0 -42
  92. package/dist/commands/create/index.d.ts +0 -13
  93. package/dist/commands/create/prompts.d.ts +0 -31
  94. package/dist/commands/create/random-name.d.ts +0 -15
  95. package/dist/commands/create/templates/builtin.d.ts +0 -15
  96. package/dist/commands/create/templates/generator.d.ts +0 -14
  97. package/dist/commands/create/templates/index.d.ts +0 -13
  98. package/dist/commands/create/templates/monorepo.d.ts +0 -16
  99. package/dist/commands/create/templates/remote.d.ts +0 -41
  100. package/dist/commands/create/templates/types.d.ts +0 -46
  101. package/dist/commands/create/utils.d.ts +0 -42
  102. package/dist/commands/dedupe.d.ts +0 -3
  103. package/dist/commands/devcontainer.d.ts +0 -3
  104. package/dist/commands/dlx.d.ts +0 -3
  105. package/dist/commands/docker.d.ts +0 -22
  106. package/dist/commands/doctor.d.ts +0 -15
  107. package/dist/commands/exec.d.ts +0 -3
  108. package/dist/commands/generate.d.ts +0 -10
  109. package/dist/commands/graph.d.ts +0 -3
  110. package/dist/commands/hook/constants.d.ts +0 -13
  111. package/dist/commands/hook/index.d.ts +0 -3
  112. package/dist/commands/hook/install.d.ts +0 -7
  113. package/dist/commands/hook/list.d.ts +0 -28
  114. package/dist/commands/hook/migrate.d.ts +0 -30
  115. package/dist/commands/hook/prek-builtins.d.ts +0 -8
  116. package/dist/commands/hook/prek.d.ts +0 -129
  117. package/dist/commands/hook/run.d.ts +0 -21
  118. package/dist/commands/hook/uninstall.d.ts +0 -3
  119. package/dist/commands/hook/validate.d.ts +0 -17
  120. package/dist/commands/ignore-helpers.d.ts +0 -157
  121. package/dist/commands/ignore.d.ts +0 -17
  122. package/dist/commands/implode.d.ts +0 -3
  123. package/dist/commands/info.d.ts +0 -3
  124. package/dist/commands/init.d.ts +0 -14
  125. package/dist/commands/install.d.ts +0 -3
  126. package/dist/commands/link.d.ts +0 -3
  127. package/dist/commands/list.d.ts +0 -3
  128. package/dist/commands/migrate/backup.d.ts +0 -8
  129. package/dist/commands/migrate/constants.d.ts +0 -16
  130. package/dist/commands/migrate/deps.d.ts +0 -32
  131. package/dist/commands/migrate/gitleaks.d.ts +0 -29
  132. package/dist/commands/migrate/index.d.ts +0 -3
  133. package/dist/commands/migrate/json.d.ts +0 -22
  134. package/dist/commands/migrate/kingfisher.d.ts +0 -14
  135. package/dist/commands/migrate/lint-staged.d.ts +0 -62
  136. package/dist/commands/migrate/moon.d.ts +0 -5
  137. package/dist/commands/migrate/nano-staged.d.ts +0 -30
  138. package/dist/commands/migrate/nx.d.ts +0 -12
  139. package/dist/commands/migrate/prompt.d.ts +0 -2
  140. package/dist/commands/migrate/secretlint.d.ts +0 -14
  141. package/dist/commands/migrate/shared.d.ts +0 -29
  142. package/dist/commands/migrate/turborepo.d.ts +0 -11
  143. package/dist/commands/migrate/types.d.ts +0 -27
  144. package/dist/commands/migrate/verify.d.ts +0 -12
  145. package/dist/commands/optimize.d.ts +0 -38
  146. package/dist/commands/pm.d.ts +0 -3
  147. package/dist/commands/remove.d.ts +0 -3
  148. package/dist/commands/run.d.ts +0 -16
  149. package/dist/commands/sbom.d.ts +0 -10
  150. package/dist/commands/secrets.d.ts +0 -3
  151. package/dist/commands/sort-package-json.d.ts +0 -3
  152. package/dist/commands/staged.d.ts +0 -10
  153. package/dist/commands/status.d.ts +0 -3
  154. package/dist/commands/sync.d.ts +0 -16
  155. package/dist/commands/task-why.d.ts +0 -3
  156. package/dist/commands/unlink.d.ts +0 -3
  157. package/dist/commands/update.d.ts +0 -3
  158. package/dist/commands/upgrade.d.ts +0 -3
  159. package/dist/commands/why.d.ts +0 -3
  160. package/dist/docker.d.ts +0 -73
  161. package/dist/flakiness.d.ts +0 -40
  162. package/dist/generate/discover.d.ts +0 -29
  163. package/dist/generate/loader.d.ts +0 -15
  164. package/dist/generate/moon-adapter/filename-interp.d.ts +0 -42
  165. package/dist/generate/moon-adapter/filters.d.ts +0 -22
  166. package/dist/generate/moon-adapter/frontmatter.d.ts +0 -39
  167. package/dist/generate/moon-adapter/index.d.ts +0 -19
  168. package/dist/generate/moon-adapter/tera-subset.d.ts +0 -85
  169. package/dist/generate/moon-adapter/util.d.ts +0 -14
  170. package/dist/generate/prompts.d.ts +0 -25
  171. package/dist/generate/remote.d.ts +0 -43
  172. package/dist/generate/runner.d.ts +0 -37
  173. package/dist/generate/types.d.ts +0 -152
  174. package/dist/hooks.d.ts +0 -118
  175. package/dist/native-binding.d.ts +0 -158
  176. package/dist/output.d.ts +0 -40
  177. package/dist/overrides.d.ts +0 -82
  178. package/dist/package-manager.d.ts +0 -23
  179. package/dist/packem_shared/otelPlugin-CJLkguJ8.js +0 -1
  180. package/dist/plugins/config-loader.d.ts +0 -3
  181. package/dist/plugins/otel.d.ts +0 -63
  182. package/dist/plugins/post-command.d.ts +0 -3
  183. package/dist/plugins/security-enforcement.d.ts +0 -3
  184. package/dist/pm-runner.d.ts +0 -44
  185. package/dist/run-report.d.ts +0 -40
  186. package/dist/runtime-check.d.ts +0 -27
  187. package/dist/sbom/cyclonedx.d.ts +0 -39
  188. package/dist/sbom/installed-package.d.ts +0 -49
  189. package/dist/sbom/license.d.ts +0 -31
  190. package/dist/sbom/lockfile.d.ts +0 -34
  191. package/dist/sbom/purl.d.ts +0 -25
  192. package/dist/sbom/resolve-specifier.d.ts +0 -24
  193. package/dist/sbom/types.d.ts +0 -196
  194. package/dist/secrets/baseline.d.ts +0 -20
  195. package/dist/secrets/format.d.ts +0 -14
  196. package/dist/secrets/git.d.ts +0 -6
  197. package/dist/secrets/spinner.d.ts +0 -9
  198. package/dist/security.d.ts +0 -64
  199. package/dist/selectors.d.ts +0 -81
  200. package/dist/shell-history.d.ts +0 -16
  201. package/dist/socket-security.d.ts +0 -129
  202. package/dist/staged/cli-parse.d.ts +0 -18
  203. package/dist/staged/config.d.ts +0 -14
  204. package/dist/staged/errors/apply-empty-commit-error.d.ts +0 -4
  205. package/dist/staged/errors/config-error.d.ts +0 -4
  206. package/dist/staged/errors/get-backup-stash-error.d.ts +0 -4
  207. package/dist/staged/errors/git-error.d.ts +0 -6
  208. package/dist/staged/errors/index.d.ts +0 -12
  209. package/dist/staged/errors/restore-original-state-error.d.ts +0 -4
  210. package/dist/staged/errors/staged-error.d.ts +0 -8
  211. package/dist/staged/errors/task-error.d.ts +0 -6
  212. package/dist/staged/git/diff.d.ts +0 -76
  213. package/dist/staged/git/exec.d.ts +0 -43
  214. package/dist/staged/git/index.d.ts +0 -77
  215. package/dist/staged/git/stash.d.ts +0 -37
  216. package/dist/staged/index.d.ts +0 -13
  217. package/dist/staged/match.d.ts +0 -12
  218. package/dist/staged/renderer/index.d.ts +0 -9
  219. package/dist/staged/renderer/ink/index.d.ts +0 -4
  220. package/dist/staged/renderer/plain.d.ts +0 -12
  221. package/dist/staged/tasks/build.d.ts +0 -13
  222. package/dist/staged/tasks/exec.d.ts +0 -56
  223. package/dist/staged/tasks/run.d.ts +0 -26
  224. package/dist/staged/types.d.ts +0 -173
  225. package/dist/target-discovery.d.ts +0 -59
  226. package/dist/target-options.d.ts +0 -261
  227. package/dist/tips.d.ts +0 -41
  228. package/dist/tui/components/CheckProgressApp.d.ts +0 -6
  229. package/dist/tui/components/CommandSummary.d.ts +0 -17
  230. package/dist/tui/components/Header.d.ts +0 -13
  231. package/dist/tui/components/OutputPanel.d.ts +0 -17
  232. package/dist/tui/components/QuitDialog.d.ts +0 -15
  233. package/dist/tui/components/TaskListPanel.d.ts +0 -19
  234. package/dist/tui/components/TaskRow.d.ts +0 -12
  235. package/dist/tui/components/TaskStore.d.ts +0 -80
  236. package/dist/tui/components/VisTaskRunnerApp.d.ts +0 -17
  237. package/dist/tui/components/devcontainer/DevcontainerStore.d.ts +0 -66
  238. package/dist/tui/components/devcontainer/VisDevcontainerApp.d.ts +0 -9
  239. package/dist/tui/components/devcontainer/catalogs/extensions.d.ts +0 -8
  240. package/dist/tui/components/devcontainer/catalogs/features.d.ts +0 -8
  241. package/dist/tui/components/devcontainer/catalogs/filters.d.ts +0 -4
  242. package/dist/tui/components/devcontainer/catalogs/mount-suggestions.d.ts +0 -19
  243. package/dist/tui/components/devcontainer/catalogs/templates.d.ts +0 -8
  244. package/dist/tui/components/devcontainer/devcontainer-io.d.ts +0 -14
  245. package/dist/tui/components/devcontainer/sections/DockerComposeSection.d.ts +0 -11
  246. package/dist/tui/components/devcontainer/sections/EnvironmentSection.d.ts +0 -16
  247. package/dist/tui/components/devcontainer/sections/ExtensionsSection.d.ts +0 -11
  248. package/dist/tui/components/devcontainer/sections/FeaturesSection.d.ts +0 -11
  249. package/dist/tui/components/devcontainer/sections/GeneralSection.d.ts +0 -12
  250. package/dist/tui/components/devcontainer/sections/LifecycleSection.d.ts +0 -13
  251. package/dist/tui/components/devcontainer/sections/MountsSection.d.ts +0 -16
  252. package/dist/tui/components/devcontainer/sections/PortsSection.d.ts +0 -10
  253. package/dist/tui/components/devcontainer/sections/PreviewPanel.d.ts +0 -11
  254. package/dist/tui/components/devcontainer/types.d.ts +0 -53
  255. package/dist/tui/components/devcontainer/validate.d.ts +0 -16
  256. package/dist/tui/components/graph/GraphStore.d.ts +0 -42
  257. package/dist/tui/components/graph/ProjectDetailPanel.d.ts +0 -10
  258. package/dist/tui/components/graph/ProjectListPanel.d.ts +0 -20
  259. package/dist/tui/components/graph/VisGraphApp.d.ts +0 -8
  260. package/dist/tui/components/optimize/OptimizeDetailPanel.d.ts +0 -9
  261. package/dist/tui/components/optimize/OptimizeListPanel.d.ts +0 -16
  262. package/dist/tui/components/optimize/OptimizeStore.d.ts +0 -50
  263. package/dist/tui/components/optimize/VisOptimizeApp.d.ts +0 -8
  264. package/dist/tui/components/optimize/constants.d.ts +0 -7
  265. package/dist/tui/components/update/PackageDetailPanel.d.ts +0 -12
  266. package/dist/tui/components/update/PackageListPanel.d.ts +0 -21
  267. package/dist/tui/components/update/UpdateStore.d.ts +0 -62
  268. package/dist/tui/components/update/VisUpdateApp.d.ts +0 -18
  269. package/dist/tui/dynamic-life-cycle.d.ts +0 -22
  270. package/dist/tui/formatting-utils.d.ts +0 -17
  271. package/dist/tui/pretty-time.d.ts +0 -8
  272. package/dist/tui/static-life-cycle.d.ts +0 -28
  273. package/dist/tui/status-utils.d.ts +0 -20
  274. package/dist/tui/symbols.d.ts +0 -7
  275. package/dist/tui/types.d.ts +0 -11
  276. package/dist/typosquats.d.ts +0 -70
  277. package/dist/upgrade-check.d.ts +0 -30
  278. package/dist/utils.d.ts +0 -22
  279. package/dist/watch.d.ts +0 -65
  280. package/dist/workspace.d.ts +0 -675
package/dist/bin.js CHANGED
@@ -1,1004 +1,2 @@
1
1
  #!/usr/bin/env node
2
- var ep=Object.defineProperty;var b=(e,t)=>ep(e,"name",{value:t,configurable:!0});import{createRequire as tp}from"node:module";import{createCerebro as np}from"@visulima/cerebro";import op from"@visulima/cerebro/command/completion";import ip from"@visulima/cerebro/compile-cache";import{applyHeapTuning as sp}from"@visulima/cerebro/heap-tuning";import{errorHandlerPlugin as ap}from"@visulima/cerebro/plugins/error-handler";import{isAccessibleSync as E,readFileSync as q,isFsCaseSensitive as cp,walkSync as Un,readJsonSync as ue,ensureDirSync as Se,writeJsonSync as Zi,writeFileSync as Z,removeSync as lp,glob as dp}from"@visulima/fs";import{findPackageManagerSync as Mo,parseLockFileContent as Hc,getPackageManagerVersion as up,findMonorepoRootSync as zc}from"@visulima/package";import{relative as He,join as v,isAbsolute as st,basename as Do,resolve as xe,dirname as Lt,parse as pp,sep as qc}from"@visulima/path";import{createTaskGraph as es,getAffectedProjects as Jc,DEFAULT_CACHE_DIRECTORY_NAME as fp,Cache as Yc,parseCacheSize as gp,projectGraphToDot as mp,runConcurrently as ts,TerminalBuffer as Kc,readLastRunSummary as hp,enforceProjectConstraints as Xc,parsePartition as yp,TaskScheduler as vp,generateRunSummary as Zs,writeChromeTrace as wp,CompositeLifeCycle as ea,defaultTaskRunner as ta,createLogReporter as kp,writeRunSummary as bp}from"@visulima/task-runner";import{dim as $e,green as Ot,yellow as Re,cyan as ut,red as Ge,magenta as Zc,bold as Sr}from"@visulima/colorize";import xp,{coerce as Wn,lt as Sp,rcompare as Cp,parse as jp,validRange as Ep,satisfies as Tp}from"semver";import{hyperlink as Rp}from"@visulima/ansi";import{runProvider as ol,PROVIDER_NAMES as Bp,detectProvider as Fp,detectAvailableProviders as Lp,detectAllProviders as Vp}from"@visulima/find-ai-runner";import{Spinner as ns,Text as l,Box as m,render as Xt,renderToString as Oe,Table as os,useWindowSize as sn,useApp as an,useInput as kt,Dialog as Ar,ScrollView as cn,Tabs as il,Tab as sl,ScrollBar as Gn,TextInput as is,StaticRender as oa}from"@visulima/tui";import Q,{useState as we,useRef as Ue,useEffect as Pt,useCallback as Nt,useSyncExternalStore as Hn,useMemo as Dt}from"react";import{findCacheDirSync as al}from"@visulima/find-cache-dir";import{readYamlSync as ln}from"@visulima/fs/yaml";import{formatBytes as On,duration as ul}from"@visulima/humanizer";import{jsx as u,jsxs as f,Fragment as En}from"react/jsx-runtime";import{getRandomWord as sa}from"@nkzw/safe-word-list";import Wp from"validate-npm-package-name";import{downloadTemplate as pl}from"giget";import{stripJsonComments as Gp}from"@visulima/fs/utils";import{getManifestData as Hp}from"@socketsecurity/registry";import zp from"module-replacements/manifests/micro-utilities.json"with{type:"json"};import qp from"module-replacements/manifests/native.json"with{type:"json"};import Jp from"module-replacements/manifests/preferred.json"with{type:"json"};import{readTomlSync as Yp}from"@visulima/fs/toml";import{parse as Kp}from"yaml";import{findVisConfigFile as dn,loadVisConfig as aa}from"./config.js";import{createHooks as Zp}from"hookable";import{toXML as tf}from"jstoxml";import{fingerprint as Xr,listRules as fl,listRequiredValidators as rf,scan as gl,scanFiles as nf,inspectRuleset as of}from"@visulima/secret-scanner";import{execa as ml}from"execa";import hl from"zeptomatch";const rp=tp(import.meta.url),Kr=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,xt=b(e=>{if(typeof Kr<"u"&&Kr.versions&&Kr.versions.node){const[t,r]=Kr.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return Kr.getBuiltinModule(e)}return rp(e)},"__cjs_getBuiltinModule"),{createInterface:gt}=xt("node:readline"),{platform:Qc,availableParallelism:ra,homedir:Qe,tmpdir:$p}=xt("node:os"),{env:fi,cwd:on,stdin:na,stdout:Ap}=Kr,{readFileSync:el,writeFileSync:me,unlinkSync:Dr,readdirSync:Ve,rmSync:at,statSync:Mt,lstatSync:tl,chmodSync:rl,cpSync:rs,mkdtempSync:Ip,copyFileSync:Op,mkdirSync:Pp,watch:Np}=xt("node:fs"),{createRequire:Mp}=xt("node:module"),{fileURLToPath:Dp,pathToFileURL:nl}=xt("node:url"),{execSync:zn,spawnSync:De,execFileSync:cl,execFile:_p}=xt("node:child_process"),{readdir:ll,stat:dl,realpath:ia,rm:Up,appendFile:ss}=xt("node:fs/promises"),{promisify:Xp}=xt("node:util"),{createInterface:Qp}=xt("node:readline/promises"),{randomUUID:ef}=xt("node:crypto"),{resolve:sf,join:af}=xt("node:path");var cf="1.0.0-alpha.7";const Pn={version:cf};var lf=Object.defineProperty,Ir=b((e,t)=>lf(e,"name",{value:t,configurable:!0}),"g$x");const df=/^#([\w\-/]+):(.+)$/,uf=/^([@\w\-/]+):(.+)$/,pf=Ir(e=>{if(e==="")return;if(e.startsWith(":"))return{kind:"all",target:e.slice(1)};if(e.startsWith("~:"))return{kind:"closest",target:e.slice(2)};const t=df.exec(e);if(t?.[1]&&t[2])return{kind:"tag",tag:t[1],target:t[2]};const r=uf.exec(e);return r?.[1]&&r[2]&&(r[1].startsWith("@")||r[1].includes("/")||r[1].includes("-"))?{kind:"project",projects:[r[1]],target:r[2]}:{kind:"all",target:e}},"parseTargetSelector"),yl=Ir(async(e,t,r,n)=>{const o=pf(e);if(!o)throw new Error(`Invalid target selector: "${e}"`);const i=Object.keys(t.projects);if(o.kind==="all")return{projects:i,target:o.target};if(o.kind==="project")return{projects:o.projects??[],target:o.target};if(o.kind==="tag"){const d=o.tag;return{projects:i.filter(p=>t.projects[p]?.tags?.includes(d)??!1),target:o.target}}const s=He(n,r)||".";let a,c=-1;for(const[d,p]of Object.entries(t.projects)){const g=p.root;g&&(s===g||s.startsWith(`${g}/`))&&g.length>c&&(c=g.length,a=d)}if(!a){if(process.stdout.isTTY){const d=gt({input:process.stdin,output:process.stderr}),p=Object.keys(t.projects).sort();process.stderr.write(`No project found at ${s}. Pick one:
3
- `);for(const[y,w]of p.entries())process.stderr.write(` ${String(y+1)}) ${w}
4
- `);const g=await new Promise(y=>{d.question("> ",y)});d.close();const h=Number.parseInt(g,10)-1;if(h>=0&&h<p.length)return{projects:[p[h]],target:o.target}}throw new Error(`No project found at or above ${s} for selector "${e}".`)}return{projects:[a],target:o.target}},"resolveSelector"),ff=/^(\w+)\s*(!?=)\s*(.+)$/,gf=Ir(e=>{const t=e.trim();if(t==="")return;const r=t.split("&&").map(d=>d.trim()),n=t.split("||").map(d=>d.trim()),o=r.length>1,i=n.length>1;if(o&&i)throw new Error("Query language does not support mixed && / || — split into multiple --query flags or simplify.");const s=i?n:r,a=i?"||":"&&",c=[];for(const d of s){const p=ff.exec(d);if(!p)throw new Error(`Invalid query clause: "${d}". Expected <field>=<value> or <field>!=<value>.`);const[,g,h,y]=p;c.push({field:g,op:h==="!="?"!=":"=",value:y.trim().replaceAll(/^["']|["']$/g,"")})}return{clauses:c,op:a}},"parseQuery"),ca=Ir((e,t,r)=>{const{field:n,op:o,value:i}=e,s=Ir(c=>{const d=c===i;return o==="="?d:!d},"test"),a=Ir(c=>{const d=(c??[]).includes(i);return o==="="?d:!d},"testList");switch(n){case"id":case"project":return s(t);case"language":return s(r.language);case"layer":return s(r.layer);case"projectType":case"type":return s(r.projectType);case"stack":return s(r.stack);case"tag":case"tags":return a(r.tags);default:return!1}},"matchClause"),Bo=Ir((e,t,r)=>{if(!r||r.trim()==="")return e;const n=gf(r);return n?e.filter(o=>{const i=t.projects[o];return i?n.op==="&&"?n.clauses.every(s=>ca(s,o,i)):n.clauses.some(s=>ca(s,o,i)):!1}):e},"filterProjectsByQuery");var mf=Object.defineProperty,St=b((e,t)=>mf(e,"name",{value:t,configurable:!0}),"s$z");const hf=St((e,t=process.env,r=process.platform)=>{if(e===void 0)return!0;if(typeof e=="string"){const n=e.trim();if(n.startsWith("!")){const o=n.slice(1);return!t[o]}if(n.startsWith("$")){const o=n.slice(1);return!!t[o]}return!!t[n]}if(e.platform!==void 0&&!(Array.isArray(e.platform)?e.platform:[e.platform]).includes(r))return!1;if(e.env!==void 0){const n=t[e.env];return e.equals!==void 0?n===e.equals:e.in!==void 0?typeof n=="string"&&e.in.includes(n):!!n}return!0},"evaluateWhen"),yf={server:{cache:!1,interactive:!1,persistent:!0,runInCI:!1},utility:{cache:!1,runInCI:!1}},vf=St(e=>{const t=e.preset??e.options?.preset;if(!t)return e;const r=yf[t];if(!r)return e;const{cache:n,...o}=r;return{...e,cache:e.cache??n,options:{...o,...e.options}}},"applyPreset"),wf=St(e=>{if(e!==void 0)return Array.isArray(e)?e:[e]},"normalizeOsType"),as=St(()=>{const e=Qc();return e==="darwin"?"macos":e==="win32"?"windows":"linux"},"detectCurrentOs"),kf=St((e,t=as())=>{const r=wf(e?.osType);return!r||r.length===0?!0:r.includes(t)},"matchesOs"),bf=St((e,t,r=!0)=>{const n=e?.runInCI??!0;return n===!0||n==="always"?!0:n===!1?!t:n==="affected"?!t||r:!0},"shouldRunInCI"),vl=St((e,t)=>{if(t===!1)return{};const r=t===!0?$f("production"):Array.isArray(t)?t:[t],n={};for(const o of r)Object.assign(n,xf(e,o));return n},"loadEnvFile"),$f=St(e=>{const t=[".env"];return e&&t.push(`.env.${e}`),e!=="test"&&t.push(".env.local"),e&&e!=="test"&&t.push(`.env.${e}.local`),t},"resolveEnvCascade"),xf=St((e,t)=>{const r=t.startsWith("/")?t:v(e,t);if(!E(r))return{};let n;try{n=q(r)}catch{return{}}const o={};for(const i of n.split(/\r?\n/)){const s=i.trim();if(s===""||s.startsWith("#"))continue;const a=s.indexOf("=");if(a===-1)continue;const c=s.slice(0,a).trim();if(c==="")continue;let d=s.slice(a+1).trim();(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))&&(d=d.slice(1,-1)),o[c]=d}return o},"loadSingleEnvFile"),Sf=St((e,t=as())=>{if(e)return t==="windows"&&e.windowsShell?e.windowsShell:(t==="linux"||t==="macos")&&e.unixShell?e.unixShell:e.shell},"resolveTargetShell"),Cf=St(e=>{if(e==="run")return!1;if(e==="build"||e==="test")return!0},"defaultCacheForType");var jf=Object.defineProperty,Ef=b((e,t)=>jf(e,"name",{value:t,configurable:!0}),"s$y");class Br extends Error{static{b(this,"StagedError")}static{Ef(this,"StagedError")}constructor(t,r){super(t,r),this.name=this.constructor.name}}var Tf=Object.defineProperty,Rf=b((e,t)=>Tf(e,"name",{value:t,configurable:!0}),"o$w");class Af extends Br{static{b(this,"ApplyEmptyCommitError")}static{Rf(this,"ApplyEmptyCommitError")}}var If=Object.defineProperty,Of=b((e,t)=>If(e,"name",{value:t,configurable:!0}),"o$v");class $t extends Br{static{b(this,"ConfigError")}static{Of(this,"ConfigError")}}var Pf=Object.defineProperty,Nf=b((e,t)=>Pf(e,"name",{value:t,configurable:!0}),"t$m");class la extends Br{static{b(this,"GetBackupStashError")}static{Nf(this,"GetBackupStashError")}}var Mf=Object.defineProperty,Df=b((e,t)=>Mf(e,"name",{value:t,configurable:!0}),"s$x");class Tn extends Br{static{b(this,"GitError")}static{Df(this,"GitError")}stderr;constructor(t,r,n){super(t,n),this.stderr=r}}var Bf=Object.defineProperty,Ff=b((e,t)=>Bf(e,"name",{value:t,configurable:!0}),"e$b");class da extends Br{static{b(this,"RestoreOriginalStateError")}static{Ff(this,"RestoreOriginalStateError")}}var Lf=Object.defineProperty,Vf=b((e,t)=>Lf(e,"name",{value:t,configurable:!0}),"o$s");class Tr extends Br{static{b(this,"TaskError")}static{Vf(this,"TaskError")}commandTitle;constructor(t,r,n){super(r,n),this.commandTitle=t}}var _f=Object.defineProperty,Fo=b((e,t)=>_f(e,"name",{value:t,configurable:!0}),"i$i");const Uf=Fo(async e=>{if(e.config!==void 0)return e.config;throw new $t(`No staged config provided. Add \`staged\` to your vis.config.ts:
5
-
6
- import { defineConfig } from "@visulima/vis/config";
7
-
8
- export default defineConfig({
9
- staged: { "*.ts": "eslint --fix" },
10
- });
11
-
12
- Coming from lint-staged or nano-staged? Run \`vis migrate lint-staged\` (or \`vis migrate nano-staged\`) to move the config in and remove the legacy files.`)},"resolveConfig"),ua=Fo(e=>{if(typeof e!="object"||e===null)throw new $t("Staged config must be an object mapping glob patterns to tasks.");const t=Object.entries(e);if(t.length===0)throw new $t("Staged config is empty — at least one glob pattern is required.");for(const[r,n]of t){if(!r||r.trim()==="")throw new $t("Staged config keys must be non-empty glob patterns.");wl(r,n)}return e},"validateConfig"),wl=Fo((e,t)=>{if(typeof t=="string"){if(t.trim()==="")throw new $t(`Task for "${e}" is an empty string.`);return}if(Array.isArray(t)){if(t.length===0)throw new $t(`Task array for "${e}" is empty.`);for(const r of t)wl(e,r);return}if(typeof t!="function"&&!Wf(t))throw new $t(`Invalid task for "${e}" — expected string, string[], function, or { title, task } object.`)},"validateTask"),Wf=Fo(e=>typeof e=="object"&&e!==null&&typeof e.title=="string"&&typeof e.task=="function","isCustomTask");var Gf=Object.defineProperty,rr=b((e,t)=>Gf(e,"name",{value:t,configurable:!0}),"n$d");const pa=2048,Te=rr(async(e,t)=>{const r=await ml("git",[...e],{cwd:t.cwd,env:t.env?{...process.env,...t.env}:void 0,input:t.input,reject:!1,stderr:"pipe",stdin:t.input===void 0?"ignore":"pipe",stdout:"pipe"}),n=typeof r.exitCode=="number"?r.exitCode:1;if(n!==0&&!t.lenient){const o=typeof r.stderr=="string"?r.stderr:"",i=o.length>pa?`${o.slice(0,pa)}…`:o;throw new Tn(`git ${e.join(" ")} failed with exit code ${n}: ${i.trim()}`,o)}return{exitCode:n,stderr:typeof r.stderr=="string"?r.stderr:"",stdout:typeof r.stdout=="string"?r.stdout:""}},"git"),un=rr(async(e,t)=>{const{stdout:r}=await Te(e,t);return r.trim()},"gitOut"),Hf=rr(async e=>{const t=await Te(["rev-parse","--is-inside-work-tree"],{cwd:e,lenient:!0});return t.exitCode===0&&t.stdout.trim()==="true"},"isGitRepo"),zf=rr(async e=>un(["rev-parse","--absolute-git-dir"],{cwd:e}),"getGitDirectory"),kl=rr(async e=>un(["rev-parse","--show-toplevel"],{cwd:e}),"getWorkTree"),fa=rr(async e=>un(["write-tree"],{cwd:e}),"writeIndexTree"),qf=rr(async e=>{const t=await Te(["rev-parse","HEAD^{tree}"],{cwd:e,lenient:!0});return t.exitCode===0?t.stdout.trim():""},"headTreeSha"),wn={major:2,minor:32},Jf=rr(e=>{const t=/git version (\d+)\.(\d+)/.exec(e);if(!t)return null;const r=Number.parseInt(t[1]??"",10),n=Number.parseInt(t[2]??"",10);return Number.isNaN(r)||Number.isNaN(n)?null:{major:r,minor:n}},"parseGitVersion"),Yf=rr(async e=>{const t=Jf(await un(["--version"],{cwd:e}));if(t!==null&&(t.major<wn.major||t.major===wn.major&&t.minor<wn.minor))throw new Tn(`Git ${wn.major}.${wn.minor} or newer is required; found ${t.major}.${t.minor}.`)},"assertGitVersion");var Kf=Object.defineProperty,gr=b((e,t)=>Kf(e,"name",{value:t,configurable:!0}),"a$t");const Xf="ACMR",ga=500,Qf=gr(async e=>{const{stdout:t}=await Te(["diff-files","--raw","-z"],{cwd:e}),r=t.split("\0").filter(o=>o.length>0),n=[];for(let o=0;o<r.length;o+=1){const i=r[o];if(!i?.startsWith(":"))continue;const s=i.slice(1).split(" "),a=s[3],c=s[4],d=r[o+1];o+=1,c==="A"&&a!==void 0&&/^0+$/.test(a)&&d!==void 0&&n.push(d)}return n},"getIntentToAddPaths"),ma=gr(async e=>{const{stdout:t}=await Te(["ls-files","--others","--exclude-standard","-z"],{cwd:e});return t.split("\0").filter(r=>r.length>0)},"getUntrackedFiles"),Zf=gr(async(e,t)=>{if(e.length===0)return;const r=`${e.join("\0")}\0`;await Te(["rm","--cached","--quiet","--pathspec-from-file=-","--pathspec-file-nul","--"],{cwd:t.cwd,input:r})},"removeFromIndex"),eg=gr(async e=>{const t=e.diffFilter??Xf,r=e.diff===void 0?["diff","--name-only","-z",`--diff-filter=${t}`,"--staged"]:["diff","--name-only","-z",`--diff-filter=${t}`,...e.diff.split(/\s+/).filter(Boolean)],{stdout:n}=await Te(r,{cwd:e.cwd}),o=n.split("\0").filter(s=>s.length>0);if(o.length===0)return[];const i=e.workTree??await kl(e.cwd);return o.map(s=>st(s)?s:v(i,s))},"getFiles"),tg=gr(async(e,t)=>{if(e.length===0)return null;const r=[];for(let i=0;i<e.length;i+=ga){const s=e.slice(i,i+ga),{stdout:a}=await Te(["diff","--binary","--unified=0","--no-color","--no-ext-diff","--src-prefix=a/","--dst-prefix=b/","--patch","--submodule=short","--",...s],{cwd:t.cwd});a.length>0&&r.push(a)}if(r.length===0)return null;const n=r.join(""),o=n.endsWith(`
13
- `)?n:`${n}
14
- `;return Buffer.from(o,"utf8")},"capturePatch"),rg=gr(async e=>{const{stdout:t}=await Te(["status","--porcelain=v1","-z"],{cwd:e}),r=t.split("\0"),n=[];for(let o=0;o<r.length;o+=1){const i=r[o];if(i===void 0||i.length<4)continue;const s=i.charAt(0),a=i.charAt(1),c=i.slice(3),d=s==="R"||s==="C"||a==="R"||a==="C";s!==" "&&s!=="?"&&a!==" "&&a!=="?"&&n.push(c),d&&(o+=1)}return n},"getPartiallyStagedFiles"),ng=gr(async(e,t)=>{if(e.length===0)return;const r=`${e.join("\0")}\0`;await Te(["checkout","--force","--pathspec-from-file=-","--pathspec-file-nul","--"],{cwd:t.cwd,input:r})},"checkoutPaths"),og=gr(async(e,t)=>{if(await Te(["update-index","--again"],{cwd:t.cwd,lenient:!0}),e.length===0)return;const r=`${e.join("\0")}\0`;await Te(["add","-u","--pathspec-from-file=-","--pathspec-file-nul","--"],{cwd:t.cwd,input:r})},"updateIndexAgain");var ig=Object.defineProperty,Fr=b((e,t)=>ig(e,"name",{value:t,configurable:!0}),"r$s");const sg="vis_staged_automatic_backup",bl=Fr(()=>`${sg}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,"buildMessage"),ag=Fr(async e=>{const t=await un(["stash","create"],{cwd:e});return t.length===0?null:(await Te(["stash","store","-m",bl(),t],{cwd:e}),t)},"createBackupStash"),cg=Fr(async e=>{const t=bl(),{exitCode:r,stdout:n}=await Te(["stash","push","--keep-index","--include-untracked","--quiet","-m",t],{cwd:e,lenient:!0});if(r!==0)return null;const o=n.trim();return o.length>0&&/no local changes/i.test(o)?null:un(["rev-parse","stash@{0}"],{cwd:e})},"createHideAllStash"),cs=Fr(async(e,t)=>{const{exitCode:r,stdout:n}=await Te(["reflog","--format=%H %gd","refs/stash"],{cwd:e,lenient:!0});if(r!==0)return null;for(const o of n.split(/\r?\n/)){const[i,s]=o.split(/\s+/,2);if(i===t&&s!==void 0)return s}return null},"findStashRefBySha"),ha=Fr(async(e,t)=>{if(t===null)return;const r=await cs(e,t);r!==null&&await Te(["stash","drop","--quiet",r],{cwd:e})},"dropBackupStash"),lg=Fr(async(e,t)=>{if(t===null)throw new la("Backup stash was not found — can't revert working tree.");const r=await cs(e,t);if(r===null)throw new la(`Backup stash ${t} is no longer reachable — can't revert working tree.`);await Te(["reset","--hard","HEAD"],{cwd:e}),await Te(["stash","apply","--index","--quiet",r],{cwd:e})},"applyBackupStash"),dg=Fr(async(e,t)=>{if(t===null)return;const r=await cs(e,t);r!==null&&await Te(["stash","pop","--quiet",r],{cwd:e})},"popHideAllStash");var ug=Object.defineProperty,pg=b((e,t)=>ug(e,"name",{value:t,configurable:!0}),"l$t");class fg{static{b(this,"GitWorkflow")}static{pg(this,"GitWorkflow")}stagedFiles=[];partiallyStaged=[];workTree="";gitDir="";preTaskIndexTree="";postTaskIndexTree="";headTree="";revertApplied=!1;warnings=[];cwd;options;patch=null;backupStashSha=null;merge=[];shouldStash;shouldHidePartial;shouldHideUnstaged;shouldHideAll;hideAllStashSha=null;intentToAddPaths=[];preTaskUntracked=new Set;constructor(t){this.cwd=t.cwd??process.cwd(),this.options=t,this.shouldStash=t.stash!==!1&&t.diff===void 0,this.shouldHidePartial=t.hidePartiallyStaged!==!1,this.shouldHideUnstaged=t.hideUnstaged===!0,this.shouldHideAll=t.hideAll===!0}async prepare(){if(!await Hf(this.cwd))throw new Tn(`Not a git repository: ${this.cwd}`);await Yf(this.cwd),this.workTree=await kl(this.cwd),this.gitDir=await zf(this.cwd),this.stagedFiles=await eg({cwd:this.cwd,diff:this.options.diff,diffFilter:this.options.diffFilter,workTree:this.workTree}),this.partiallyStaged=this.stagedFiles.length===0?[]:await rg(this.cwd),this.snapshotMergeState(),this.intentToAddPaths=await Qf(this.workTree),this.intentToAddPaths.length>0&&await Zf(this.intentToAddPaths,{cwd:this.workTree}),this.shouldStash?this.backupStashSha=await ag(this.workTree):this.partiallyStaged.length>0&&this.warnings.push("Running with --no-stash on partially-staged files — unstaged deltas will be captured to a patch, but if re-applying the patch fails after tasks run the changes cannot be recovered."),this.shouldHideAll?this.hideAllStashSha=await cg(this.workTree):await this.hideUnstagedChanges(),this.preTaskIndexTree=this.stagedFiles.length===0?"":await fa(this.workTree),this.postTaskIndexTree=this.preTaskIndexTree,this.headTree=await qf(this.workTree),this.preTaskUntracked=new Set(await ma(this.workTree))}async applyModifications({autoStage:t=!1}={}){if(this.stagedFiles.length===0)return;const r=this.stagedFiles.map(n=>He(this.workTree,n));if(await og(r,{cwd:this.workTree}),t){const n=(await ma(this.workTree)).filter(o=>!this.preTaskUntracked.has(o));if(n.length>0){const o=`${n.join("\0")}\0`;await Te(["add","--pathspec-from-file=-","--pathspec-file-nul","--"],{cwd:this.workTree,input:o})}}if(this.intentToAddPaths.length>0)try{await Te(["add","--intent-to-add","--",...this.intentToAddPaths],{cwd:this.workTree})}catch{}this.postTaskIndexTree=await fa(this.workTree)}indexTreeChanged(){return this.preTaskIndexTree.length>0&&this.postTaskIndexTree.length>0&&this.preTaskIndexTree!==this.postTaskIndexTree}postTaskIndexMatchesHead(){return this.postTaskIndexTree.length>0&&this.headTree.length>0&&this.postTaskIndexTree===this.headTree}async restoreUnstagedChanges(){if(this.revertApplied||this.patch===null||this.shouldHideAll)return;const t=["apply","--whitespace=nowarn","--recount","--unidiff-zero"];let r;try{await Te(t,{cwd:this.workTree,input:this.patch});return}catch(n){r=n instanceof Tn?n.stderr:String(n)}try{await Te([...t,"--3way"],{cwd:this.workTree,input:this.patch})}catch(n){const o=n instanceof Tn&&n.stderr?n.stderr:String(n);throw new da(`Failed to re-apply unstaged changes after running tasks. Original changes remain in the backup stash — recover with \`git stash list\` and \`git stash apply\`.
15
- First attempt: ${r??"(no stderr)"}
16
- Second attempt: ${o}`,{cause:n})}}async revert(){if(this.backupStashSha!==null){try{await lg(this.workTree,this.backupStashSha)}catch(t){throw new da("Revert failed while restoring the backup stash. Use `git stash list` to recover manually.",{cause:t})}if(await ha(this.workTree,this.backupStashSha),this.intentToAddPaths.length>0)try{await Te(["add","--intent-to-add","--",...this.intentToAddPaths],{cwd:this.workTree})}catch{}this.revertApplied=!0}}async cleanup(t){if(this.restoreMergeState(),this.hideAllStashSha!==null)try{await dg(this.workTree,this.hideAllStashSha)}catch{}t&&this.backupStashSha!==null&&!this.revertApplied&&await ha(this.workTree,this.backupStashSha)}recoveryHint(){return this.backupStashSha===null?null:`Backup stash is preserved (sha ${this.backupStashSha.slice(0,7)}) — restore with: git stash apply --index ${this.backupStashSha}`}async hideUnstagedChanges(){const t=new Set(this.stagedFiles.map(n=>He(this.workTree,n))),r=this.shouldHideUnstaged?[...t]:this.shouldHidePartial?this.partiallyStaged.filter(n=>t.has(n)):[];r.length!==0&&(this.patch=await tg(r,{cwd:this.workTree}),this.patch!==null&&await ng(r,{cwd:this.workTree}))}snapshotMergeState(){this.gitDir.length!==0&&(this.merge=["MERGE_HEAD","MERGE_MODE","MERGE_MSG"].map(t=>{const r=v(this.gitDir,t);return E(r)?{body:el(r),existed:!0,name:t}:{body:null,existed:!1,name:t}}))}restoreMergeState(){if(!(this.gitDir.length===0||this.merge.length===0))for(const t of this.merge){const r=v(this.gitDir,t.name);try{t.existed&&t.body!==null?me(r,t.body):E(r)&&Dr(r)}catch{}}}}var gg=Object.defineProperty,Lo=b((e,t)=>gg(e,"name",{value:t,configurable:!0}),"r$r");const $l=Lo(e=>e.includes("/"),"isPathStyle"),$o=Lo((e,t)=>t?e.toLowerCase():e,"normalizeForMatch"),mg=Lo((e,t,r,n={})=>{const o=$l(e),i=n.caseInsensitive===!0,s=$o(e,i),a=[];for(const c of t){const d=o?He(r,c):Do(c);hl(s,$o(d,i))&&a.push(c)}return a},"matchFiles"),hg=Lo((e,t,r,n={})=>{if(!t||t.length===0)return[...e];const o=n.caseInsensitive===!0;return e.filter(i=>{for(const s of t){const a=$l(s)?He(r,i):Do(i),c=$o(s,o);if(hl(c,$o(a,o)))return!1}return!0})},"applyIgnore");var yg=Object.defineProperty,vg=b((e,t)=>yg(e,"name",{value:t,configurable:!0}),"e$a");const wg=vg(()=>process.platform==="win32"?!!process.env.WT_SESSION||process.env.TERM_PROGRAM==="vscode"||process.env.TERM==="xterm-256color":process.env.TERM!=="linux","isUnicodeSupported"),Vo=wg(),_o=Vo?"✓":"√",qn=Vo?"✖":"×",xl=Vo?"…":"...",dr=Vo?"—":"-";var kg=Object.defineProperty,Nn=b((e,t)=>kg(e,"name",{value:t,configurable:!0}),"g$u");const bg=Nn(e=>{switch(e){case"failed":return"red";case"running":return"cyan";case"skipped":return"yellow";case"success":return"green";default:return"gray"}},"colorForStatus"),ya=Nn(e=>{if(e==="running")return u(ns,{type:"dots"});const t=e==="failed"?qn:e==="skipped"?dr:e==="success"?_o:dr;return u(l,{color:bg(e),children:t})},"iconForStatus"),va=Nn(({state:e,tick:t,verbose:r})=>f(m,{flexDirection:"column",children:[[...e.patterns.values()].map(n=>f(m,{flexDirection:"column",children:[f(m,{children:[ya(n.status),f(l,{children:[" ",n.title]})]}),[...n.commands.values()].map(o=>f(m,{flexDirection:"column",marginLeft:2,children:[f(m,{children:[ya(o.status),f(l,{children:[" ",o.title," "]}),o.status!=="pending"&&o.status!=="running"?f(l,{color:"gray",children:["(",o.durationMs,"ms)"]}):null]}),r&&o.output?u(m,{flexDirection:"column",marginLeft:2,children:o.output.split(/\r?\n/).slice(0,20).map((i,s)=>u(l,{color:"gray",children:i},`${o.id}-line-${s}`))}):null,o.status==="failed"&&o.error?u(m,{marginLeft:2,children:u(l,{color:"red",children:o.error.message})}):null]},o.id))]},n.id)),e.infoMessages.map((n,o)=>u(l,{color:"gray",children:n},`info-${o}`)),e.warnMessages.map((n,o)=>u(l,{color:"yellow",children:n},`warn-${o}`)),e.errorMessages.map(({message:n},o)=>u(l,{color:"red",children:n},`err-${o}`))]}),"App"),$g=Nn((e={})=>{const t=e.verbose===!0,r={errorMessages:[],infoMessages:[],patterns:new Map,started:!1,warnMessages:[]};let n=0;const o=Xt(u(va,{state:r,tick:n,verbose:t}),{exitOnCtrlC:!1,stdout:process.stderr}),i=Nn(()=>{n+=1,o.rerender(u(va,{state:r,tick:n,verbose:t}))},"refresh");return{commandEnd({commandId:s,durationMs:a,error:c,output:d,patternId:p,status:g}){const h=r.patterns.get(p)?.commands.get(s);h&&(h.status=g,h.durationMs=a,h.output=d,h.error=c,i())},commandStart({commandId:s,patternId:a}){const c=r.patterns.get(a)?.commands.get(s);c&&(c.status="running",i())},error({error:s,message:a}){r.errorMessages.push({error:s,message:a}),i()},info({message:s}){r.infoMessages.push(s),i()},patternEnd({patternId:s,status:a}){const c=r.patterns.get(s);c&&(c.status=a,i())},patternStart({patternId:s}){const a=r.patterns.get(s);a&&(a.status="running",i())},start({patterns:s}){r.started=!0;for(const a of s){const c=new Map;for(const d of a.commands)c.set(d.id,{durationMs:0,id:d.id,status:"pending",title:d.title});r.patterns.set(a.id,{commands:c,id:a.id,status:"pending",title:a.title})}i()},async stop(){o.unmount(),await o.waitUntilExit()},warn({message:s}){r.warnMessages.push(s),i()}}},"createInkRenderer");var xg=Object.defineProperty,gi=b((e,t)=>xg(e,"name",{value:t,configurable:!0}),"a$s");const wa=gi((e={})=>{const{quiet:t=!1,verbose:r=!1}=e,n=new Map,o=new Map,i=gi(a=>{t||process.stderr.write(`${a}
17
- `)},"print"),s=gi(a=>{switch(a){case"failed":return Ge(qn);case"running":return ut(">");case"skipped":return Re(dr);case"success":return Ot(_o);default:return $e(dr)}},"iconFor");return{commandEnd({commandId:a,durationMs:c,error:d,output:p,status:g}){const h=o.get(a)??a,y=$e(`(${c}ms)`);if(i(` ${s(g)} ${h} ${y}`),g==="failed"&&d&&i($e(d.message)),(g==="failed"||r)&&p&&p.trim().length>0)for(const w of p.split(/\r?\n/))i(` ${$e(w)}`)},commandStart({commandId:a}){if(!r)return;const c=o.get(a)??a;i(` ${$e("…")} ${c}`)},error({error:a,message:c}){t?process.stderr.write(`${Ge(c)}
18
- `):i(Ge(c)),a?.stack&&(r||!t)&&process.stderr.write(`${$e(a.stack)}
19
- `)},info({message:a}){i($e(a))},patternEnd({patternId:a,status:c}){const d=n.get(a)??a;i(`${s(c)} ${d}`)},patternStart({patternId:a}){const c=n.get(a)??a;i(`${ut(">")} ${c}`)},start({patterns:a}){if(a.length===0){i($e("No staged files matched any pattern."));return}const c=new Set(a.flatMap(d=>d.files)).size;i(`${ut(">")} Running staged tasks on ${c} file${c===1?"":"s"} across ${a.length} pattern${a.length===1?"":"s"}`);for(const d of a){n.set(d.id,d.title);for(const p of d.commands)o.set(p.id,p.title)}},stop(){},warn({message:a}){i(Re(a))}}},"createPlainRenderer");var Sg=Object.defineProperty,Cg=b((e,t)=>Sg(e,"name",{value:t,configurable:!0}),"t$k");const jg=Cg(async e=>{const{env:t}=process;if(e.debug===!0||e.quiet===!0||t.NODE_ENV==="test"||t.TERM==="dumb"||t.CI!==void 0||!process.stderr.isTTY)return wa({quiet:e.quiet,verbose:e.verbose});try{return $g({verbose:e.verbose})}catch{return wa({quiet:e.quiet,verbose:e.verbose})}},"pickRenderer");var Eg=Object.defineProperty,Sn=b((e,t)=>Eg(e,"name",{value:t,configurable:!0}),"a$r");const mi=Sn(e=>typeof e=="object"&&e!==null&&typeof e.title=="string"&&typeof e.task=="function","isCustomTask"),Tg=Sn(async e=>{let t=0,r=0;const n=Sn(()=>(t+=1,`pattern-${t}`),"nextPatternId"),o=Sn(()=>(r+=1,`cmd-${r}`),"nextCommandId"),i=Sn(async(a,c,d)=>{if(typeof a=="string"){d.push({command:a,files:c,id:o(),source:"string",title:a});return}if(Array.isArray(a)){for(const p of a)await i(p,c,d);return}if(typeof a=="function"){const p=await a([...c]);if(typeof p=="string"){d.push({command:p,files:c,id:o(),source:"function",title:p});return}if(Array.isArray(p)){for(const g of p)if(typeof g=="string")d.push({command:g,files:c,id:o(),source:"function",title:g});else if(mi(g))d.push({files:c,id:o(),run:g.task,source:"custom",title:g.title});else throw new $t("Task function returned an array with an unsupported entry — expected strings or { title, task }.");return}if(mi(p)){d.push({files:c,id:o(),run:p.task,source:"custom",title:p.title});return}throw new $t("Task function returned an unsupported value — expected string, string[], or { title, task }.")}if(mi(a)){d.push({files:c,id:o(),run:a.task,source:"custom",title:a.title});return}throw new $t("Unsupported task value — expected string, string[], function, or { title, task }.")},"expandTask"),s=[];for(const[a,c]of Object.entries(e.config)){const d=mg(a,e.files,e.cwd,{caseInsensitive:e.caseInsensitive===!0});if(d.length===0)continue;const p=e.relative?d.map(h=>He(e.cwd,h)):d,g=[];await i(c,p,g),g.length!==0&&s.push({commands:g,files:p,id:n(),pattern:a,title:`${a} — ${d.length} file${d.length===1?"":"s"}`})}return s},"buildTaskGraph");var Rg=Object.defineProperty,Uo=b((e,t)=>Rg(e,"name",{value:t,configurable:!0}),"d$E");const Ag=Uo(e=>{const t=[];let r="",n=!1,o=!1;for(let i=0;i<e.length;i+=1){const s=e[i];if(s===void 0)break;if(s==="\\"&&!n&&i+1<e.length){const a=e[i+1];if(a!==void 0){o&&a!=='"'&&a!=="\\"&&(r+=s),r+=a,i+=1;continue}}if(s==='"'&&!n){o=!o;continue}if(s==="'"&&!o){n=!n;continue}if(!n&&!o&&/\s/.test(s)){r.length>0&&(t.push(r),r="");continue}r+=s}if(n||o)throw new $t(`Unterminated ${n?"single":"double"} quote in command: ${e}`);return r.length>0&&t.push(r),t},"parseCommandString"),Sl=process.platform==="win32"?28e3:131072,Ig=Uo((e,t,r)=>{const n=[];let o=[],i=t;const s=r<=0?Sl:r;for(const a of e){const c=Buffer.byteLength(a)+1;o.length>0&&i+c>s&&(n.push(o),o=[],i=t),o.push(a),i+=c}return o.length>0&&n.push(o),n},"chunkFiles"),Og=Uo(async(e,t,r)=>{const n=Ag(e);if(n.length===0)throw new Tr(e,"Empty command for staged task.");const[o,...i]=n;if(o===void 0)throw new Tr(e,"Empty command for staged task.");const s=Buffer.byteLength(o)+i.reduce((p,g)=>p+Buffer.byteLength(g)+1,0),a=Ig(t,s,r.maxArgLength??Sl),c=Date.now(),d=[];for(const p of a){if(r.signal?.aborted===!0)throw new Tr(e,"Task aborted by earlier failure.");const g=await ml(o,[...i,...p],{cancelSignal:r.signal,cwd:r.cwd,env:Pg(r.env),killSignal:r.killSignal??"SIGTERM",reject:!1,stderr:"pipe",stdout:"pipe"}),h=typeof g.stdout=="string"?g.stdout:"",y=typeof g.stderr=="string"?g.stderr:"",w=[h,y].filter(k=>k.length>0).join(`
20
- `);if(w.length>0&&d.push(w),g.isCanceled||g.isTerminated||typeof g.exitCode!="number"){const k=g.isCanceled?"Task aborted by earlier failure.":g.isTerminated?`Task killed by signal ${g.signal??"(unknown)"}.`:w.trim()||"Task exited without a numeric status code.";throw new Tr(e,k)}if(g.exitCode!==0)throw new Tr(e,w.trim()||`Exit code ${g.exitCode} from ${o}`)}return{durationMs:Date.now()-c,output:d.join(`
21
- `)}},"execCommand"),Pg=Uo(e=>{const t={...process.env};return process.stderr.isTTY&&t.FORCE_COLOR===void 0&&t.NO_COLOR===void 0&&(t.FORCE_COLOR="1"),e?{...t,...e}:t},"buildTaskEnv");var Ng=Object.defineProperty,Rr=b((e,t)=>Ng(e,"name",{value:t,configurable:!0}),"o$p");const Mg=Rr(async(e,t,r)=>{const n=Bg(r.concurrent,e.length),o=[],i=new AbortController;let s=!1,a=0;const c=Rr(()=>{s||(s=!0,r.continueOnError||i.abort())},"cancel");r.externalSignal&&(r.externalSignal.aborted?c():r.externalSignal.addEventListener("abort",()=>{c()},{once:!0}));const d=Rr(w=>{for(const k of w.commands)t.commandEnd({commandId:k.id,durationMs:0,patternId:w.id,status:"skipped"})},"emitSkippedCommands"),p=Rr(async w=>{if(s){d(w),t.patternEnd({patternId:w.id,status:"skipped"});return}t.patternStart({patternId:w.id});let k="success";for(const $ of w.commands){if(s){t.commandEnd({commandId:$.id,durationMs:0,patternId:w.id,status:"skipped"}),k=k==="success"?"skipped":k;continue}t.commandStart({commandId:$.id,patternId:w.id});const x=await Dg($,r,i.signal),T=x.status==="failed"&&i.signal.aborted?{...x,status:"skipped"}:x;if(t.commandEnd({commandId:$.id,durationMs:T.durationMs,error:T.error,output:T.output,patternId:w.id,status:T.status}),T.status==="failed"){o.push($.title),k="failed",c();break}if(T.status==="skipped"){k=k==="success"?"skipped":k;break}}t.patternEnd({patternId:w.id,status:k})},"runOne"),g=Rr(async()=>{for(;a<e.length;){const w=e[a];a+=1,w&&await p(w)}},"pickNext"),h=[];for(let w=0;w<Math.min(n,e.length);w+=1)h.push(g());await Promise.all(h);const y=r.externalSignal?.aborted===!0;return{failedCommands:o,success:o.length===0&&!y}},"runTasks"),Dg=Rr(async(e,t,r)=>{const n=Date.now();try{if(e.source==="custom"&&e.run)return await e.run([...e.files]),{durationMs:Date.now()-n,status:"success"};if(e.command){const o=await Og(e.command,e.files,{cwd:t.cwd,killSignal:t.killSignal,maxArgLength:t.maxArgLength,signal:r});return{durationMs:o.durationMs,output:t.verbose?o.output:void 0,status:"success"}}return{durationMs:Date.now()-n,error:new Tr(e.title,"Command has no invocation target."),status:"failed"}}catch(o){const i=o instanceof Error?o:new Error(String(o));return{durationMs:Date.now()-n,error:i,output:i instanceof Tr?i.message:void 0,status:"failed"}}},"runCommand"),Bg=Rr((e,t)=>{if(e===!1)return 1;if(e===!0){const n=Math.max(1,typeof ra=="function"?ra():4);return Math.min(Math.max(1,t),n)}const r=Math.floor(e);return r>0?r:1},"concurrencyLimit");var Fg=Object.defineProperty,Pi=b((e,t)=>Fg(e,"name",{value:t,configurable:!0}),"u$q");const Lg=!0,Vg=Pi(e=>{try{return!cp(e)}catch{return!1}},"detectCaseInsensitive"),_g=Pi(async(e={})=>{const t=e.cwd??process.cwd(),r=await jg(e),n=await Uf(e);typeof n!="function"&&ua(n);const o=new fg({...e,cwd:t}),i=new AbortController;let s=!1;const a=Pi(g=>{if(s){process.removeListener("SIGINT",a),process.removeListener("SIGTERM",a),process.kill(process.pid,g);return}s=!0,r.warn({message:`Received ${g} — cancelling staged tasks and restoring state. Press Ctrl+C again to abort.`}),i.abort()},"onInterrupt");process.on("SIGINT",a),process.on("SIGTERM",a);let c={failedCommands:[],ranTasks:!1,success:!0},d=!1,p=!1;try{await o.prepare(),d=!0;for(const x of o.warnings)r.warn({message:x});if(o.stagedFiles.length===0)return e.allowEmpty!==!0&&r.info({message:"No staged files found."}),p=!0,{failedCommands:[],ranTasks:!1,success:!0};const g=Vg(t),h=hg(o.stagedFiles,e.ignore,t,{caseInsensitive:g});if(h.length===0&&o.stagedFiles.length>0)return r.info({message:"Every staged file was excluded by the `ignore` list."}),p=!0,{failedCommands:[],ranTasks:!1,success:!0};const y=typeof n=="function"?ua(await n([...h])):n,w=await Tg({caseInsensitive:g,config:y,cwd:t,files:h,relative:e.relative});if(r.start({patterns:w}),w.length===0)return r.info({message:"No staged files matched any pattern."}),p=!0,{failedCommands:[],ranTasks:!1,success:!0};const{failedCommands:k,success:$}=await Mg(w,r,{concurrent:e.concurrent??Lg,continueOnError:e.continueOnError===!0,cwd:t,externalSignal:i.signal,killSignal:e.killSignal,maxArgLength:e.maxArgLength,verbose:e.verbose});if(c={failedCommands:k,ranTasks:!0,success:$},$){if(e.diff===void 0&&(await o.applyModifications({autoStage:e.autoStage===!0}),e.failOnChanges===!0&&o.indexTreeChanged()&&(r.warn({message:"Tasks modified staged content — failing because --fail-on-changes is set."}),c={failedCommands:[...k],ranTasks:!0,success:!1}),e.allowEmpty!==!0&&o.postTaskIndexMatchesHead()))throw new Af("All staged changes were reverted by tasks. Re-stage changes or rerun with --allow-empty.")}else if(e.revert===!0)r.info({message:"Reverting working tree from backup stash."}),await o.revert();else{const x=o.recoveryHint();x&&r.warn({message:x})}return await o.restoreUnstagedChanges(),p=c.success,c}catch(g){const h=g instanceof Error?g.message:String(g),y=g instanceof Error?g:new Error(h);if(r.error({error:y,message:h}),g instanceof Br)return{failedCommands:c.failedCommands,ranTasks:c.ranTasks,success:!1};throw g}finally{if(process.removeListener("SIGINT",a),process.removeListener("SIGTERM",a),d)try{await o.cleanup(p)}catch(g){r.error({error:g,message:"Cleanup failed."})}await r.stop()}},"runStaged");var Ug=Object.defineProperty,Je=b((e,t)=>Ug(e,"name",{value:t,configurable:!0}),"c$C");const Wg=/\/+$/,Gg=/\/\*\*$/,Hg=/\/\*\/\*$/,zg=/^['"]|['"]$/g,Cl=/node_modules/,jl=/\.git/,ho=Je(e=>{try{return ue(e)}catch{return}},"readJsonFileSafe"),qg=Je((e,t,r)=>{for(const n of Un(e,{includeFiles:!1,includeSymlinks:!1,skip:[Cl,jl]}))if(n.path!==e&&E(v(n.path,"package.json"))){const o=n.path.slice(e.length+1);r.push(`${t}/${o}`)}},"scanDirectoryRecursive"),Jg=Je((e,t,r)=>{const n=t.slice(0,-2),o=xe(e,n);if(E(o))for(const i of Un(o,{includeFiles:!1,includeSymlinks:!1,maxDepth:1,skip:[Cl,jl]}))i.path!==o&&E(v(i.path,"package.json"))&&r.push(v(n,i.name))},"resolveSimpleGlob"),Yg=Je((e,t,r)=>{const n=t.replace(Gg,"").replace(Hg,""),o=xe(e,n);E(o)&&qg(o,n,r)},"resolveDoubleGlob"),Kg=Je((e,t,r)=>{const n=xe(e,t);E(n)&&E(v(n,"package.json"))&&r.push(t)},"resolveExactDirectory"),Or=Je((e,t)=>{const r=[];for(const n of t){const o=n.replace(Wg,"");o.startsWith("!")||(o.endsWith("/*")?Jg(e,o,r):o.endsWith("/**")||o.endsWith("/*/*")?Yg(e,o,r):Kg(e,o,r))}return r},"resolveWorkspacePatterns"),El=Je((e,t,r=new Set)=>{if(!e)return[];const n=[];for(const o of e){if(typeof o=="object"&&o&&"group"in o){const i=o.group;if(r.has(i))throw new Error(`Cycle detected in vis.config taskGroups: ${[...r,i].join(" → ")}`);const s=t?.[i];if(!s)throw new Error(`Unknown taskGroup "${i}" referenced in dependsOn. Declare it under \`taskGroups\` in vis.config.ts.`);n.push(...El(s,t,new Set([...r,i])));continue}n.push(o)}return n},"expandTaskGroups"),Tl=Je(e=>{if(Array.isArray(e)){if(e.length===0)throw new Error('Invalid package.json `workspaces`: empty array. Add at least one pattern like "packages/*" or remove the field.');for(const t of e)if(typeof t!="string"||t.trim().length===0)throw new TypeError(`Invalid package.json \`workspaces\` entry: expected a non-empty glob string, got ${JSON.stringify(t)}.`);return e}if(e&&typeof e=="object"){const{packages:t}=e;if(t===void 0)throw new Error('Invalid package.json `workspaces`: object form requires a `packages` array (e.g. `{ "packages": ["packages/*"] }`).');if(!Array.isArray(t))throw new TypeError(`Invalid package.json \`workspaces.packages\`: expected an array of glob strings, got ${typeof t}.`);return Tl(t)}throw new TypeError(`Invalid package.json \`workspaces\`: expected an array or { packages: string[] } object, got ${typeof e}.`)},"validateWorkspacesField"),Wo=Je(e=>{const t=v(e,"pnpm-workspace.yaml");if(!E(t))return;const r=q(t),n=[];let o=!1;for(const i of r.split(`
22
- `)){const s=i.trim();if(s==="packages:"){o=!0;continue}if(o){if(s.startsWith("- ")){const a=s.slice(2).replaceAll(zg,"");n.push(a)}else if(s&&!s.startsWith("#"))break}}return n.length>0?n:void 0},"readPnpmWorkspacePatterns"),ka="@filegroup:",Xg=Je((e,t,r)=>{if(!e)return!0;if(e.projectType&&e.projectType!==r)return!1;if(e.tags&&e.tags.length>0){const n=new Set(t?.tags);if(!e.tags.some(o=>n.has(o)))return!1}if(e.layer){const n=Array.isArray(e.layer)?e.layer:[e.layer];if(t?.layer===void 0||!n.includes(t.layer))return!1}if(e.stack){const n=Array.isArray(e.stack)?e.stack:[e.stack];if(t?.stack===void 0||!n.includes(t.stack))return!1}if(e.language){const n=Array.isArray(e.language)?e.language:[e.language];if(t?.language===void 0||!n.includes(t.language))return!1}return!0},"scopeMatches"),Qg=Je((e,t,r)=>{const n={};for(const[o,i]of Object.entries(e.targetDefaults??{}))n[o]={...i};for(const o of e.taskDefaults??[])if(Xg(o.scope,t,r))for(const[i,s]of Object.entries(o.targets))n[i]={...n[i],...s};return n},"collectTargetDefaults"),Zg=Je((e,t)=>{if(!e)return e;const r=[];for(const n of e){if(typeof n=="string"&&n.startsWith(ka)){const o=n.slice(ka.length),i=t?.[o];i&&r.push(...i);continue}r.push(n)}return r},"resolveFileGroupInputs"),ba=Je((e,t,r,n,o)=>{const i={...n,...r,options:{...n?.options,...r?.options}};t&&i.command===void 0&&i.executor===void 0&&(i.command=t),i.inputs&&(i.inputs=Zg(i.inputs,o));const s=vf(i);return s.cache===void 0&&(s.cache=Cf(s.type)),s},"mergeTarget"),em=Je((e,t,r,n)=>{const o={},i=new Set;for(const[s,a]of Object.entries(e??{}))i.add(s),o[s]=ba(s,a,t?.[s],r[s],n);for(const[s,a]of Object.entries(t??{}))i.has(s)||(o[s]=ba(s,void 0,a,r[s],n));return o},"createTargetsFromScripts"),mt=Je((e,t={})=>{const r={},n=new Map,o=new Map,i=Wo(e),s=ho(v(e,"package.json"));let a;if(i?a=i:s?.workspaces!==void 0&&(a=Tl(s.workspaces)),!a)throw new Error("No workspace configuration found. Expected pnpm-workspace.yaml or package.json workspaces field.");const c=Or(e,a);for(const d of c){const p=v(e,d,"package.json"),g=ho(p);if(!g?.name)continue;o.set(g.name,g);const h=v(e,d,"project.json"),y=ho(h);let w="library";y?.projectType?w=y.projectType:g.bin!==void 0&&(w="application");const k=Qg(t,y,w),$=em(g.scripts,y?.targets,k,t.fileGroups);n.set(g.name,$);const x={};for(const[T,I]of Object.entries($)){const{options:P,preset:R,type:M,...L}=I,U=I.dependsOn?El(I.dependsOn,t.taskGroups):void 0;x[T]={...L,...U?{dependsOn:U}:{},...P?{options:P}:{}}}r[g.name]={implicitDependencies:y?.implicitDependencies,language:y?.language,layer:y?.layer,owners:y?.owners,project:y?.project,projectType:w,root:d,sourceRoot:y?.sourceRoot??`${d}/src`,stack:y?.stack,tags:y?.tags,targets:x}}return{config:t,packageJsons:o,projectOptions:n,workspace:{projects:r}}},"discoverWorkspace"),nr=Je((e,t,r)=>{const n={},o={},i=new Set(Object.keys(t.projects));for(const[s,a]of Object.entries(t.projects)){n[s]={data:a,name:s,type:a.projectType??"library"},o[s]=[];const c=r?.get(s)??ho(v(e,a.root,"package.json"));if(!c)continue;const d=[[c.dependencies,"static"],[c.devDependencies,"devDependency"],[c.peerDependencies,"peerDependency"]],p=new Set;for(const[g,h]of d)if(g)for(const y of Object.keys(g))i.has(y)&&!p.has(y)&&(p.add(y),o[s]?.push({source:s,target:y,type:h}))}return{dependencies:o,nodes:n}},"buildProjectGraph");var tm=Object.defineProperty,xo=b((e,t)=>tm(e,"name",{value:t,configurable:!0}),"u$p");const rm=xo((e,t,r)=>{const n=[],o=new Set,i=xo((s,a)=>{if(o.has(s))return;o.add(s);const c=t[s]??[];for(const g of c)i(g,a+1);const d=r[s],p=" ".repeat(a);n.push(`${p}${s}${d?.cache===!1?" (no-cache)":""}`)},"walk");for(const s of e)i(s,0);return n},"renderPlan"),nm=xo((e,t,r)=>({roots:e,tasks:Object.fromEntries(Object.entries(r).map(([n,o])=>[n,{cache:o.cache,dependsOn:t[n]??[],outputs:o.outputs,parallelism:o.parallelism,projectRoot:o.projectRoot,target:o.target}]))}),"toJson"),om={argument:{description:"Target selector (same syntax as `vis run`): `build`, `:build`, `~:test`, `#tag:lint`, …",name:"selector",type:String},description:"Show the execution plan for a target without running it",examples:[["vis action-graph build","Print the task plan for `build` on every project"],["vis action-graph :test","Moon-style selector"],["vis action-graph build --json","Emit a JSON description of the plan"],['vis action-graph lint --query "tag=frontend"',"Filter projects by query"]],execute:xo(async({argument:e,logger:t,options:r,visConfig:n,workspaceRoot:o})=>{const i=e[0];if(!i)throw new Error("Missing selector. Usage: vis action-graph <selector>");if(!o)throw new Error("Could not determine workspace root. Run inside a monorepo.");const{config:s,packageJsons:a,workspace:c}=mt(o,n),d=nr(o,c,a),p=await yl(i,c,process.cwd(),o),{target:g}=p;let h=p.projects;r.query&&(h=Bo(h,c,r.query));const y=h.filter(x=>c.projects[x]?.targets?.[g]!==void 0);if(y.length===0){t.info(`No projects have a "${g}" target.`);return}const w=y.map(x=>{const T=c.projects[x],I=T.targets?.[g],P={project:x,target:g};return{cache:I?.cache,id:`${x}:${g}`,outputs:I?.outputs??[],overrides:{command:I?.command},parallelism:I?.parallelism,projectRoot:T.root,target:P}}),k=es(w,{projectGraph:d,targetDefaults:s.targetDefaults,workspace:c});if(r.json){t.info(JSON.stringify(nm(k.roots,k.dependencies,k.tasks),null,2));return}const $=rm(k.roots,k.dependencies,k.tasks);t.info(`Execution plan (${Object.keys(k.tasks).length} task(s), ${k.roots.length} root(s)):`),t.info("");for(const x of $)t.info(x)},"execute"),group:"Workspace",name:"action-graph",options:[{defaultValue:!1,description:"Emit JSON instead of ASCII",name:"json",type:Boolean},{description:"Filter matched projects by a query",name:"query",type:String}]};var im=Object.defineProperty,sm=b((e,t)=>im(e,"name",{value:t,configurable:!0}),"t$j");const $a=sm(e=>e in fi&&fi[e]!=="0"&&fi[e]!=="false","check"),ft=$a("CI")||$a("CONTINUOUS_INTEGRATION");var am=Object.defineProperty,ct=b((e,t)=>am(e,"name",{value:t,configurable:!0}),"r$p");const cm=ct(()=>process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:!!process.stderr.isTTY,"supportsColor"),lm=cm(),mr=ct((e,t)=>r=>lm?`\x1B[${e}m${r}\x1B[${t}m`:r,"ansi"),ve=mr("1","22"),re=mr("2","22"),Rl=mr("31","39"),Al=mr("32","39"),Il=mr("33","39"),dm=mr("34","39"),Fe=mr("36","39"),um=mr("90","39"),pm=ct(()=>process.platform==="win32"?!!process.env.WT_SESSION||process.env.TERM_PROGRAM==="vscode"||process.env.TERM==="xterm-256color":process.env.TERM!=="linux","isUnicodeSupported"),hi=pm(),ls={arrow:hi?"→":"->",failure:hi?"✗":"x",success:hi?"✓":"v"},S=ct(e=>{process.stderr.write(`${ve(dm("info:"))} ${e}
23
- `)},"info"),se=ct(e=>{process.stderr.write(`${ve(Il("warn:"))} ${e}
24
- `)},"warn"),ur=ct(e=>{process.stderr.write(`${ve(Rl("error:"))} ${e}
25
- `)},"error"),ie=ct(e=>{process.stderr.write(`${ve(um("note:"))} ${e}
26
- `)},"note"),ee=ct(e=>{process.stderr.write(`${Al(ls.success)} ${e}
27
- `)},"success"),Ze=ct(e=>{process.stderr.write(`${Rl(ls.failure)} ${e}
28
- `)},"failure");ct((e,t)=>!process.stderr.isTTY||process.env.TERM==="dumb"?e===t?t:`${e} (${re(t)})`:Rp(e,t),"link");const fm=ct(()=>{if(process.env.VIS_VERSION)return process.env.VIS_VERSION;try{const e=new URL("../../package.json",import.meta.url);return ue(e).version}catch{return"0.0.0"}},"getVersion"),gm=ct(()=>{process.env.VIS_VERSION=fm()},"injectVersion"),mm=ct(e=>{!process.stdout.isTTY||ft||process.env.TERM==="dumb"||process.stdout.write(`\x1B]0;${e}\x07`)},"setTerminalTitle");var hm=Object.defineProperty,Ol=b((e,t)=>hm(e,"name",{value:t,configurable:!0}),"n$c");const ym=1;let so,xa=!1;const vm=Mp(import.meta.url),Go=Ol(()=>{if(xa)return so;xa=!0;try{const e=vm("../index.js");typeof e.detectPackageManager=="function"&&typeof e.execPmCommand=="function"&&typeof e.resolveLink=="function"&&e.NATIVE_BINDING_VERSION===ym&&(so=e)}catch{so=void 0}return so},"loadNativeBindings");Ol(()=>Go()!==void 0,"isNativeAvailable");var wm=Object.defineProperty,Be=b((e,t)=>wm(e,"name",{value:t,configurable:!0}),"t$g");const ds=Be(()=>{const e=Go();if(!e)throw new Error("Native bindings for package manager operations failed to load. Ensure the correct platform binary is installed.");return e},"requireNative"),ao=Be((e,t)=>{try{const r=v(e,"package.json");if(E(r)){const n=ue(r);if(n.packageManager?.startsWith(`${t}@`))return n.packageManager.slice(t.length+1)}}catch{}},"readPackageManagerVersion"),km=Be(e=>{let t;try{t=new Set(Ve(e))}catch{return}if(t.has("pnpm-lock.yaml")||t.has("pnpm-workspace.yaml"))return{name:"pnpm",version:ao(e,"pnpm")??"latest"};if(t.has("yarn.lock"))return{name:"yarn",version:ao(e,"yarn")??"latest"};if(t.has("bun.lock")||t.has("bun.lockb"))return{name:"bun",version:ao(e,"bun")??"latest"};if(t.has("package-lock.json")||t.has("npm-shrinkwrap.json"))return{name:"npm",version:ao(e,"npm")??"latest"};if(t.has("package.json"))try{const r=ue(v(e,"package.json"));if(r.packageManager){const n=/^(pnpm|yarn|npm|bun)@(.+)$/.exec(r.packageManager);if(n)return{name:n[1],version:n[2]}}}catch{}},"detectPmInDir"),bm=Be(e=>{let t=e;for(;;){const r=km(t);if(r)return r;const n=Lt(t);if(n===t||pp(t).root===t)break;t=n}throw new Error(`Could not detect package manager in ${e}. No lockfile or packageManager field found.`)},"detectPmFallback"),Ne=Be(e=>{if(!E(e))throw new Error(`Could not detect package manager in ${e}. Directory does not exist.`);try{const t=ds().detectPackageManager(e);return{name:t.name,version:t.version||"latest"}}catch{return bm(e)}},"detectPm"),Pl=Be((e,t,r)=>{for(const n of e.warnings)r.warn(`warning: ${n}`);return ds().execPmCommandInteractive(e.bin,e.args,t)},"runResolved"),Ct=Be((e,t,r)=>{const n=e(ds());return Pl(n,t,r)},"resolveAndRun"),Ho=Be((e,t,r,n)=>Ct(o=>o.resolveInstall(e.name,e.version,t),r,n),"runInstall"),$m=Be((e,t,r,n)=>Ct(o=>o.resolveAdd(e.name,e.version,t),r,n),"runAdd"),xm=Be((e,t,r,n)=>Ct(o=>o.resolveRemove(e.name,e.version,t),r,n),"runRemove"),Sm=Be((e,t,r,n)=>Ct(o=>o.resolveDedupe(e.name,e.version,t),r,n),"runDedupe"),Cm=Be((e,t,r,n)=>Ct(o=>o.resolveWhy(e.name,e.version,t),r,n),"runWhy");Be((e,t,r,n)=>Ct(o=>o.resolveOutdated(e.name,e.version,t),r,n),"runOutdated");const jm=Be((e,t)=>{const r=[],n=[],o=e.name;switch(e.name){case"bun":{const i=Wn(e.version);i&&Sp(i,"1.3.0")&&n.push(`bun ${e.version} does not support \`bun pm view\` (added in bun 1.3). Upgrade bun, or run \`npm view ${t.package}\` instead.`),r.push("pm","view","--",t.package,...t.fields),t.json&&r.push("--json");break}case"npm":case"pnpm":{r.push("view","--",t.package,...t.fields),t.json&&r.push("--json");break}case"yarn":{if(e.version.startsWith("1.")){r.push("info","--",t.package);const[i,...s]=t.fields;i!==void 0&&(s.length>0&&n.push("yarn v1 only supports querying one field at a time; using the first."),r.push(i)),t.json&&r.push("--json")}else r.push("npm","info","--",t.package),t.fields.length>0&&n.push("yarn berry does not support field arguments to 'npm info'; ignoring."),t.json&&r.push("--json");break}default:{const i=e.name;throw new Error(`Unsupported package manager: ${i}`)}}return{args:r,bin:o,warnings:n}},"resolveInfo"),Em=Be((e,t,r,n)=>Pl(jm(e,t),r,n),"runInfo"),Tm=Be((e,t,r,n)=>Ct(o=>o.resolveLink(e.name,e.version,t),r,n),"runLink"),Rm=Be((e,t,r,n,o)=>Ct(i=>i.resolveUnlink(e.name,e.version,t,r),n,o),"runUnlink"),us=Be((e,t,r,n)=>Ct(o=>o.resolveDlx(e.name,e.version,t),r,n),"runDlx"),Am=Be((e,t,r,n)=>Ct(o=>o.resolveExec(e.name,e.version,t),r,n),"runExec"),Im=Be((e,t,r,n,o)=>Ct(i=>i.resolvePmCommand(e.name,e.version,t,r),n,o),"runPmSubcommand");var Om=Object.defineProperty,_e=b((e,t)=>Om(e,"name",{value:t,configurable:!0}),"a$o");const Pm="https://api.socket.dev/v0/purl?alerts=true",zo=_e(()=>v(Qe(),".vis","cache","socket-security"),"getCacheDirectory"),Nm=3600*1e3,lr=.4,Sa=100,Mm=_e(e=>typeof e=="object"&&e!=null&&"id"in e&&"type"in e&&"name"in e&&"version"in e&&"alerts"in e&&"score"in e&&e.type==="npm","isPackageReportData"),Dm=_e(()=>{Se(zo())},"ensureCacheDirectory"),Nl=_e((e,t)=>`${encodeURIComponent(e)}@${encodeURIComponent(t)}`,"buildCacheKey"),Bm=_e((e,t)=>{const r=Nl(e,t),n=v(zo(),`${r}.json`);try{const o=ue(n);if(Date.now()-o.createdAt>o.ttlMs){at(n,{force:!0});return}return o.report}catch{return}},"getCachedReport"),Fm=_e((e,t,r,n)=>{const o=Nl(e,t),i={createdAt:Date.now(),report:r,ttlMs:n};me(v(zo(),`${o}.json`),JSON.stringify(i),"utf8")},"setCachedReport"),Lm=_e(e=>{const t=[e.license,e.maintenance,e.quality,e.supplyChain,e.vulnerability];return Number((t.reduce((r,n)=>r+n,0)/t.length).toFixed(2))},"calculateOverallScore"),pn=_e(async(e,t={})=>{const{apiToken:r,cacheTtlMs:n=Nm,timeoutMs:o=15e3}=t,i=new Map;if(e.length===0||!r)return i;const s=[];for(const d of e){const p=Bm(d.name,d.version);p?i.set(`${d.name}@${d.version}`,p):s.push(d)}if(s.length===0)return i;const a=`Basic ${Buffer.from(`${r}:`).toString("base64")}`;Dm();const c=[];for(let d=0;d<s.length;d+=Sa)c.push(s.slice(d,d+Sa));for(const d of c){const p=d.map(y=>({purl:`pkg:npm/${y.name}@${y.version}`})),g=new AbortController,h=setTimeout(()=>{g.abort()},o);try{const y=await fetch(Pm,{body:JSON.stringify({components:p}),headers:{Authorization:a,"Content-Type":"application/json","User-Agent":"@visulima/vis"},method:"POST",signal:g.signal});if(!y.ok)continue;const w=await y.text();Vm(w,d,i,n)}catch{}finally{clearTimeout(h)}}return i},"fetchSocketReports"),Vm=_e((e,t,r,n)=>{const o=new Map;for(const s of t)o.set(`${s.name}@${s.version}`,s);const i=e.split(`}
29
- `);for(const s of i){const a=s.trim();if(a)try{const c=JSON.parse(a.endsWith("}")?a:`${a}}`),d=`${c.namespace?`${c.namespace}/`:""}${c.name}`,p=`${d}@${c.version}`;if(!o.has(p))continue;const g=c.score.overall??Lm(c.score),h={alerts:c.alerts,author:c.author,id:c.id,license:c.license,name:c.name,score:{...c.score,overall:g},size:c.size,type:"npm",version:c.version};c.namespace&&(h.namespace=c.namespace),Mm(h)&&(r.set(p,h),Fm(d,c.version,h,n))}catch{}}},"parseNdjsonResponse"),en=_e(e=>e.namespace?`${e.namespace}/${e.name}`:e.name,"getFullPackageName"),ps=_e(e=>e>=.8?"excellent":e>=.6?"good":e>=.4?"fair":e>=.2?"poor":"critical","scoreLabel"),Jn=_e(e=>e>=.6?"green":e>=.4?"yellow":"red","scoreColor"),Ca=_e(e=>{const t=en(e),r=`score: ${String(Math.round(e.score.overall*100))}%`,n=e.alerts.length,o=n>0?`${String(n)} alert${n===1?"":"s"}`:"no alerts";return`${t}@${e.version} (${r}, ${o})`},"formatReportSummary");_e(e=>{const t=[`${en(e)}@${e.version}`,` License: ${e.license||"unknown"}`];if(t.push(` Overall Score: ${String(Math.round(e.score.overall*100))}% (${ps(e.score.overall)})`),t.push(` Supply Chain: ${String(Math.round(e.score.supplyChain*100))}%`),t.push(` Quality: ${String(Math.round(e.score.quality*100))}%`),t.push(` Maintenance: ${String(Math.round(e.score.maintenance*100))}%`),t.push(` Vulnerability: ${String(Math.round(e.score.vulnerability*100))}%`),t.push(` License: ${String(Math.round(e.score.license*100))}%`),e.alerts.length>0){t.push(` Alerts (${String(e.alerts.length)}):`);for(const r of e.alerts){const n=r.props?.cveId?` (${r.props.cveId})`:"";t.push(` [${r.severity.toUpperCase()}] ${r.type}${n} — ${r.category}`)}}return t.join(`
30
- `)},"formatReportDetailed");const _m=_e(e=>{if(e.size===0)return"";let t=0,r=0,n=0,o=0,i=0,s=0;for(const c of e.values()){for(const d of c.alerts)switch(t++,d.severity){case"critical":{r++;break}case"high":{n++;break}case"medium":{o++;break}default:i++}c.score.overall<lr&&s++}const a=[];if(a.push(`Socket.dev: scanned ${String(e.size)} package${e.size===1?"":"s"}`),t>0){const c=[];r>0&&c.push(`${String(r)} critical`),n>0&&c.push(`${String(n)} high`),o>0&&c.push(`${String(o)} medium`),i>0&&c.push(`${String(i)} low`),a.push(` Alerts: ${String(t)} total (${c.join(", ")})`)}else a.push(" No security alerts found.");return s>0&&a.push(` ${String(s)} package${s===1?"":"s"} with low security score (<40%)`),a.join(`
31
- `)},"formatSecurityOverview"),Um=_e(()=>{const e=zo();if(!E(e))return 0;const t=Ve(e).filter(r=>r.endsWith(".json"));for(const r of t)at(v(e,r),{force:!0});return t.length},"clearSocketCache"),Lr=_e(e=>e?.enabled?{apiToken:e.apiToken??process.env.VIS_SOCKET_TOKEN,cacheTtlMs:e.cacheTtlMs,minimumScore:e.minimumScore,timeoutMs:e.timeoutMs}:void 0,"buildSocketOptions"),fs=_e((e,t,r)=>{if(!r)return;const n=`${e}@${t}`;if(r[n])return r[n];if(r[e])return r[e];for(const[o,i]of Object.entries(r))if(o.endsWith("*")&&e.startsWith(o.slice(0,-1)))return i},"findAcceptedRisk"),Wm=_e((e,t,r,n)=>[" // Add to security.socket.acceptedRisks in vis.config.ts:",` ${`"${e}"`}: {`,` reason: "${n}",`,` acceptedAt: "${new Date().toISOString()}",`,` acceptedScore: ${String(r)},`," },"].join(`
32
- `),"formatAcceptedRiskSnippet");var Gm=Object.defineProperty,ht=b((e,t)=>Gm(e,"name",{value:t,configurable:!0}),"o$m");const Hm={a:["4","e"],b:["d"],d:["b"],e:["3","a"],g:["9","q"],i:["1","l"],l:["1","i"],m:["n"],n:["m"],o:["0"],s:["5","z"],t:["7"],u:["v"],v:["u"]},zm=ht(e=>{const t=new Set;if(e.length<3)return t;for(let n=0;n<e.length;n++){const o=e[n]==="-"||e[n]==="."||e[n]==="_";if(o||t.add(e.slice(0,n)+e.slice(n+1)),o||t.add(e.slice(0,n)+e[n]+e.slice(n)),n<e.length-1&&e[n]!==e[n+1]){const a=e[n+1]==="-"||e[n+1]==="."||e[n+1]==="_";if(!o&&!a){const c=e.split("");[c[n],c[n+1]]=[c[n+1],c[n]],t.add(c.join(""))}}const i=e[n].toLowerCase(),s=Hm[i];if(s)for(const a of s)t.add(e.slice(0,n)+a+e.slice(n+1))}const r=/[-._]/g;if(r.test(e))t.add(e.replaceAll(r,"")),t.add(e.replaceAll(r,"-")),t.add(e.replaceAll(r,".")),t.add(e.replaceAll(r,"_"));else if(e.length>5)for(let n=2;n<e.length-2;n++)t.add(`${e.slice(0,n)}-${e.slice(n)}`),t.add(`${e.slice(0,n)}.${e.slice(n)}`),t.add(`${e.slice(0,n)}_${e.slice(n)}`);return e.startsWith("@")||(t.add(`${e}-js`),t.add(`${e}js`),t.add(`${e}-node`)),t.delete(e),t},"generateVariants");let yi,co;const Ml=ht(()=>{if(!yi){const e=xe(Lt(Dp(import.meta.url)),"../data/typosquats.json");yi=ue(e)}return yi},"loadBlocklist"),qm=ht(()=>{if(!co){co=new Map;for(const[e,t]of Object.entries(Ml()))for(const r of t)co.set(r,e)}return co},"getReverseLookup"),Jm=ht(e=>e.startsWith("@")?e.split("/")[1]??e:e,"bareName"),Ym=ht(e=>{const t=Jm(e),r=qm().get(t);if(r)return{input:e,legitimate:r,method:"blocklist"};for(const n of Object.keys(Ml()))if(zm(n).has(t))return{input:e,legitimate:n,method:"heuristic"}},"checkTyposquat"),Dl=ht((e,t)=>{const r=t?new Set(t):void 0,n=[];for(const o of e){if(r?.has(o))continue;const i=Ym(o);i&&n.push(i)}return n},"checkTyposquats"),Bl=ht((e,t)=>{se(""),se(Ge(`Possible typosquat${e.length===1?"":"s"} ${t}:`));for(const r of e){const n=r.method==="blocklist"?"known typosquat":"similar name";se(` ${Re("⚠")} ${Ge(r.input)} — did you mean ${Re(r.legitimate)}? (${n})`)}se("")},"printTyposquatWarnings"),Fl=ht(async e=>{if(!process.stdin.isTTY){se("Aborting: potential typosquat detected in non-interactive mode. Use --no-typosquat-check to skip.");return}const t=gt({input:process.stdin,output:process.stdout}),r=await new Promise(n=>{t.question(e,o=>{n(o.trim().toLowerCase())})});return t.close(),r},"askConfirmation"),Ll=ht(async(e,t)=>{const r=Dl(e,t);if(r.length===0)return{ok:!0,packages:e};Bl(r,"detected");const n=await Fl(`Use suggested package${r.length===1?"":"s"} instead? [S]uggested / [y]es, keep original / [N]o, abort (default: N) `);if(n===void 0)return{ok:!1,packages:e};if(n==="s"||n==="suggested"){const o=new Map(r.map(i=>[i.input,i.legitimate]));return{ok:!0,packages:e.map(i=>o.get(i)??i)}}return n==="y"||n==="yes"?{ok:!0,packages:e}:{ok:!1,packages:e}},"runTyposquatCheck"),Km=/^(?:npm|pnpm|yarn):(.+?)(?:@.*)?$/,Xm=ht(e=>Km.exec(e)?.[1],"parseAliasTarget"),Qm=ht(e=>{if(!E(e))return[];const t=ue(e),r={...t.dependencies,...t.devDependencies,...t.optionalDependencies,...t.peerDependencies},n=new Set;for(const[o,i]of Object.entries(r)){n.add(o);const s=Xm(i);s&&n.add(s)}return[...n]},"readDepsFromPackageJson"),Vl=ht(async(e,t)=>{const r=v(e,"package.json"),n=Qm(r);if(n.length===0)return!0;const o=Dl(n,t);if(o.length===0)return!0;Bl(o,"in package.json dependencies"),se("Fix the package name in package.json before proceeding.");const i=await Fl("Continue anyway? [y/N] ");return i==="y"||i==="yes"},"scanDepsForTyposquats");var Zm=Object.defineProperty,gs=b((e,t)=>Zm(e,"name",{value:t,configurable:!0}),"s$s");const Yn=gs(e=>e?Array.isArray(e)?e:[e]:[],"toStringArray"),Ni=gs(e=>e instanceof Error?e.message:typeof e=="string"?e:String(e),"errorMessage"),eh=/^(.+?)(?:@(.+))?$/,ms=gs(e=>{if(e.startsWith("@")){const r=e.indexOf("/");if(r===-1)return{name:e,versionSpec:void 0};const n=e.slice(r+1),o=n.indexOf("@");return o===-1?{name:e,versionSpec:void 0}:{name:e.slice(0,r+1+o),versionSpec:n.slice(o+1)}}const t=eh.exec(e);return t?{name:t[1]??e,versionSpec:t[2]}:{name:e,versionSpec:void 0}},"parsePackageArgument");var th=Object.defineProperty,tn=b((e,t)=>th(e,"name",{value:t,configurable:!0}),"m$r");const rh=tn(async(e,t=1e4)=>{const r=new Map,n=new AbortController,o=setTimeout(()=>{n.abort()},t);try{const i=e.map(async s=>{try{const a=await fetch(`https://registry.npmjs.org/${s}/latest`,{headers:{Accept:"application/json"},signal:n.signal});if(a.ok){const c=await a.json();c.version&&r.set(s,c.version)}}catch{}});await Promise.all(i)}finally{clearTimeout(o)}return r},"resolveLatestVersions"),nh=tn((e,t,r)=>{const n=[];for(const o of e.values()){const{overall:i}=o.score,s=Jn(i),a=`${String(Math.round(i*100))}%`,c=o.alerts.length,d=en(o),p=fs(d,o.version,r),g=s==="red"?Ge:s==="yellow"?Re:Ot;if(S(p?` ${g(a)} ${Ca(o)} ${$e(`[accepted: ${p.reason}]`)}`:` ${g(a)} ${Ca(o)}`),c>0){const h=o.alerts.filter(y=>y.severity==="critical"||y.severity==="high").length;h>0&&se(` ${String(h)} critical/high alert${h===1?"":"s"}`)}i<t&&!p&&n.push(o)}return n},"displaySecurityReports"),oh=tn(async(e,t)=>{const r=gt({input:process.stdin,output:process.stdout}),n=tn(a=>new Promise(c=>{r.question(a,d=>{c(d.trim())})}),"ask"),o=String(Math.round(t*100));se(""),se(`${String(e.length)} package${e.length===1?"":"s"} scored below the minimum threshold (${o}%):`);for(const a of e){const c=en(a),d=`${String(Math.round(a.score.overall*100))}%`;se(` • ${c}@${a.version} — score: ${d} (${ps(a.score.overall)})`)}se("");const i=await n("Continue adding these packages? [y/N] ");if(i.toLowerCase()!=="y"&&i.toLowerCase()!=="yes")return r.close(),!1;const s=await n("Remember this decision? (prints config snippet) [y/N] ");if(r.close(),s.toLowerCase()==="y"||s.toLowerCase()==="yes"){ie(""),ie("Add the following to security.socket.acceptedRisks in vis.config.ts:"),ie("");for(const a of e){const c=en(a),d=Wm(c,a.version,a.score.overall,"Reviewed and accepted");ie(d)}ie("")}return!0},"confirmLowScorePackages"),ih=tn(async(e,t,r,n)=>{const o=e.map(ms),i=new Map;for(const g of o)if(g.versionSpec){const h=Wn(g.versionSpec);h&&i.set(g.name,h.version)}const s=o.filter(g=>!i.has(g.name)).map(g=>g.name),a=s.length>0?await rh(s):new Map,c=[];for(const g of o){const h=i.get(g.name)??a.get(g.name);h&&c.push({name:g.name,version:h})}if(c.length===0)return!0;S(""),S("Socket.dev security check:");const d=await pn(c,t);if(d.size===0)return S(" Could not fetch security data. Proceeding."),!0;const p=nh(d,r,n);return p.length===0?(S(""),!0):process.stdin.isTTY?oh(p,r):(se(`Aborting: ${String(p.length)} package${p.length===1?"":"s"} below minimum score. Use --no-socket-check to skip.`),!1)},"runSocketPreCheck"),sh={argument:{description:"Packages to add (e.g., react react-dom)",name:"packages",type:String},description:"Add packages using the detected package manager",examples:[["vis add react react-dom","Add packages"],["vis add -D typescript @types/react","Add as dev dependencies"],["vis add react --filter app","Add to specific workspace package"],["vis add -g typescript","Add globally (uses npm)"],["vis add lodash -w","Add to workspace root"],["vis add lodash --no-socket-check","Add without Socket.dev check"],["vis add lodash --no-typosquat-check","Skip typosquat name check"]],execute:tn(async({argument:e,logger:t,options:r,visConfig:n,workspaceRoot:o})=>{let i=e;if(!i||i.length===0)throw new Error("No packages specified. Usage: vis add <packages...>");if(!r.noTyposquatCheck){const d=i.map(g=>ms(g)),p=await Ll(d.map(g=>g.name),n?.security?.typosquatAllowlist);if(!p.ok){process.exitCode=1;return}i=d.map((g,h)=>{const y=p.packages[h];return y!==g.name?g.versionSpec?`${y}@${g.versionSpec}`:y??"":i[h]??""})}if(!r.noSocketCheck){const d=Lr(n?.security?.socket);if(d){const p=d.minimumScore??lr;if(!await ih(i,d,p,n?.security?.socket?.acceptedRisks)){process.exitCode=1;return}}}const s=process.cwd(),a=Ne(o??s),c=$m(a,{exact:r.exact||!1,filter:Yn(r.filter),global:r.global||!1,optional:r.saveOptional||!1,packages:i,peer:r.savePeer||!1,saveDev:r.saveDev||!1,workspace:r.workspace||!1,workspaceRoot:r.workspaceRoot||!1},s,t);c!==0&&(process.exitCode=c)},"execute"),group:"Dependencies",name:"add",options:[{alias:"D",defaultValue:!1,description:"Add as dev dependency",name:"save-dev",type:Boolean},{alias:"E",defaultValue:!1,description:"Save exact version",name:"exact",type:Boolean},{alias:"P",defaultValue:!1,description:"Add as peer dependency",name:"save-peer",type:Boolean},{alias:"O",defaultValue:!1,description:"Add as optional dependency",name:"save-optional",type:Boolean},{alias:"g",defaultValue:!1,description:"Install globally (uses npm)",name:"global",type:Boolean},{alias:"w",defaultValue:!1,description:"Add to workspace root",name:"workspace-root",type:Boolean},{defaultValue:!1,description:"Use workspace protocol (pnpm)",name:"workspace",type:Boolean},{alias:"F",description:"Filter by workspace package name",multiple:!0,name:"filter",type:String},{defaultValue:!1,description:"Skip typosquat name check before adding",name:"no-typosquat-check",type:Boolean},{defaultValue:!1,description:"Skip Socket.dev security check before adding",name:"no-socket-check",type:Boolean}]};var ah=Object.defineProperty,ch=b((e,t)=>ah(e,"name",{value:t,configurable:!0}),"l$q");const lh={argument:{description:"The target to run (e.g., build, test, lint)",name:"target",type:String},description:"Run a target only on projects affected by recent changes",examples:[["vis affected build","Run build on affected projects"],["vis affected test --base=main","Run tests on projects changed since main"]],execute:ch(async({argument:e,logger:t,options:r,runtime:n,visConfig:o,workspaceRoot:i})=>{const s=e[0];if(!s)throw new Error("Missing target. Usage: vis affected <target>");if(!i)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const a=i,{packageJsons:c,workspace:d}=mt(a,o),p=nr(a,d,c),g=new Set(["deep","direct","none"]),h=r.downstream??"deep",y=r.upstream??"none";if(!g.has(h))throw new Error(`Invalid --downstream value: "${h}". Must be "none", "direct", or "deep".`);if(!g.has(y))throw new Error(`Invalid --upstream value: "${y}". Must be "none", "direct", or "deep".`);const w={base:r.base,downstream:h,head:r.head,projectGraph:p,projects:d.projects,upstream:y,workspaceRoot:a},k=await Jc(w);if(k.changedFiles.length===0){t.info("No files changed. Nothing to run.");return}if(k.affectedProjects.length===0){t.info("No projects affected by the changes.");return}let{affectedProjects:$}=k;if(r.query&&($=Bo($,d,r.query),$.length===0)){t.info(`Query "${String(r.query)}" matched no affected projects.`);return}t.info(`Affected projects: ${$.join(", ")}`),k.changedFiles.length>0&&(process.env.VIS_AFFECTED_FILES=k.changedFiles.join(`
33
- `));const x=[s,`--projects=${$.join(",")}`];r.parallel!==void 0&&x.push(`--parallel=${String(r.parallel)}`),r.cache||x.push("--no-cache"),r.dryRun&&x.push("--dry-run"),r.partition&&x.push(`--partition=${String(r.partition)}`);try{await n.runCommand("run",{argv:x})}finally{delete process.env.VIS_AFFECTED_FILES}},"execute"),group:"Run & Execute",name:"affected",options:[{defaultValue:"HEAD~1",description:"Git base ref for comparison",name:"base",type:String},{defaultValue:"HEAD",description:"Git head ref for comparison",name:"head",type:String},{defaultValue:"deep",description:'Downstream scope: "none", "direct", or "deep" — controls how far to include dependents of changed projects',name:"downstream",type:String},{defaultValue:"none",description:'Upstream scope: "none", "direct", or "deep" — controls how far to include dependencies of changed projects',name:"upstream",type:String},{defaultValue:3,description:"Maximum number of parallel tasks",name:"parallel",type:Number},{defaultValue:!0,description:"Enable caching (use --no-cache to disable)",name:"cache",type:Boolean},{defaultValue:!1,description:"Show what would run without executing",name:"dry-run",type:Boolean},{description:'Partition tasks for distributed CI (e.g., "1/4" for first of four runners). Falls back to VIS_PARTITION env var.',name:"partition",type:String},{description:"Filter affected projects by a query (e.g. 'language=typescript && tag=lib')",name:"query",type:String}]};var dh=Object.defineProperty,ke=b((e,t)=>dh(e,"name",{value:t,configurable:!0}),"f$t");const Qr=(1n<<128n)-1n,ae=(1n<<64n)-1n,So=(1n<<32n)-1n,_l=0x9E3779B1n,Ul=0x85EBCA77n,uh=0xC2B2AE3Dn,pr=0x9E3779B185EBCA87n,Pr=0xC2B2AE3D27D4EB4Fn,Wl=0x165667B19E3779F9n,hs=0x85EBCA77C2B2AE63n,ph=0x27D4EB2F165667C5n,fh=0x165667919E3779F9n,gh=0x9FB21C651E98DF25n,Yt=64,Gl=Yt/8,mh=8,At=Buffer.from("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e","hex"),je=ke((e,t=0)=>Buffer.from(e.buffer,e.byteOffset+t,e.length-t),"getView"),hh=ke(e=>{const t=Buffer.allocUnsafe(8);return t.writeBigUInt64LE(e),t.readBigUInt64BE()},"bswap64"),yh=ke(e=>{let t=e;return t=(t&0x0000FFFFn)<<16n|(t&0xFFFF0000n)>>16n,t=(t&0x00FF00FFn)<<8n|(t&0xFF00FF00n)>>8n,t},"bswap32"),vh=ke((e,t)=>(e&So)*(t&So)&ae,"multU32ToU64"),wh=ke((e,t)=>(e<<t|e>>32n-t)&So,"rotl32"),Mi=ke((e,t)=>e^e>>t,"xorshift64"),Di=ke(e=>~e+1n&ae,"inv64"),Hl=ke((e,t)=>{const r=e*t&Qr;return r&ae^r>>64n},"mul128Fold64"),It=ke(e=>{let t=e;return t^=t>>37n,t=t*fh&ae,t^=t>>32n,t},"avalanche"),Co=ke(e=>{let t=e;return t^=t>>33n,t=t*Pr&ae,t^=t>>29n,t=t*Wl&ae,t^=t>>32n,t},"avalanche64"),zl=ke((e,t,r)=>{for(let n=0;n<Gl;n++){const o=t.readBigUInt64LE(n*8),i=o^r.readBigUInt64LE(n*8);e[n^1]+=o,e[n]+=vh(i,i>>32n)}return e},"accumulate512"),ja=ke((e,t,r,n)=>{for(let o=0;o<n;o++)zl(e,je(t,o*Yt),je(r,o*8));return e},"accumulate"),kh=ke((e,t)=>{for(let r=0;r<Gl;r++){const n=t.readBigUInt64LE(r*8);let o=e[r];o=Mi(o,47n),o^=n,o*=_l,e[r]=o&ae}return e},"scrambleAcc"),lo=ke((e,t)=>Hl(e[0]^t.readBigUInt64LE(0),e[1]^t.readBigUInt64LE(mh)),"mix2Accs"),Ea=ke((e,t,r)=>{let n=r;return n+=lo(e.slice(0),je(t,0)),n+=lo(e.slice(2),je(t,16)),n+=lo(e.slice(4),je(t,32)),n+=lo(e.slice(6),je(t,48)),It(n&ae)},"mergeAccs"),bh=ke((e,t,r)=>{const n=Math.floor((r.byteLength-Yt)/8),o=Yt*n,i=Math.floor((t.byteLength-1)/o);for(let a=0;a<i;a++)ja(e,je(t,a*o),r,n),kh(e,je(r,r.byteLength-Yt));const s=Math.floor((t.byteLength-1-o*i)/Yt);return ja(e,je(t,i*o),r,s),zl(e,je(t,t.byteLength-Yt),je(r,r.byteLength-Yt-7)),e},"hashLong"),$h=ke((e,t)=>{const r=new BigUint64Array([uh,pr,Pr,Wl,hs,Ul,ph,_l]);bh(r,e,t);const n=Ea(r,je(t,11),BigInt(e.byteLength)*pr&ae);return Ea(r,je(t,t.byteLength-Yt-11),~(BigInt(e.byteLength)*Pr)&ae)<<64n|n},"hashLong128b"),Ta=ke((e,t,r)=>Hl((e.readBigUInt64LE(0)^t.readBigUInt64LE(0)+r)&ae,(e.readBigUInt64LE(8)^t.readBigUInt64LE(8)-r)&ae),"mix16B"),yo=ke((e,t,r,n,o)=>{let i=e&ae,s=e>>64n&ae;return i+=Ta(t,n,o),i^=r.readBigUInt64LE(0)+r.readBigUInt64LE(8),i&=ae,s+=Ta(r,je(n,16),o),s^=t.readBigUInt64LE(0)+t.readBigUInt64LE(8),s&=ae,s<<64n|i},"mix32B"),xh=ke((e,t,r)=>{const n=e.byteLength,o=BigInt(e.readUInt8(n-1))|BigInt(n<<8)|BigInt(e.readUInt8(0)<<16)|BigInt(e.readUInt8(n>>1)<<24),i=(BigInt(t.readUInt32LE(0))^BigInt(t.readUInt32LE(4)))+r,s=(o^i)&ae,a=(BigInt(t.readUInt32LE(8))^BigInt(t.readUInt32LE(12)))-r,c=(wh(yh(o),13n)^a)&ae;return(Co(c)&ae)<<64n|Co(s)},"len1to3_128b"),Sh=ke((e,t,r)=>{const n=e.byteLength,o=e.readUInt32LE(0),i=e.readUInt32LE(n-4),s=BigInt(o)|BigInt(i)<<32n,a=(t.readBigUInt64LE(16)^t.readBigUInt64LE(24))+r&ae;let c=(s^a)*(pr+(BigInt(n)<<2n))&Qr;return c+=(c&ae)<<65n,c&=Qr,c^=c>>67n,Mi(Mi(c&ae,35n)*gh&ae,28n)|It(c>>64n)<<64n},"len4to8_128b"),Ch=ke((e,t,r)=>{const n=e.byteLength,o=(t.readBigUInt64LE(32)^t.readBigUInt64LE(40))+r&ae,i=(t.readBigUInt64LE(48)^t.readBigUInt64LE(56))-r&ae,s=e.readBigUInt64LE();let a=e.readBigUInt64LE(n-8),c=(s^a^o)*pr;const d=(c&ae)+(BigInt(n-1)<<54n);c=c&(Qr^ae)|d,a^=i,c+=a+(a&So)*(Ul-1n)<<64n,c&=Qr,c^=hh(c>>64n);let p=(c&ae)*Pr;return p+=(c>>64n)*Pr<<64n,p&=Qr,It(p&ae)|It(p>>64n)<<64n},"len9to16_128b"),jh=ke((e,t)=>{const r=e.byteLength;return r>8?Ch(e,At,t):r>=4?Sh(e,At,t):r>0?xh(e,At,t):Co(t^At.readBigUInt64LE(64)^At.readBigUInt64LE(72))|Co(t^At.readBigUInt64LE(80)^At.readBigUInt64LE(88))<<64n},"len0to16_128b"),Eh=ke((e,t,r)=>{let n=BigInt(e.byteLength)*pr&ae,o=BigInt(e.byteLength-1)/32n;for(;o>=0n;){const a=Number(o);n=yo(n,je(e,16*a),je(e,e.byteLength-16*(a+1)),je(t,32*a),r),o--}let i=n+(n>>64n)&ae;i=It(i);let s=(n&ae)*pr+(n>>64n)*hs+(BigInt(e.byteLength)-r&ae)*Pr;return s&=ae,s=Di(It(s)),i|s<<64n},"len17to128_128b"),Th=ke((e,t,r)=>{let n=BigInt(e.byteLength)*pr&ae;for(let s=32;s<160;s+=32)n=yo(n,je(e,s-32),je(e,s-16),je(t,s-32),r);n=It(n&ae)|It(n>>64n)<<64n;for(let s=160;s<=e.byteLength;s+=32)n=yo(n,je(e,s-32),je(e,s-16),je(t,3+s-160),r);n=yo(n,je(e,e.byteLength-16),je(e,e.byteLength-32),je(t,103),Di(r));let o=n+(n>>64n)&ae;o=It(o);let i=(n&ae)*pr+(n>>64n)*hs+(BigInt(e.byteLength)-r&ae)*Pr;return i&=ae,i=Di(It(i)),o|i<<64n},"len129to240_128b"),Rh=ke((e,t=0n)=>{const r=e.byteLength;return r<=16?jh(e,t):r<=128?Eh(e,At,t):r<=240?Th(e,At,t):$h(e,At)},"xxh3_128"),Ah=ke(e=>{const t=e>>64n&ae,r=e&ae;return t.toString(16).padStart(16,"0")+r.toString(16).padStart(16,"0")},"bigintToHex"),ql=ke(e=>Ah(Rh(e)),"xxh3Hash");class Ih{static{b(this,"gn")}static{ke(this,"Xxh3Hasher")}#e=[];update(t){return typeof t=="string"?this.#e.push(Buffer.from(t)):this.#e.push(t),this}digest(){return ql(Buffer.concat(this.#e))}}ke(()=>new Ih,"createXxh3Hasher");var Oh=Object.defineProperty,hr=b((e,t)=>Oh(e,"name",{value:t,configurable:!0}),"s$r");const Kn=hr(()=>v(Qe(),".vis","cache","ai"),"getCacheDirectory"),Ph=3600*1e3,Nh=1800*1e3,Mh=hr(()=>{Se(Kn())},"ensureCacheDirectory"),Dh=hr((e,t,r)=>{const n=r.map(i=>({currentRange:i.currentRange,name:i.packageName,targetVersion:i.targetVersion})).toSorted((i,s)=>i.name.localeCompare(s.name)),o=JSON.stringify({analysisType:t,packages:n,provider:e});return ql(Buffer.from(o))},"buildCacheKey"),Bh=hr(e=>{const t=v(Kn(),`${e}.json`);if(E(t))try{const r=ue(t);if(Date.now()-r.createdAt>r.ttlMs){at(t,{force:!0});return}return r.result}catch{at(t,{force:!0});return}},"getCachedAnalysis"),Fh=hr((e,t,r)=>{Mh();const n=Kn(),o={createdAt:Date.now(),result:t,ttlMs:r};me(v(n,`${e}.json`),JSON.stringify(o,void 0,2),"utf8")},"setCachedAnalysis"),Lh=hr((e,t)=>t!==void 0&&t>0?t:e==="security"?Nh:Ph,"getTtlForAnalysisType"),Vh=hr(()=>{const e=Kn();if(!E(e))return{entries:0,newestEntry:void 0,oldestEntry:void 0,totalSizeBytes:0};const t=Ve(e).filter(i=>i.endsWith(".json"));let r=0,n,o;for(const i of t){const s=v(e,i),a=Mt(s);r+=a.size;const{mtimeMs:c}=a;(n===void 0||c<n)&&(n=c),(o===void 0||c>o)&&(o=c)}return{entries:t.length,newestEntry:o,oldestEntry:n,totalSizeBytes:r}},"getCacheStats"),_h=hr(()=>{const e=Kn();if(!E(e))return 0;const t=Ve(e).filter(r=>r.endsWith(".json"));for(const r of t)at(v(e,r),{force:!0});return t.length},"clearCache");var Uh=Object.defineProperty,Le=b((e,t)=>Uh(e,"name",{value:t,configurable:!0}),"o$k");const vo={amp:30,claude:80,codex:60,copilot:50,crush:35,cursor:40,droid:20,gemini:100,kimi:25,opencode:35,qwen:30},ys=Le(e=>{if(e?.provider){if(!Bp.includes(e.provider))return;const n=Fp(e.provider);return n.available?n:void 0}const t=Lp();if(t.length===0)return;const r={...vo,...e?.priority};return t.toSorted((n,o)=>(r[o.name]??0)-(r[n.name]??0))[0]},"resolveProvider"),Wh=new Set(["defer","review","skip","update"]),Gh=new Set(["critical","high","low","medium"]),Hh=new Set(["high","low","medium"]),zh=50,vi=30,qh=2,Jh=1e3,Yh=12e4,Kh=Le(e=>e.map(t=>{const r=t.vulnerabilities&&t.vulnerabilities.length>0?` [VULNERABILITIES: ${t.vulnerabilities.map(o=>`${o.severity} ${o.id}`).join(", ")}]`:"";let n="";if(t.socketReport){const o=Math.round(t.socketReport.score.overall*100),i=[`score:${String(o)}%`];if(t.socketReport.alerts.length>0){const s=t.socketReport.alerts.reduce((c,d)=>(c[d.severity]=(c[d.severity]??0)+1,c),{}),a=Object.entries(s).map(([c,d])=>`${String(d)} ${c}`).join(", ");i.push(`alerts: ${a}`)}i.push(`supply-chain:${String(Math.round(t.socketReport.score.supplyChain*100))}%`),i.push(`quality:${String(Math.round(t.socketReport.score.quality*100))}%`),n=` [SOCKET.DEV: ${i.join(", ")}]`}return`- ${t.packageName}: ${t.currentRange} → ${t.newRange} (${t.updateType})${r}${n}`}).join(`
34
- `),"buildPackageList"),uo=`Respond ONLY with valid JSON in this exact structure:
35
- {
36
- "summary": "Brief overall summary",
37
- "recommendations": [
38
- {
39
- "package": "package-name",
40
- "action": "update|skip|review|defer",
41
- "reason": "explanation",
42
- "riskLevel": "low|medium|high|critical",
43
- "breakingChanges": ["change1"],
44
- "effort": "low|medium|high"
45
- }
46
- ],
47
- "warnings": ["warning1"]
48
- }`,Xh={compatibility:Le(e=>`Analyze the compatibility of these package updates:
49
-
50
- ${e}
51
-
52
- For each package:
53
- 1. Check peer dependency compatibility
54
- 2. Identify potential conflicts with other packages in the list
55
- 3. Assess API compatibility between current and target versions
56
- 4. Check for deprecated features being removed
57
- 5. Evaluate Node.js version requirements
58
-
59
- ${uo}`,"compatibility"),impact:Le(e=>`Analyze the impact of updating these npm packages:
60
-
61
- ${e}
62
-
63
- For each package, provide:
64
- 1. Risk level (low/medium/high/critical)
65
- 2. Recommended action (update/skip/review/defer)
66
- 3. Reason for recommendation
67
- 4. Known breaking changes (if any)
68
- 5. Estimated migration effort (low/medium/high)
69
-
70
- ${uo}`,"impact"),recommend:Le(e=>`Provide smart recommendations for updating these packages:
71
-
72
- ${e}
73
-
74
- Consider:
75
- 1. Update priority based on security, features, and stability
76
- 2. Grouping related packages for atomic updates
77
- 3. Best practices for the specific package ecosystem
78
- 4. Risk vs. benefit analysis
79
- 5. Suggested update order
80
- 6. If Socket.dev scores are provided, prioritize packages with low supply chain or quality scores
81
-
82
- ${uo}`,"recommend"),security:Le(e=>`Analyze the security implications of these package updates:
83
-
84
- ${e}
85
-
86
- For each package:
87
- 1. Check if the update fixes known vulnerabilities (use the vulnerability data above)
88
- 2. Assess if the new version introduces security risks
89
- 3. Evaluate if this is a security-sensitive package (auth, crypto, session, etc.)
90
- 4. Recommend urgency of the update based on vulnerability severity
91
- 5. Flag any packages where skipping the update poses security risk
92
- 6. If Socket.dev scores are provided, factor in supply chain and quality scores — low scores indicate higher risk
93
-
94
- ${uo}`,"security")},Qh=new Set(["compatibility","impact","recommend","security"]),vs=Le(e=>Qh.has(e)?e:"impact","validateAnalysisType"),Jl=Le((e,t="impact")=>{const r=Kh(e);return Xh[t](r)},"buildAnalysisPrompt"),Zh=/```(?:json)?\s*([\s\S]*?)```/,ey=/\{[\s\S]*\}/,ty=Le(e=>{try{return JSON.parse(e)}catch{}const t=Zh.exec(e);if(t?.[1])try{return JSON.parse(t[1])}catch{}const r=ey.exec(e);if(r?.[0])try{return JSON.parse(r[0])}catch{}},"extractJson"),ry=Le(e=>({action:Wh.has(e.action)?e.action:"review",breakingChanges:Array.isArray(e.breakingChanges)?e.breakingChanges:[],effort:Hh.has(e.effort)?e.effort:"medium",package:typeof e.package=="string"?e.package:"",reason:typeof e.reason=="string"?e.reason:"",riskLevel:Gh.has(e.riskLevel)?e.riskLevel:"medium"}),"normalizeRecommendation"),Yl=Le((e,t,r)=>{const n=ty(e);if(!n||typeof n!="object")return{analysisType:r,provider:t,recommendations:[],summary:"Failed to parse AI response.",warnings:["AI response was not valid JSON."]};const o=n,i=Array.isArray(o.recommendations)?o.recommendations:[];return{analysisType:r,provider:t,recommendations:i.map(s=>ry(s)),summary:typeof o.summary=="string"?o.summary:"",warnings:Array.isArray(o.warnings)?o.warnings:[]}},"parseAiResponse"),ny={eslint:["ESLint 9.0: Flat config required","ESLint 8.0+: New rule formats"],next:["Next.js 13+: App router changes","Next.js 14+: Server components default"],react:["React 17 to 18: Concurrent features","React 18+: Strict mode changes"],typescript:["TypeScript 5.0: New decorators","TypeScript 4.7+: ESM changes"],vite:["Vite 5: Node.js 18+ required"],vue:["Vue 3: Composition API","Vue 3: Breaking template changes"],webpack:["Webpack 5: Node.js polyfills removed"]},oy=new Set(["bcrypt","cors","crypto-js","express-session","helmet","jose","jsonwebtoken","node-forge","oauth","passport"]),Ra=Le((e,t)=>{const r=e.map(n=>{const o=n.vulnerabilities&&n.vulnerabilities.length>0,i=oy.has(n.packageName),s=ny[n.packageName]??[];let a="low",c="update",d="low",p="Patch/minor update, safe to apply.";return n.updateType==="major"?(a="high",c=s.length>0?"review":"update",d="medium",p=s.length>0?`Major update with known breaking changes: ${s[0]}`:"Major version update, review changelog before applying."):n.updateType==="minor"&&(a="medium",p="Minor update, generally safe."),o&&(a="high",c="update",p="Security update — current version has known vulnerabilities."),i&&n.updateType==="major"&&(c="review",p="Security-sensitive package with major update, careful review needed.",d="high"),{action:c,breakingChanges:s,effort:d,package:n.packageName,reason:p,riskLevel:a}});return{analysisType:t,provider:"rule-engine",recommendations:r,summary:`Rule-based ${t} analysis for ${String(e.length)} packages.`,warnings:["No AI provider available — using built-in rule engine."]}},"ruleBasedAnalysis"),iy=Le(e=>new Promise(t=>{setTimeout(t,e)}),"sleep"),Kl=Le(async(e,t,r=qh)=>{let n;for(let o=0;o<=r;o+=1)try{return(await ol(e,t,{timeoutMs:Yh})).stdout}catch(i){if(n=i instanceof Error?i:new Error(String(i)),n.message.includes("timed out"))throw n;if(o<r){const s=Jh*2**o;await iy(s)}}throw n??new Error("AI analysis failed after retries")},"runWithRetry"),sy=Le(async(e,t,r)=>{const n=Jl(t,r),o=await Kl(e,n);return Yl(o,e.name,r)},"analyzeChunk"),ay=Le((e,t,r)=>{const n=[],o=[],i=[];for(const s of e)n.push(...s.recommendations),o.push(...s.warnings),s.summary&&i.push(s.summary);return{analysisType:r,provider:t,recommendations:n,summary:i.length===1?i[0]??"":`Analyzed ${String(n.length)} packages in ${String(e.length)} batches.`,warnings:[...new Set(o)]}},"mergeResults"),Xl={compatibility:"Compatibility",impact:"Impact",recommend:"Recommendations",security:"Security"},jo=Le(e=>{const t=`${Xl[e.analysisType]??e.analysisType} Analysis (${e.provider})`,r=e.recommendations.flatMap(o=>{const i=[{action:o.action,effort:o.effort,package:o.package,reason:o.reason,risk:o.riskLevel}];return o.breakingChanges.length>0&&i.push({action:"",effort:"",package:"",reason:`Breaking: ${o.breakingChanges.join("; ")}`,risk:""}),i}),n=process.stdout.columns||80;return Oe(Q.createElement(m,{borderStyle:"round",flexDirection:"column",paddingLeft:1,paddingRight:1},Q.createElement(l,{bold:!0},t),Q.createElement(l,null,""),Q.createElement(l,null,e.summary),Q.createElement(l,null,""),Q.createElement(os,{borderStyle:"none",data:r}),...e.warnings.length>0?[Q.createElement(l,null,""),...e.warnings.map((o,i)=>Q.createElement(l,{dimColor:!0,key:String(i)},` ${o}`))]:[]),{columns:n})},"formatAiAnalysis");Le(e=>JSON.stringify(e,void 0,2),"formatAiAnalysisJson");const ws=Le(async(e,t,r,n="impact")=>{const o=ys(r);if(!o)return t.info(`No AI CLI tool found, using rule-based analysis.
95
- `),Ra(e,n);const i=Dh(o.name,n,e),s=Bh(i);if(s)return t.info(`Using cached ${n} analysis from ${s.provider}.
96
- `),s;const a=Xl[n]??n;t.info(`Running ${a.toLowerCase()} analysis with ${o.name}...
97
- `);try{let c;if(e.length>zh){t.info(`Splitting ${String(e.length)} packages into batches of ${String(vi)}...
98
- `);const d=[];for(let g=0;g<e.length;g+=vi)d.push(e.slice(g,g+vi));const p=[];for(let g=0;g<d.length;g+=1){t.info(` Batch ${String(g+1)}/${String(d.length)}...`);const h=d[g];h&&p.push(await sy(o,h,n))}c=ay(p,o.name,n)}else{const d=await Kl(o,Jl(e,n));c=Yl(d,o.name,n)}return Fh(i,c,Lh(n,r?.cacheTtl)),c}catch(c){const d=c instanceof Error?c.message:String(c);return t.warn(`AI analysis failed (${d}), falling back to rule engine.
99
- `),Ra(e,n)}},"runAiAnalysis");var cy=Object.defineProperty,qo=b((e,t)=>cy(e,"name",{value:t,configurable:!0}),"c$w");const ly=qo((e,t)=>{const r=Vh();if(e==="json"){process.stdout.write(`${JSON.stringify(r,void 0,2)}
100
- `);return}t.info("AI Cache Statistics:"),t.info(` Entries: ${String(r.entries)}`),t.info(` Total size: ${String(Math.round(r.totalSizeBytes/1024))} KB`),t.info(` Oldest: ${r.oldestEntry?new Date(r.oldestEntry).toISOString():"N/A"}`),t.info(` Newest: ${r.newestEntry?new Date(r.newestEntry).toISOString():"N/A"}`)},"handleCacheStats"),dy=qo(async(e,t)=>{const r=ys(t);if(!r){e.error("No AI provider available to test."),process.exitCode=1;return}e.info(`Testing ${r.name}...`);try{const n=await ol(r,"Reply with exactly: OK",{timeoutMs:3e4});e.info(`Provider ${r.name} responded: ${n.stdout.trim().slice(0,200)}`)}catch(n){const o=n instanceof Error?n.message:String(n);e.error(`Provider ${r.name} failed: ${o}`),process.exitCode=1}},"handleTest"),uy=qo((e,t,r)=>{const n=Vp(),o=ys(r);if(e==="json"){const c=n.map(d=>({available:d.available,method:d.detectionMethod,name:d.name,path:d.path,priority:vo[d.name]??0,selected:d.name===o?.name,version:d.version}));process.stdout.write(`${JSON.stringify(c,void 0,2)}
101
- `);return}const i=n.map(c=>({method:c.detectionMethod??"-",path:c.path??"-",priority:String(vo[c.name]??0),provider:c.name,selected:c.name===o?.name?">>>":"",status:c.available?"available":"not found",version:c.version??"-"})),s=process.stdout.columns||80,a=Oe(Q.createElement(os,{data:i}),{columns:s});t.info(a),o?t.info(`
102
- Selected provider: ${o.name} (priority ${String(vo[o.name]??0)})`):t.info(`
103
- No AI provider available. Install one of the supported AI CLI tools.`)},"handleProviderStatus"),py={alias:"a",description:"Show AI provider status, test connectivity, and manage cache",examples:[["vis ai","Show all AI providers and their status"],["vis ai --test","Test the best available provider"],["vis ai --cache-stats","Show AI response cache statistics"],["vis ai --clear-cache","Clear the AI response cache"],["vis ai --format json","Output as JSON"]],execute:qo(async({logger:e,options:t,visConfig:r})=>{const n=t.format??"table";if(t.cacheStats){ly(n,e);return}if(t.clearCache){const o=_h(),i=Um();e.info(`Cleared ${String(o)} cached AI response${o===1?"":"s"}.`),i>0&&e.info(`Cleared ${String(i)} cached Socket.dev report${i===1?"":"s"}.`);return}if(t.test){await dy(e,r?.ai);return}uy(n,e,r?.ai)},"execute"),group:"System",name:"ai",options:[{defaultValue:!1,description:"Test the best available AI provider with a quick prompt",name:"test",type:Boolean},{defaultValue:!1,description:"Show AI response cache statistics",name:"cache-stats",type:Boolean},{defaultValue:!1,description:"Clear the AI response cache",name:"clear-cache",type:Boolean},{description:"Output format: table or json (default: table)",name:"format",type:String}]};var fy=Object.defineProperty,_=b((e,t)=>fy(e,"name",{value:t,configurable:!0}),"c$v");const gy=/^([\^~]|>=|<=|[><=])/,my=/^(?:'([^']+)'|"([^"]+)"|([^:\s]+)):\s*(?:'([^']+)'|"([^"]+)"|(\S+))/,hy=/^catalog:/m,yy=/^catalogs:/m,vy=/^(@[^:]+):registry$/,wy=/^\/\/(.+)\/:_authToken$/,ky=/\*+/g,by=/[.+^${}()|[\]\\]/g,Aa=/[.*+?^${}()|[\]\\]/g,Ql=/^['"]|['"]$/g,$y=/^https?:\/\//,Zl=/\/$/,xy=/\n(\s+)/,ed=["dependencies","devDependencies","optionalDependencies","peerDependencies"],Sy=new Set([...ed,"overrides","pnpm.overrides","resolutions"]),ks=_(e=>{const t=al("vis",{create:!0,cwd:e});if(!t)throw new Error("Cannot resolve cache directory. Ensure node_modules exists in your workspace. Run your package manager's install command first.");return v(t,"backup")},"getBackupDir"),Qt=_(e=>{const t=e.replace(/^[\^~]|^>=|^<=|^[><]/,""),r=jp(t);if(r)return{major:r.major,minor:r.minor,patch:r.patch,prerelease:Array.isArray(r.prerelease)?r.prerelease.join("."):String(r.prerelease??"")};const n=Wn(e);if(n)return{major:n.major,minor:n.minor,patch:n.patch,prerelease:""}},"parseVersion"),bs=_(e=>gy.exec(e)?.[1]??"","extractPrefix"),Cy=_(e=>{const t=`${String(e.major)}.${String(e.minor)}.${String(e.patch)}`;return e.prerelease?`${t}-${e.prerelease}`:t},"versionToString"),td=_((e,t)=>e.major!==t.major?"major":e.minor!==t.minor?"minor":e.patch!==t.patch||e.prerelease!==t.prerelease?"patch":"none","getUpdateType"),jy=_((e,t)=>e.major!==t.major?e.major-t.major:e.minor!==t.minor?e.minor-t.minor:e.patch!==t.patch?e.patch-t.patch:!e.prerelease&&t.prerelease?1:e.prerelease&&!t.prerelease?-1:e.prerelease&&t.prerelease?e.prerelease<t.prerelease?-1:e.prerelease>t.prerelease?1:0:0,"compareVersions"),rd=_((e,t)=>jy(t,e)>0,"isNewer"),Mn=_((e,t)=>{const r=t.replaceAll(ky,"*").replaceAll(by,String.raw`\$&`);return new RegExp(`^${r.replaceAll("*",".*").replaceAll("?",".")}$`).test(e)},"matchesPattern"),Ey=_((e,t,r)=>r.some(n=>Mn(e,n))?!1:t.length>0?t.some(n=>Mn(e,n)):!0,"matchesFilters"),nd=_(e=>{const t=my.exec(e);if(!t)return;const r=t[1]??t[2]??t[3],n=t[4]??t[5]??t[6];if(!(!r||!n))return[r,n]},"parseYamlEntry"),od=_((e,t,r,n)=>{e.has(t)||e.set(t,new Map);const o=e.get(t);o&&o.set(r,n)},"setCatalogEntry"),Ty=_((e,t,r)=>{if(r<2)return;const n=nd(t);n&&od(e,"default",n[0],n[1])},"parseCatalogSection"),Ry=_((e,t,r,n)=>{if(r===2&&t.endsWith(":"))return t.slice(0,-1).trim().replaceAll(Ql,"");if(r>=4&&n){const o=nd(t);o&&od(e,n,o[0],o[1])}return n},"parseCatalogsSection"),id=_(e=>e==="catalog:"||e.startsWith("catalog:")?"catalog":e==="catalogs:"||e.startsWith("catalogs:")?"catalogs":"none","detectTopLevelSection"),Ay=_(e=>{const t=new Map;let r="none",n="";for(const o of e.split(`
104
- `)){const i=o.trimStart(),s=o.length-i.length;if(s===0&&i.length>0&&!i.startsWith("#")){r=id(i),r==="catalogs"&&(n="");continue}i.length===0||i.startsWith("#")||(r==="catalog"&&Ty(t,i,s),r==="catalogs"&&(n=Ry(t,i,s,n)))}return t},"parseCatalogsFromYaml"),Iy=_(e=>{const t=v(e,"pnpm-workspace.yaml");if(!E(t))return!1;const r=q(t);return hy.test(r)||yy.test(r)},"hasPnpmCatalogs"),Oy=_(e=>{const t=v(e,"pnpm-workspace.yaml");if(!E(t))return new Map;const r=q(t);return Ay(r)},"readPnpmCatalogs"),sd=_(e=>{if(E(e))try{return ue(e)}catch{return}},"readPackageJsonSafe"),Py=_(e=>{const t=sd(v(e,"package.json"));return!!(t?.workspaces?.catalog||t?.workspaces?.catalogs)},"hasBunCatalogs"),Ny=_(e=>{const t=new Map;if(e.workspaces?.catalog&&typeof e.workspaces.catalog=="object"&&t.set("default",new Map(Object.entries(e.workspaces.catalog))),e.workspaces?.catalogs&&typeof e.workspaces.catalogs=="object")for(const[r,n]of Object.entries(e.workspaces.catalogs))typeof n=="object"&&n!==void 0&&t.set(r,new Map(Object.entries(n)));return t},"parseBunCatalogs"),My=_(e=>{const t=sd(v(e,"package.json"));return t?Ny(t):new Map},"readBunCatalogs"),Xn=_(e=>{const t=e.lastIndexOf(":");if(t===-1)return;const r=e.slice(t+1);if(Sy.has(r))return{depType:r,relativePath:e.slice(0,t)}},"parseCompositeCatalogName"),Dy=_(e=>e?.dev?["devDependencies"]:e?.prod?["dependencies"]:e?.depFields&&e.depFields.length>0?e.depFields:ed,"getDepTypesToInclude"),By=_((e,t,r)=>{const n=new Set;t&&n.add(t);for(const o of r){const i=v(e,o,"package.json");if(E(i))try{const s=ue(i);s.name&&n.add(s.name)}catch{}}return n},"collectInternalPackageNames"),ad=_((e,t)=>{const r=t.split(".");let n=e;for(const o of r)if(n&&typeof n=="object")n=n[o];else return;return typeof n=="object"&&n!==null?n:void 0},"getNestedField"),Fy=_((e,t,r,n)=>{const o=t.split(".");let i=e;for(const a of o.slice(0,-1))(!i[a]||typeof i[a]!="object")&&(i[a]={}),i=i[a];const s=o.at(-1);(!i[s]||typeof i[s]!="object")&&(i[s]={}),i[s][r]=n},"setNestedField"),Ly=_((e,t)=>{const r=new Map;for(const[n,o]of Object.entries(e))t.has(n)||o.startsWith("workspace:")||o.startsWith("file:")||o.startsWith("link:")||o.startsWith("catalog:")||o.startsWith("$")||r.set(n,o);return r},"filterExternalDeps"),Vy=_((e,t,r,n,o,i)=>{const s=t==="."?r:v(e,t,"package.json");if(!E(s))return;let a;try{a=ue(s)}catch{return}for(const c of n){const d=c.includes(".")?ad(a,c):a[c];if(!d||typeof d!="object")continue;const p=Ly(d,o);p.size>0&&i.set(`${t}:${c}`,p)}},"scanDirectoryDeps"),_y=_((e,t)=>{const r=new Map,n=v(e,"package.json");if(!E(n))return r;const o=ue(n);let i=[];const s=o.workspaces;if(s){const p=Array.isArray(s)?s:s.packages;p&&(i=Or(e,p))}if(i.length===0){const p=Wo(e);p&&(i=Or(e,p))}const a=By(e,o.name,i),c=Dy(t),d=[".",...i];for(const p of d)Vy(e,p,n,c,a,r);return r},"readPackageJsonDeps"),wi=_(e=>{const t=v(e,"package.json");if(!E(t))return!1;try{const r=ue(t);return!!(r.dependencies||r.devDependencies||r.peerDependencies||r.optionalDependencies||r.overrides||r.resolutions||ad(r,"pnpm.overrides"))}catch{return!1}},"hasPackageJsonDeps"),Ia=_((e,t)=>{const r=new Map;for(const n of t){const o=Xn(n.catalogName);if(!o)continue;const i=o.relativePath==="."?v(e,"package.json"):v(e,o.relativePath,"package.json");r.has(i)||r.set(i,[]);const s=r.get(i);s&&s.push({depType:o.depType,newRange:n.newRange,packageName:n.packageName})}for(const[n,o]of r){const i=ue(n);for(const{depType:s,newRange:a,packageName:c}of o)s.includes(".")?Fy(i,s,c,a):i[s]&&(i[s][c]=a);Zi(n,i,{detectIndent:!0,overwrite:!0})}},"applyPackageJsonUpdates"),Uy=_((e,t)=>t==="bun"?Py(e)||wi(e):t==="npm"||t==="yarn"?wi(e):Iy(e)||wi(e),"hasCatalogs"),Jo=_((e,t,r)=>{let n;t==="bun"?n=My(e):t==="npm"||t==="yarn"?n=new Map:n=Oy(e);const o=_y(e,r);for(const[i,s]of o)n.has(i)||n.set(i,s);return n},"readCatalogs"),Oa=_(e=>{const t=new Map,r=new Map;let n="https://registry.npmjs.org";for(const o of e.split(`
105
- `)){const i=o.trim();if(!i||i.startsWith("#")||i.startsWith(";"))continue;const s=i.indexOf("=");if(s===-1)continue;const a=i.slice(0,s).trim(),c=i.slice(s+1).trim(),d=vy.exec(a);if(d?.[1]){t.set(d[1],c);continue}if(a==="registry"){n=c;continue}const p=wy.exec(a);p?.[1]&&r.set(p[1],c)}return{authTokens:r,defaultRegistry:n,registries:t}},"parseNpmrc"),Wy=_((e,t)=>({authTokens:new Map([...e.authTokens,...t.authTokens]),defaultRegistry:t.defaultRegistry==="https://registry.npmjs.org"?e.defaultRegistry:t.defaultRegistry,registries:new Map([...e.registries,...t.registries])}),"mergeNpmrcConfigs"),$s=_(e=>{const t={authTokens:new Map,defaultRegistry:"https://registry.npmjs.org",registries:new Map},r=process.env.HOME??process.env.USERPROFILE??"",n=v(r,".npmrc");let o=r&&E(n)?Oa(q(n)):t;const i=v(e,".npmrc");return E(i)&&(o=Wy(o,Oa(q(i)))),o},"loadNpmrc"),Gy=_((e,t)=>{let r=t.defaultRegistry;if(e.startsWith("@")){const o=e.split("/")[0];if(o&&t.registries.has(o)){const i=t.registries.get(o);i&&(r=i)}}const n=r.replace($y,"").replace(Zl,"");return{token:t.authTokens.get(n),url:r}},"getRegistryForPackage"),cd=15e3,ld=_(async(e,t,r=cd,n=!1)=>{const o=`${(t?.url??"https://registry.npmjs.org").replace(Zl,"")}/${e}`,i=n?{Accept:"application/json"}:{Accept:"application/vnd.npm.install-v1+json"};t?.authToken&&(i.Authorization=`Bearer ${t.authToken}`);const s=new AbortController,a=setTimeout(()=>{s.abort()},r);try{const c=await fetch(o,{headers:i,signal:s.signal});if(!c.ok)throw new Error(`Failed to fetch ${e}: ${String(c.status)} ${c.statusText}`);const d=await c.json(),p={latest:d["dist-tags"]?.latest??"",versions:Object.keys(d.versions??{})};return n&&d.time&&(p.publishTimes=new Map(Object.entries(d.time))),p}finally{clearTimeout(a)}},"fetchPackageVersions"),Hy=_(e=>{const t=e.database_specific?.severity?.toUpperCase();if(t==="CRITICAL"||t==="HIGH"||t==="MODERATE"||t==="LOW")return t;const r=e.severity?.find(n=>n.type==="CVSS_V3")?.score;if(r){const n=Number.parseFloat(r);return n>=9?"CRITICAL":n>=7?"HIGH":n>=4?"MODERATE":"LOW"}return"UNKNOWN"},"mapOsvSeverity"),zy=_(e=>{const t=e.severity?.find(r=>r.type==="CVSS_V3")?.score;return t?Number.parseFloat(t):void 0},"mapOsvCvss"),qy=_(e=>{const t=[];for(const r of e.affected??[])for(const n of r.ranges??[])for(const o of n.events??[])o.fixed&&t.push(o.fixed);return t},"mapOsvFixedVersions"),Jy=_(e=>({aliases:e.aliases?.length?e.aliases:void 0,cvssScore:zy(e),fixedVersions:qy(e),id:e.id,severity:Hy(e),summary:e.summary??""}),"mapOsvVuln"),Yo=_(async(e,t=1e4)=>{if(e.length===0)return new Map;const r=e.map(i=>({package:{ecosystem:"npm",name:i.name},version:i.version})),n=new AbortController,o=setTimeout(()=>{n.abort()},t);try{const i=await fetch("https://api.osv.dev/v1/querybatch",{body:JSON.stringify({queries:r}),headers:{"Content-Type":"application/json"},method:"POST",signal:n.signal});if(!i.ok)return new Map;const s=await i.json(),a=new Map;for(const[c,d]of e.entries()){const p=s.results[c]?.vulns;p&&p.length>0&&a.set(d.name,p.map(g=>Jy(g)))}return a}catch{return new Map}finally{clearTimeout(o)}},"fetchVulnerabilities"),Pa=new Map,Yy=_((e,t,r)=>{if(!r)return t;const n=r[e];if(n!==void 0)return n;for(const[o,i]of Object.entries(r))if(o!==e){if(o.startsWith("/")&&o.endsWith("/")){let s=Pa.get(o);if(s||(s=new RegExp(o.slice(1,-1)),Pa.set(o,s)),s.test(e))return i}else if(Mn(e,o))return i}return t},"resolvePackageTarget"),dd=_((e,t,r)=>{const n=t?.get(e);return n?Date.now()-new Date(n).getTime()<r:!1},"isTooNew"),Ky=_(e=>e?.minimumReleaseAge?e.packageName&&e.minimumReleaseAgeExclude?.some(t=>Mn(e.packageName,t))?0:e.minimumReleaseAge*60*1e3:0,"resolveMinAgeMs"),Na=_((e,t,r,n,o,i)=>e.map(s=>({parsed:Qt(s),raw:s})).filter(s=>!s.parsed||!r&&s.parsed.prerelease!==""||!rd(t,s.parsed)||n&&dd(s.raw,o,n)?!1:i?i(s.parsed):!0).toSorted((s,a)=>Cp(s.raw,a.raw))[0]?.raw,"filterCandidates"),Xy=_((e,t,r,n,o,i)=>{const s=Qt(r);if(!s)return;const a=Ky(i);if(n==="latest"){const d=Qt(t);return!d||!o&&d.prerelease!==""||!rd(s,d)?void 0:!a||!dd(t,i?.publishTimes,a)?t:Na(e,s,o,a,i?.publishTimes)}const c=n==="patch"?d=>d.major===s.major&&d.minor===s.minor:d=>d.major===s.major;return Na(e,s,o,a,i?.publishTimes,c)},"findTargetVersion"),Qy=_((e,t)=>{const r=[],n=new Set;for(const[o,i]of e)for(const[s,a]of i)if(!(a.startsWith("workspace:")||a.startsWith("file:")||a.startsWith("link:")||a==="*")&&!(!t.includeLocked&&!bs(a))){if(t.ignore.some(c=>Mn(s,c))){n.add(s);continue}Ey(s,t.include,t.exclude)&&r.push({catalogName:o,packageName:s,range:a})}return{entries:r,ignored:[...n]}},"collectEntries"),Zy=_(async(e,t,r,n=!1)=>{const o=new Map,i=[],s=8;let a=0;for(let c=0;c<e.length;c+=s){const d=e.slice(c,c+s),p=await Promise.allSettled(d.map(async g=>{const h=t?Gy(g,t):void 0,y=await ld(g,h?{authToken:h.token,url:h.url}:void 0,cd,n);return o.set(g,y),g}));for(const[g,h]of p.entries())if(a+=1,h.status==="rejected"){const y=d[g];y&&i.push(y)}r&&r(a,e.length)}return{failed:i,versionCache:o}},"fetchVersionsBatched"),Ma=_((e,t,r)=>{const n=[];for(const o of e){const i=t.get(o.packageName);if(!i)continue;const s=Yy(o.packageName,r.target,r.packageMode),a=Xy(i.versions,i.latest,o.range,s,r.includePrerelease,{minimumReleaseAge:r.minimumReleaseAge,minimumReleaseAgeExclude:r.minimumReleaseAgeExclude,packageName:o.packageName,publishTimes:i.publishTimes});if(!a)continue;const c=Qt(o.range),d=Qt(a);if(!c||!d)continue;const p=td(c,d);if(p==="none")continue;const g=bs(o.range);n.push({catalogName:o.catalogName,currentRange:o.range,newRange:`${g}${a}`,packageName:o.packageName,targetVersion:a,updateType:p})}return n},"buildOutdatedEntries"),Da=_(e=>e?Cy(e):"","formatVersionString"),ev=_(async(e,t,r,n)=>{const o=[...new Map(t.map(c=>{const d=Qt(c.range);return[c.packageName,{name:c.packageName,version:Da(d)}]})).values()].filter(c=>c.version),i=r?pn(o,r):void 0,[s,a]=await Promise.all([Yo(o),i]);for(const c of e){const d=s.get(c.packageName);d&&d.length>0&&(c.vulnerabilities=d);const p=Qt(c.currentRange),g=Da(p);if(a){const h=a.get(`${c.packageName}@${g}`);h&&(c.socketReport={alerts:h.alerts,license:h.license,score:h.score})}if(n){const h=fs(c.packageName,g,n);h&&(c.acceptedRisk=h)}}},"enrichWithSecurity"),tv=6e4,rv=_((e,t,r,n)=>{const o=[];for(const[a,c]of e)for(const[d,p]of c)o.push(`${a}:${d}=${p}`);if(o.push(`target=${t.target},pre=${String(t.includePrerelease)},sec=${String(t.security??!1)}`),o.push(`in=${t.include.join(",")},ex=${t.exclude.join(",")},ig=${t.ignore.join(",")}`),o.push(`locked=${String(t.includeLocked)}`),o.push(`mra=${String(t.minimumReleaseAge??0)}`),t.packageMode){const a=Object.entries(t.packageMode).map(([c,d])=>`${c}=${d}`).toSorted().join(",");o.push(`pkgMode=${a}`)}o.push(`socket=${String(r??!1)}`),n&&n.length>0&&o.push(`risks=${n.toSorted().join(",")}`);let i=5381;const s=o.join("|");for(let a=0;a<s.length;a++)i=(i<<5)+i+s.charCodeAt(a)|0;return String(i)},"computeCacheHash"),ud=_(e=>{const t=al("vis",{create:!0,cwd:e});return t?v(t,"outdated-cache.json"):void 0},"getOutdatedCachePath"),nv=_((e,t)=>{const r=ud(e);if(!(!r||!E(r)))try{const n=ue(r);if(n.hash===t&&Date.now()-n.timestamp<tv)return n.result}catch{}},"readOutdatedCache"),ov=_((e,t,r)=>{const n=ud(e);if(n)try{Se(Lt(n)),Zi(n,{hash:t,result:r,timestamp:Date.now()})}catch{}},"writeOutdatedCache"),xs=_(async(e,t,r,n,o,i,s)=>{const a=rv(e,t,!!i,s?Object.keys(s):void 0);if(o){const x=nv(o,a);if(x)return x}const{entries:c,ignored:d}=Qy(e,t),p=[...new Set(c.map(x=>x.packageName))],g=!!(t.minimumReleaseAge&&t.minimumReleaseAge>0),{failed:h,versionCache:y}=await Zy(p,r,n,g),w=Ma(c,y,t);let k=[];if(t.target!=="latest"){const x=new Set(w.map(I=>I.packageName)),T={...t,packageMode:void 0,target:"latest"};k=Ma(c,y,T).filter(I=>!x.has(I.packageName))}(t.security||i)&&w.length>0&&await ev(w,c,i,s);const $={checkedCount:p.length,failed:h,filteredByTarget:k,ignored:d,outdated:w};return o&&ov(o,a,$),$},"checkOutdated"),Ss=_((e,t)=>t==="bun"?v(e,"package.json"):v(e,"pnpm-workspace.yaml"),"getCatalogFilePath"),Ba=_((e,t)=>{const r=ks(e),n=new Set;for(const o of t){const i=Xn(o.catalogName);i&&n.add(i.relativePath==="."?"package.json":v(i.relativePath,"package.json"))}if(n.size!==0){Se(r);for(const o of n){const i=v(e,o);if(E(i)){const s=v(r,o),a=Lt(s);Se(a),Z(s,q(i))}}return r}},"createPackageJsonBackup"),iv=_((e,t,r)=>{if((t==="npm"||t==="yarn")&&r)return Ba(e,r);let n;const o=Ss(e,t);if(E(o)&&(n=`${o}.bak`,Z(n,q(o))),r){const i=r.filter(s=>Xn(s.catalogName));i.length>0&&Ba(e,i)}return n},"createBackup"),sv=_(e=>{const t=ks(e);if(!E(t))return!1;for(const r of Un(t,{includeDirs:!1})){const n=r.path.slice(t.length+1),o=v(e,n);Z(o,q(r.path))}return lp(t),!0},"restorePackageJsonBackup"),av=_((e,t)=>{if(t==="npm"||t==="yarn")return sv(e);const r=Ss(e,t),n=`${r}.bak`;if(!E(n))return!1;const o=q(n);return Z(r,o),!0},"restoreFromBackup"),cv=_((e,t)=>{if(t==="npm"||t==="yarn")try{const n=ks(e);return E(n)}catch{return!1}const r=Ss(e,t);return E(`${r}.bak`)},"hasBackup"),lv=_(e=>JSON.stringify(e,void 0,2),"formatOutdatedJson"),pd=_(e=>e.map(t=>`${t.packageName} ${t.currentRange} → ${t.newRange}`).join(`
106
- `),"formatOutdatedMinimal"),bt=_(e=>e?Array.isArray(e)?e:[e]:[],"toFilterArray"),dv=_(e=>{const t=new Map;for(const r of e){t.has(r.catalogName)||t.set(r.catalogName,[]);const n=t.get(r.catalogName);n&&n.push(r)}return t},"groupByCatalog"),uv=_(e=>{const t=Xn(e);return t?`${t.relativePath==="."?"root":t.relativePath} (${t.depType})`:`Catalog: ${e}`},"formatCatalogDisplayName"),fd=_((e,t)=>{const r=dv(e),n=process.stdout.columns||80,o=e.some(i=>i.socketReport);for(const[i,s]of r){const a=s.flatMap(p=>{const g=p.vulnerabilities&&p.vulnerabilities.length>0,h=p.socketReport&&p.socketReport.alerts.length>0,y=`${g||h?"[SEC] ":""}${p.packageName}`,w=p.socketReport?`${String(Math.round(p.socketReport.score.overall*100))}%`:"",k={current:p.currentRange,package:y,target:p.newRange,type:p.updateType};o&&(k.score=w);const $=[k];if(p.vulnerabilities)for(const x of p.vulnerabilities){const T={current:x.summary,package:` ${x.severity} ${x.id}`,target:"",type:""};o&&(T.score=""),$.push(T)}if(p.socketReport)for(const x of p.socketReport.alerts){const T={current:x.category,package:` [${x.severity.toUpperCase()}] ${x.type}`,target:"",type:""};o&&(T.score=""),$.push(T)}return $}),c=uv(i),d=Oe(Q.createElement(os,{data:a}),{columns:n});t.info(`${c}
107
- ${d}
108
- `)}},"formatOutdatedTable"),Eo=_(e=>{let t=0,r=0,n=0,o=0,i=0,s=0;for(const g of e)g.updateType==="major"?t++:g.updateType==="minor"?r++:n++,g.vulnerabilities&&g.vulnerabilities.length>0&&o++,g.socketReport?.alerts.length&&i++,g.socketReport&&g.socketReport.score.overall<lr&&s++;const a=[];t&&a.push(`${String(t)} major`),r&&a.push(`${String(r)} minor`),n&&a.push(`${String(n)} patch`),o&&a.push(`${String(o)} with vulnerabilities`),i&&a.push(`${String(i)} with Socket.dev alerts`);const c=`Found ${String(e.length)} outdated (${a.join(", ")})`,d=process.stdout.columns||80,p=[Q.createElement(l,{bold:!0},"─ Summary"),Q.createElement(l,null,` ${c}`)];return s>0&&p.push(Q.createElement(l,{color:"yellow"},` ${String(s)} package${s===1?"":"s"} with low Socket.dev score (<${String(lr*100)}%)`)),Oe(Q.createElement(m,{flexDirection:"column",paddingX:1},...p),{columns:d})},"formatSummary"),pv=_((e,t)=>{const r=e.replaceAll(Aa,String.raw`\$&`),n=t.replaceAll(Aa,String.raw`\$&`);return new RegExp(String.raw`^(?:'${r}'|"${r}"|${r}):\s*['"]?${n}['"]?`)},"buildLineMatchRegex"),fv=_((e,t,r)=>pv(t,r).test(e),"lineMatchesPackage"),gv=_(e=>{const t=new Map;for(const r of e){t.has(r.catalogName)||t.set(r.catalogName,new Map);const n=t.get(r.catalogName);n&&n.set(r.packageName,{newRange:r.newRange,oldRange:r.currentRange})}return t},"buildUpdateMap"),Fa=_((e,t,r)=>{if(!r)return e;for(const[n,{newRange:o,oldRange:i}]of r)if(fv(t,n,i))return e.replace(i,o);return e},"applyLineUpdate"),mv=_((e,t,r,n)=>{const o=e.trimStart(),i=e.length-o.length;return o.length===0||o.startsWith("#")?e:t==="catalog"&&i>=2?Fa(e,o,n.get("default")):t==="catalogs"&&i>=4&&r?Fa(e,o,n.get(r)):e},"processYamlLineForUpdate"),hv=_((e,t)=>{const r=v(e,"pnpm-workspace.yaml"),n=q(r).split(`
109
- `),o=gv(t);let i="none",s="";const a=[];for(const c of n){const d=c.trimStart(),p=c.length-d.length;p===0&&d.length>0&&!d.startsWith("#")&&(i=id(d),i==="catalogs"&&(s="")),i==="catalogs"&&p===2&&d.endsWith(":")&&(s=d.slice(0,-1).trim().replaceAll(Ql,"")),a.push(mv(c,i,s,o))}Z(r,a.join(`
110
- `))},"applyPnpmCatalogUpdates");_(e=>{const t=xy.exec(e);if(!t)return 2;const r=t[1];return r?r.includes(" ")?r:r.length:2},"detectJsonIndent");const yv=_((e,t)=>{const r=v(e,"package.json"),n=ue(r);for(const o of t)if(o.catalogName==="default")n.workspaces?.catalog&&(n.workspaces.catalog[o.packageName]=o.newRange);else{const i=n.workspaces?.catalogs?.[o.catalogName];i&&(i[o.packageName]=o.newRange)}Zi(r,n,{detectIndent:!0,overwrite:!0})},"applyBunCatalogUpdates"),vv=_((e,t,r,n=!0)=>{let o;n&&(o=iv(e,r,t));const i=[],s=[];for(const a of t)Xn(a.catalogName)?s.push(a):i.push(a);return i.length>0&&(r==="npm"||r==="yarn"?Ia(e,i):r==="bun"?yv(e,i):hv(e,i)),s.length>0&&Ia(e,s),o},"applyCatalogUpdates"),wv=_(async e=>{const t=gt({input:process.stdin,output:process.stdout}),r=_(o=>new Promise(i=>{t.question(o,s=>{i(s.trim())})}),"ask");process.stdout.write(`
111
- Outdated catalog dependencies:
112
- `);for(const[o,i]of e.entries())i&&process.stdout.write(` ${String(o+1)}. ${i.packageName}: ${i.currentRange} → ${i.newRange} (${i.updateType})
113
- `);process.stdout.write(`
114
- `);const n=await r("Apply updates? [a]ll / [n]one / [s]elect: ");if(n.toLowerCase()==="a"||n.toLowerCase()==="all")return t.close(),e;if(n.toLowerCase()==="n"||n.toLowerCase()==="none")return t.close(),[];if(n.toLowerCase()==="s"||n.toLowerCase()==="select"){const o=await r("Enter numbers to apply (comma-separated): ");return t.close(),o.split(",").map(i=>Number.parseInt(i.trim(),10)-1).filter(i=>i>=0&&i<e.length).map(i=>e[i]).filter(i=>i!==void 0)}return t.close(),[]},"promptPackageSelection"),kv=/github\.com[/:]([\w.-]+)\/([\w.-]+?)(?:\.git|\/|$)/,gd=_(async(e,t=1e4)=>{const r=[],n=new AbortController,o=setTimeout(()=>{n.abort()},t);try{const i=e.map(async s=>{const a=`https://www.npmjs.com/package/${s.packageName}`;try{const c=await fetch(`https://registry.npmjs.org/${s.packageName}`,{headers:{Accept:"application/json"},signal:n.signal});if(!c.ok)return{npmUrl:a,packageName:s.packageName};const d=(await c.json()).repository?.url;if(!d)return{npmUrl:a,packageName:s.packageName};const p=kv.exec(d);if(!p)return{npmUrl:a,packageName:s.packageName,repoUrl:d};const g=p[1],h=p[2],y=`https://github.com/${g}/${h}/releases/tag/v${s.targetVersion}`;return{npmUrl:a,packageName:s.packageName,releaseUrl:y,repoUrl:`https://github.com/${g}/${h}`}}catch{return{npmUrl:a,packageName:s.packageName}}});r.push(...await Promise.all(i))}finally{clearTimeout(o)}return r},"fetchChangelogInfo");var bv=Object.defineProperty,$v=b((e,t)=>bv(e,"name",{value:t,configurable:!0}),"A$e");const xv=/^[\^~>=<]+/,Sv={argument:{description:"Package name to analyze (e.g., react)",name:"package",required:!0,type:String},description:"Analyze a single package update with AI",examples:[["vis analyze react","Analyze updating react to latest"],["vis analyze react 19.0.0","Analyze updating react to specific version"],["vis analyze react --ai-type security","Run security-focused analysis"],["vis analyze react --format json","Output as JSON"]],execute:$v(async({argument:e,logger:t,options:r,visConfig:n,workspaceRoot:o})=>{if(!o)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const i=e,s=i[0];if(!s)throw new Error("Package name is required. Usage: vis analyze <package> [version]");const a=i[1],{packageManager:c}=Mo(o);let d,p="default";const g=Jo(o,c);for(const[P,R]of g){const M=R.get(s);if(M){d=M,p=P;break}}if(!d)throw new Error(`Package "${s}" not found in any catalog or package.json. Make sure it exists in your workspace dependencies.`);let h;if(a)h=a;else{t.info(`Fetching latest version for ${s}...
115
- `);const P=await ld(s);if(!P.latest)throw new Error(`Could not determine latest version for "${s}".`);h=P.latest}const y=Qt(d),w=Qt(h);if(!y||!w)throw new Error(`Could not parse versions: current="${d}", target="${h}".`);const k=td(y,w);if(k==="none"){t.info(`${s} is already at ${h}. Nothing to analyze.`);return}const $=bs(d),x={catalogName:p,currentRange:d,newRange:`${$}${h}`,packageName:s,targetVersion:h,updateType:k},T=vs(r.aiType??"impact");if(T==="security"||r.security){t.info(`Checking for known vulnerabilities...
116
- `);const P=d.replace(xv,""),R=(await Yo([{name:s,version:P}])).get(s);R&&R.length>0&&(x.vulnerabilities=R);const M=Lr(n?.security?.socket);if(M){const L=(await pn([{name:s,version:P}],M)).get(`${s}@${P}`);L&&(x.socketReport={alerts:L.alerts,license:L.license,score:L.score})}}const I=await ws([x],t,n?.ai,T);(r.format??"table")==="json"?process.stdout.write(`${JSON.stringify(I,void 0,2)}
117
- `):t.info(jo(I))},"execute"),group:"System",name:"analyze",options:[{description:"AI analysis type: impact, security, compatibility, or recommend (default: impact)",name:"ai-type",type:String},{defaultValue:!1,description:"Check for known security vulnerabilities",name:"security",type:Boolean},{description:"Output format: table or json (default: table)",name:"format",type:String}]};var Cv=Object.defineProperty,it=b((e,t)=>Cv(e,"name",{value:t,configurable:!0}),"d$y");const md=it((e,t)=>{const r={errors:[],warnings:[]},{security:n}=e;if(!n)return r.warnings.push("No security settings configured. Use defineConfig() from '@visulima/vis/config' to get secure defaults automatically."),r;if((!n.allowBuilds||Object.keys(n.allowBuilds).length===0)&&r.warnings.push(t==="pnpm"?"security.allowBuilds is not configured. pnpm blocks build scripts by default since v10. Run 'vis approve-builds' to review.":"security.allowBuilds is not configured. Consider listing which packages are allowed to run install/postinstall scripts."),n.minimumReleaseAge===0&&r.warnings.push("security.minimumReleaseAge is explicitly set to 0. New packages can be installed immediately after publishing."),n.trustPolicy==="off"&&r.warnings.push("security.trustPolicy is explicitly set to 'off'. Packages whose trust level has decreased will not be blocked."),n.blockExoticSubdeps===!1&&r.warnings.push("security.blockExoticSubdeps is explicitly disabled. Transitive dependencies can pull code from git repos or tarball URLs."),n.strictDepBuilds===!1&&r.warnings.push("security.strictDepBuilds is explicitly disabled. Unapproved build scripts will only produce warnings, not errors."),n.strictDepBuilds&&(!n.allowBuilds||Object.keys(n.allowBuilds).length===0)&&r.errors.push("security.strictDepBuilds is enabled but security.allowBuilds is empty. All dependencies with build scripts will be blocked. Run 'vis approve-builds' to review and add packages."),n.socket?.acceptedRisks){const o=Date.now();for(const[i,s]of Object.entries(n.socket.acceptedRisks)){const a=new Date(s.acceptedAt).getTime();o-a>7776e6&&r.warnings.push(`Accepted risk for "${i}" is over 90 days old (accepted ${s.acceptedAt}). Consider re-evaluating with 'vis audit'.`)}}return r},"checkSecurityConfig"),jv=it((e,t)=>{if(ft&&!process.env.VIS_SECURITY_WARNINGS)return;const r=md(e,t);for(const n of r.errors)ur(n);r.warnings.length>0&&se(`${r.warnings.length} security recommendation${r.warnings.length===1?"":"s"} found. Run 'vis check --security-config' for details.`)},"emitSecurityWarnings"),Ev=it((e,t)=>{const r=md(e,t),{security:n}=e;if(n){if(S("Active security settings:"),S(` minimumReleaseAge: ${n.minimumReleaseAge??"not set"} minutes`),S(` trustPolicy: ${n.trustPolicy??"not set"}`),S(` trustPolicyIgnoreAfter: ${n.trustPolicyIgnoreAfter??"not set"} minutes`),S(` blockExoticSubdeps: ${n.blockExoticSubdeps??!1}`),S(` strictDepBuilds: ${n.strictDepBuilds??!1}`),S(` allowBuilds: ${n.allowBuilds?`${Object.keys(n.allowBuilds).length} entries`:"not configured"}`),S(""),S("Socket.dev integration:"),S(` socket.enabled: ${n.socket?.enabled??!1}`),S(` socket.apiToken: ${n.socket?.apiToken||process.env.VIS_SOCKET_TOKEN?"configured":"using public token"}`),S(` socket.minimumScore: ${n.socket?.minimumScore??"default (0.4)"}`),S(` socket.cacheTtlMs: ${n.socket?.cacheTtlMs??"default (1 hour)"}`),S(` socket.timeoutMs: ${n.socket?.timeoutMs??"default (15s)"}`),n.socket?.acceptedRisks){const o=Object.entries(n.socket.acceptedRisks);S(` socket.acceptedRisks: ${String(o.length)} entr${o.length===1?"y":"ies"}`);for(const[i,s]of o)S(` ${i}: ${s.reason} (accepted ${s.acceptedAt.slice(0,10)})`)}else S(" socket.acceptedRisks: none");S("")}if(r.errors.length===0&&r.warnings.length===0){S("All recommended security settings are configured.");return}for(const o of r.errors)ur(o);for(const o of r.warnings)se(o);ie(""),ie("Secure defaults are applied by defineConfig(). You only need to add allowBuilds:"),ie(""),ie(" import { defineConfig } from '@visulima/vis/config';"),ie(""),ie(" export default defineConfig({"),ie(" security: {"),ie(" allowBuilds: {"),ie(" esbuild: true,"),ie(" '@prisma/client': true,"),ie(" },"),ie(" },"),ie(" });")},"printSecurityReport"),Tv=it(e=>{const{security:t}=e;if(!t)return[];const r=[];return t.minimumReleaseAge!==void 0&&r.push(`minimumReleaseAge: ${t.minimumReleaseAge}`),t.trustPolicy&&t.trustPolicy!=="off"&&r.push(`trustPolicy: ${t.trustPolicy}`),t.blockExoticSubdeps&&r.push("blockExoticSubdeps: true"),t.allowBuilds&&r.push(`allowBuilds: ${Object.keys(t.allowBuilds).length} entries`),t.strictDepBuilds&&r.push("strictDepBuilds: true"),t.trustPolicyIgnoreAfter!==void 0&&r.push(`trustPolicyIgnoreAfter: ${t.trustPolicyIgnoreAfter}`),r},"previewPnpmSync"),hd=it((e,t)=>{const r=v(e,"node_modules");if(!E(r))return[];const n=[],o=it((i,s="")=>{let a;try{a=Ve(i)}catch{return}for(const c of a){const d=v(i,c);if(c.startsWith("@")){o(d,`${c}/`);continue}if(c.startsWith("."))continue;const p=s+c,g=v(d,"package.json");try{if(!Mt(d).isDirectory()||!E(g))continue;const h=ue(g).scripts??{};if(!h.preinstall&&!h.install&&!h.postinstall&&!h.prepare)continue;if(!Object.entries(t).some(([y,w])=>w?y===p?!0:y.endsWith("*")?p.startsWith(y.slice(0,-1)):!1:!1)){const y=["preinstall","install","postinstall","prepare"].filter(w=>h[w]);n.push(`${p} (${y.join(", ")})`)}}catch{}}},"scanDir");return o(r),n},"scanUnapprovedBuildScripts"),yd=it(e=>E(v(e,".yarnrc.yml")),"isYarnBerry"),Rv=it((e,t,r)=>{const n={extraArgs:[],postInstallPackages:[],scriptsBlockedByDefault:!1,warnings:[]},o=r.security?.allowBuilds??{},i=Object.keys(o).length>0;switch(e){case"bun":{if(n.scriptsBlockedByDefault=!0,i){const s=v(t,"package.json");try{(E(s)?ue(s):{}).trustedDependencies?.length||n.warnings.push("vis security.allowBuilds is configured but trustedDependencies is empty. Run 'vis approve-builds --sync-native'.")}catch{}}break}case"npm":{n.scriptsBlockedByDefault=!1;const s=v(t,".npmrc"),a=E(s)&&/^\s*ignore-scripts\s*=\s*true\s*$/m.test(q(s));if(!a&&i?(n.warnings.push("npm does not block lifecycle scripts. vis will add --ignore-scripts automatically."),n.extraArgs.push("--ignore-scripts")):!a&&!i&&n.warnings.push("npm does not block lifecycle scripts. Add 'ignore-scripts=true' to .npmrc and configure security.allowBuilds."),i)for(const[c,d]of Object.entries(o))d&&n.postInstallPackages.push(c);break}case"pnpm":{n.scriptsBlockedByDefault=!0,i||n.warnings.push("pnpm blocks build scripts by default. Run 'vis approve-builds' to review packages that need scripts.");break}case"yarn":{if(n.scriptsBlockedByDefault=!1,yd(t)){const s=q(v(t,".yarnrc.yml"));/^\s*enableScripts\s*:\s*false\s*$/m.test(s)?n.scriptsBlockedByDefault=!0:n.warnings.push("yarn berry supports enableScripts. Add 'enableScripts: false' to .yarnrc.yml.")}else if(n.warnings.push("yarn classic does not support blocking lifecycle scripts. Consider upgrading to yarn berry."),i){n.extraArgs.push("--ignore-scripts");for(const[s,a]of Object.entries(o))a&&n.postInstallPackages.push(s)}break}}return n},"enforceScriptSecurity"),Cs=it((e,t,r)=>{const n=[],o=Object.entries(r).filter(([,i])=>i).map(([i])=>i);switch(e){case"bun":{const i=v(t,"package.json");if(E(i))try{const s=ue(i);s.trustedDependencies=o,Z(i,`${JSON.stringify(s,null,2)}
118
- `),n.push(`Updated package.json trustedDependencies with ${o.length} packages`)}catch(s){n.push(`Failed to update package.json: ${s instanceof Error?s.message:String(s)}`)}break}case"npm":{const i=v(t,".npmrc");let s=E(i)?q(i):"";/^\s*ignore-scripts\s*=\s*true\s*$/m.test(s)?n.push(".npmrc already has ignore-scripts=true"):(s=`${s.trimEnd()}
119
- ignore-scripts=true
120
- `,Z(i,s),n.push("Added ignore-scripts=true to .npmrc"));break}case"pnpm":{const i=v(t,"pnpm-workspace.yaml");if(!E(i)){n.push("pnpm-workspace.yaml not found. Cannot sync allowBuilds.");break}let s={};try{s=ln(i)?.allowBuilds??{}}catch{}const a={...s,...r},c=Object.keys(r).filter(k=>s[k]!==r[k]).length;if(c===0){n.push(`All ${String(Object.keys(r).length)} allowBuilds entries already present in pnpm-workspace.yaml.`);break}const d=Object.keys(a).sort(),p=it(k=>k.startsWith("@")||k.includes("/")||/[:#\s]/.test(k),"needsQuote"),g=it(k=>p(k)?`'${k.replaceAll("'","''")}'`:k,"renderKey"),h=`allowBuilds:
121
- ${d.map(k=>` ${g(k)}: ${String(a[k])}`).join(`
122
- `)}
123
- `;let y=q(i);y.endsWith(`
124
- `)||(y+=`
125
- `);const w=/^allowBuilds:[ \t]*\n(?:[ \t]{2}[^\n]*\n)*/m;y=w.test(y)?y.replace(w,h):`${y.trimEnd()}
126
-
127
- ${h}`,Z(i,y),n.push(`Updated pnpm-workspace.yaml allowBuilds (${String(c)} new, ${String(d.length)} total)`);break}case"yarn":{if(yd(t)){const i=v(t,".yarnrc.yml");let s=q(i);const a=/^\s*enableScripts\s*:/m.test(s),c=/^\s*enableScripts\s*:\s*false\s*$/m.test(s);a?c?n.push(".yarnrc.yml already has enableScripts: false"):(s=s.replace(/^\s*enableScripts\s*:.+$/m,"enableScripts: false"),Z(i,s),n.push("Changed enableScripts to false in .yarnrc.yml")):(s=`${s.trimEnd()}
128
- enableScripts: false
129
- `,Z(i,s),n.push("Added enableScripts: false to .yarnrc.yml"))}else{const i=v(t,".npmrc");let s=E(i)?q(i):"";/^\s*ignore-scripts\s*=\s*true\s*$/m.test(s)?n.push(".npmrc already has ignore-scripts=true"):(s=`${s.trimEnd()}
130
- ignore-scripts=true
131
- `,Z(i,s),n.push("Added ignore-scripts=true to .npmrc (yarn classic lacks enableScripts)"))}break}}return n},"syncAllowBuildsToNativeConfig"),Av=it((e,t)=>{const r=v(e,"node_modules"),n=[];for(const o of t){if(!o.endsWith("*")){n.push(o);continue}const i=o.slice(0,-1);try{if(i.startsWith("@")&&i.endsWith("/")){const s=v(r,i.slice(0,-1));for(const a of Ve(s))!a.startsWith(".")&&Mt(v(s,a)).isDirectory()&&n.push(`${i.slice(0,-1)}/${a}`)}else for(const s of Ve(r))s.startsWith(i)&&Mt(v(r,s)).isDirectory()&&n.push(s)}catch{}}return n},"expandPatterns"),Iv=it((e,t)=>{if(t.length===0)return;const r=Av(e,t);if(r.length===0)return;const n=v(e,"node_modules");let o=!1;for(const i of r){if(i.includes("..")||i.startsWith("/")||i.startsWith("\\")){se(`Skipping invalid package name: ${i}`);continue}const s=(i.match(/\//g)||[]).length;if(s>1||s===1&&!i.startsWith("@")){se(`Skipping invalid package name: ${i}`);continue}const a=v(n,i),c=v(a,"package.json");if(E(c))try{const d=ue(c).scripts??{};for(const p of["preinstall","install","postinstall"])if(d[p]){S(`Running ${p} for ${i}...`);try{zn(d[p],{cwd:a,env:{...process.env},stdio:"inherit"})}catch{ur(`${p} script failed for ${i}`),o=!0}}}catch{}}o&&(process.exitCode=1)},"runApprovedScripts");var Ov=Object.defineProperty,Pv=b((e,t)=>Ov(e,"name",{value:t,configurable:!0}),"l$o");const Nv={description:"Review and approve dependencies with build scripts",examples:[["vis approve-builds","Scan and list unapproved build scripts"],["vis approve-builds --all","Approve all pending builds (pnpm)"],["vis approve-builds --sync-native","Sync allowBuilds to native PM config"]],execute:Pv(async({options:e,visConfig:t,workspaceRoot:r})=>{const n=r??process.cwd(),o=Ne(n);if(o.name==="pnpm"&&!e.scan){S("Delegating to pnpm approve-builds...");const i=["approve-builds"];e.all&&i.push("--all");const s=De("pnpm",i,{cwd:n,stdio:"inherit"});if(s.error)throw new Error(`Failed to run pnpm approve-builds: ${s.error.message}`);if(s.status!==0&&s.status!==null&&(ur(`pnpm approve-builds exited with code ${s.status}`),process.exitCode=s.status),!e.syncNative){ie(""),ie("Tip: vis.config.ts security.allowBuilds may now be out of sync with pnpm-workspace.yaml."),ie("Run 'vis check --security-config' to compare, or copy the new entries into vis.config.ts.");return}}else{const i=t?.security?.allowBuilds??{},s=hd(n,i);if(s.length===0)ee("No unapproved build scripts found.");else{se(`Found ${s.length} package${s.length===1?"":"s"} with unapproved build scripts:
132
- `);for(const a of s)S(` ${a}`);ie(""),ie("To approve these packages, add them to vis.config.ts:"),ie(""),ie(" security: {"),ie(" allowBuilds: {");for(const a of s){const c=a.split(" (")[0];ie(` "${c}": true,`)}ie(" },"),ie(" },"),o.name==="pnpm"&&(ie(""),ie("Or run 'pnpm approve-builds' to update pnpm-workspace.yaml directly."))}}if(e.syncNative){const i=t?.security?.allowBuilds??{};if(Object.keys(i).length===0)se("No security.allowBuilds configured in vis.config.ts. Nothing to sync.");else{const s=Cs(o.name,n,i);S("");for(const a of s)ee(a)}}},"execute"),group:"Security & Health",name:"approve-builds",options:[{defaultValue:!1,description:"Approve all pending builds without prompting (pnpm only)",name:"all",type:Boolean},{defaultValue:!1,description:"Force vis scanning even for pnpm (instead of delegating)",name:"scan",type:Boolean},{defaultValue:!1,description:"Sync allowBuilds to native PM config (bun: trustedDependencies, npm: .npmrc, yarn: .yarnrc.yml)",name:"sync-native",type:Boolean}]};var Mv=Object.defineProperty,yr=b((e,t)=>Mv(e,"name",{value:t,configurable:!0}),"o$j");const To=yr(e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],"toStringArray"),Bi=yr((e,t)=>{for(const r of t)if(r===e||r.endsWith("*")&&e.startsWith(r.slice(0,-1)))return!0;return!1},"matchesGlobList"),vd=yr(e=>{const t=v(e,"pnpm-workspace.yaml");if(!E(t))return{excludedPackages:[],ignoredAdvisories:[]};try{const r=ln(t);return{excludedPackages:[],ignoredAdvisories:[...To(r?.auditConfig?.ignoreCves),...To(r?.auditConfig?.ignoreGhsas)]}}catch{return{excludedPackages:[],ignoredAdvisories:[]}}},"readPnpmAuditExclusions"),wd=yr(e=>{const t=v(e,".yarnrc.yml");if(!E(t))return{excludedPackages:[],ignoredAdvisories:[]};try{const r=ln(t);return{excludedPackages:To(r?.npmAuditExcludePackages),ignoredAdvisories:To(r?.npmAuditIgnoreAdvisories)}}catch{return{excludedPackages:[],ignoredAdvisories:[]}}},"readYarnAuditExclusions"),Dv=yr((e,t)=>{switch(t){case"pnpm":return vd(e);case"yarn":return wd(e);default:return{excludedPackages:[],ignoredAdvisories:[]}}},"readNativeAuditExclusions"),La=yr((e,t,r)=>{if(Bi(e,t.ignoredAdvisories))return!0;if(r){for(const n of r)if(Bi(n,t.ignoredAdvisories))return!0}return!1},"isAdvisoryExcluded"),Bv=yr((e,t)=>Bi(e,t.excludedPackages),"isPackageExcluded"),Fv=yr((e,t,r)=>{if(r.length===0)return["No advisory IDs to sync."];const n=[];switch(e){case"bun":{n.push(`bun has no audit config file. Use CLI flags: bun audit ${r.map(o=>`--ignore ${o}`).join(" ")}`);break}case"npm":{n.push("npm has no native audit exclusion config. vis accepted risks are the only layer.");break}case"pnpm":{const o=v(t,"pnpm-workspace.yaml");if(!E(o)){n.push("pnpm-workspace.yaml not found. Cannot sync.");break}const i=vd(t),s=new Set(i.ignoredAdvisories.filter(k=>k.startsWith("CVE-"))),a=new Set(i.ignoredAdvisories.filter(k=>k.startsWith("GHSA-"))),c=r.filter(k=>k.startsWith("CVE-")),d=r.filter(k=>k.startsWith("GHSA-")),p=[...new Set([...s,...c])],g=[...new Set([...a,...d])],h=c.filter(k=>!s.has(k)).length,y=d.filter(k=>!a.has(k)).length;if(h===0&&y===0){n.push("All advisory IDs already present in pnpm-workspace.yaml.");break}let w=q(o);if(p.length>0){const k=` ignoreCves:
133
- ${p.map($=>` - ${$}`).join(`
134
- `)}
135
- `;/auditConfig:/.test(w)?w=/ignoreCves:/.test(w)?w.replace(/ignoreCves:\s*\n(?:\s+-\s+(?:\S.*|[\t\v\f \u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])\n)*/,k):w.replace(/auditConfig:\s*\n/,`auditConfig:
136
- ${k}`):w=`${w.trimEnd()}
137
-
138
- auditConfig:
139
- ${k}`,h>0&&n.push(`Added ${String(h)} new CVE${h===1?"":"s"} to pnpm-workspace.yaml (${String(p.length)} total)`)}if(g.length>0){const k=` ignoreGhsas:
140
- ${g.map($=>` - ${$}`).join(`
141
- `)}
142
- `;/auditConfig:/.test(w)&&(w=/ignoreGhsas:/.test(w)?w.replace(/ignoreGhsas:\s*\n(?:\s+-\s+(?:\S.*|[\t\v\f \u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])\n)*/,k):w.replace(/(auditConfig:[\s\S]*?)(\n\S|\n?$)/m,`$1${k}$2`)),y>0&&n.push(`Added ${String(y)} new GHSA${y===1?"":"s"} to pnpm-workspace.yaml (${String(g.length)} total)`)}Z(o,w);break}case"yarn":{const o=v(t,".yarnrc.yml");if(!E(o)){n.push(".yarnrc.yml not found. Cannot sync.");break}const i=wd(t),s=new Set(i.ignoredAdvisories),a=[...new Set([...s,...r])],c=r.filter(g=>!s.has(g)).length;if(c===0){n.push("All advisory IDs already present in .yarnrc.yml.");break}let d=q(o);const p=`npmAuditIgnoreAdvisories:
143
- ${a.map(g=>` - "${g}"`).join(`
144
- `)}
145
- `;d=/npmAuditIgnoreAdvisories:/.test(d)?d.replace(/npmAuditIgnoreAdvisories:\s*\n(?:\s+-\s+(?:\S.*|[\t\v\f \u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])\n)*/,p):`${d.trimEnd()}
146
-
147
- ${p}`,Z(o,d),n.push(`Synced ${String(c)} advisor${c===1?"y":"ies"} to .yarnrc.yml (${String(a.length)} total)`);break}default:n.push(`Unknown package manager: ${e}`)}return n},"syncAcceptedRisksToNativeConfig");var Lv=Object.defineProperty,Zt=b((e,t)=>Lv(e,"name",{value:t,configurable:!0}),"k$j");const kd=Zt(e=>{const t=v(e,"node_modules");if(!E(t))return[];const r=[],n=v(e,"package.json");let o=new Set;if(E(n))try{const s=ue(n);o=new Set(Object.keys(s.devDependencies??{}))}catch{}const i=Zt((s,a)=>{let c;try{c=Ve(s)}catch{return}for(const d of c){if(d.startsWith("."))continue;const p=v(s,d);if(d.startsWith("@")){i(p,`${d}/`);continue}const g=a+d,h=v(p,"package.json");try{if(!Mt(p).isDirectory()||!E(h))continue;const y=ue(h);y.version&&r.push({isDev:o.has(g),name:g,version:y.version});const w=v(p,"node_modules");E(w)&&i(w,"")}catch{}}},"scanDir");return i(t,""),r},"scanInstalledPackages"),Vv={bun:{file:"bun.lock",type:"bun"},npm:{file:"package-lock.json",type:"npm"},pnpm:{file:"pnpm-lock.yaml",type:"pnpm"},yarn:{file:"yarn.lock",type:"yarn"}},bd=Zt((e,t)=>{const r=Vv[t];if(!r)return[];let n;try{n=q(v(e,r.file))}catch{return[]}const o=Hc(n,r.type);if(o.length===0)return[];const i=new Map;for(const a of o)i.has(a.name)||i.set(a.name,new Set),i.get(a.name).add(a.version);const s=[];for(const[a,c]of i)c.size<=1||s.push({name:a,versions:[...c]});return s.sort((a,c)=>a.name.localeCompare(c.name))},"findDuplicateDependencies"),ki={CRITICAL:0,HIGH:1,LOW:3,MODERATE:2,UNKNOWN:4},_v={critical:Ge,high:Zc,low:ut,medium:Re},bi=Zt((e,t)=>{const r=ki[t.toUpperCase()]??ki.MODERATE??2;return(ki[e.toUpperCase()]??4)<=r},"severityPassesFilter"),Uv={CRITICAL:Ge,HIGH:Zc,LOW:ut,MODERATE:Re,UNKNOWN:$e},Wv=Zt((e,t,r,n)=>{const o=Uv[r.severity]??$e,i=n?` ${$e("[acknowledged]")}`:"",s=r.fixedVersions??[],a=s.length>0?` (fix: ${s.join(", ")})`:"";return` ${o(r.severity)} ${r.id} — ${e}@${t}${i}
148
- ${r.summary}${a}`},"formatVulnLine"),Gv=Zt((e,t)=>{const r=en(e),n=`${String(Math.round(e.score.overall*100))}%`,o=t?` ${$e("[acknowledged]")}`:"",i=e.alerts.length>0?`, ${String(e.alerts.length)} alert${e.alerts.length===1?"":"s"}`:"";return` ${n} ${r}@${e.version} (${ps(e.score.overall)}${i})${o}`},"formatSocketLine"),Hv=Zt(async(e,t,r,n)=>{const o=t.severity??"low",i=t.format==="json"||!!t.json,s=!!t.fix,a=!!t.showAccepted,c=r?.security?.socket,d=c?.acceptedRisks,p=Ne(e),g=Dv(e,p.name);(g.ignoredAdvisories.length>0||g.excludedPackages.length>0)&&S(`Loaded ${String(g.ignoredAdvisories.length)} ignored advisor${g.ignoredAdvisories.length===1?"y":"ies"} and ${String(g.excludedPackages.length)} excluded package${g.excludedPackages.length===1?"":"s"} from ${p.name} config.`),S("Scanning installed packages...");const h=kd(e);if(h.length===0){S("No packages found in node_modules. Run your package manager's install command first.");return}S(`Found ${String(h.length)} packages.
149
- `);const y=h.map(C=>({name:C.name,version:C.version})),w=Lr(c),k=bd(e,p.name),[$,x]=await Promise.all([Yo(y),w?pn(y,w):Promise.resolve(new Map)]),T=[];for(const C of h){if(Bv(C.name,g))continue;const j=$.get(C.name)??[],A=x.get(`${C.name}@${C.version}`),V=fs(C.name,C.version,d),N=j.length>0,F=A?A.score.overall<lr:!1,J=A?A.alerts.length>0:!1;(N||F||J)&&T.push({acceptedRisk:V,name:C.name,socketReport:A,version:C.version,vulnerabilities:j})}const I=T.filter(C=>{const j=C.vulnerabilities.some(N=>bi(N.severity,o)),A=C.socketReport?.alerts.some(N=>bi(N.severity==="medium"?"MODERATE":N.severity.toUpperCase(),o)),V=C.socketReport&&C.socketReport.score.overall<lr;return j||A||V});if(i){const C={duplicates:k.map(j=>({name:j.name,versionCount:j.versions.length,versions:j.versions})),packages:h.length,results:I.map(j=>({acceptedRisk:j.acceptedRisk??null,name:j.name,socketAlerts:j.socketReport?.alerts??[],socketScore:j.socketReport?.score.overall??null,version:j.version,vulnerabilities:j.vulnerabilities})),summary:{accepted:I.filter(j=>j.acceptedRisk).length,duplicatePackages:k.length,issues:I.filter(j=>!j.acceptedRisk).length,total:I.length}};process.stdout.write(`${JSON.stringify(C,void 0,2)}
150
- `),t.exitCode&&C.summary.issues>0&&(process.exitCode=1);return}if(I.length===0){ee(`No security issues found across ${String(h.length)} packages.`);return}const P={CRITICAL:[],HIGH:[],LOW:[],MODERATE:[]};for(const C of I)for(const j of C.vulnerabilities)if(bi(j.severity,o)){const A=j.severity==="UNKNOWN"?"LOW":j.severity;P[A]?.push({entry:C,vuln:j})}let R=0,M=0;for(const C of["CRITICAL","HIGH","MODERATE","LOW"]){const j=P[C];if(!(!j||j.length===0)){S(`
151
- ── ${C} (${String(j.length)}) ──`);for(const{entry:A,vuln:V}of j){const N=!!A.acceptedRisk||La(V.id,g,V.aliases);N&&(M++,!a)||(R++,S(Wv(A.name,A.version,V,N)),s&&(V.fixedVersions??[]).length>0&&ie(` Fix: update to ${V.fixedVersions.at(-1)}`))}}}const L=I.filter(C=>C.socketReport&&(C.socketReport.score.overall<lr||C.socketReport.alerts.length>0));if(L.length>0){S(`
152
- ── Socket.dev Supply Chain (${String(L.length)}) ──`);for(const C of L){if(!C.socketReport)continue;const j=!!C.acceptedRisk;if(!(j&&!a)){S(Gv(C.socketReport,j));for(const A of C.socketReport.alerts){const V=_v[A.severity]??$e;S(` ${V(`[${A.severity.toUpperCase()}]`)} ${A.type} — ${A.category}`)}}}}if(k.length>0){S(`
153
- ── Duplicate Dependencies (${String(k.length)}) ──`);for(const C of k){const j=C.versions.join(", ");S(` ${C.name} — ${String(C.versions.length)} versions: ${Re(j)}`)}}const U=Zt(C=>!!C.acceptedRisk||C.vulnerabilities.length>0&&C.vulnerabilities.every(j=>La(j.id,g,j.aliases)),"isEntryExcluded"),D=I.filter(C=>!U(C)).length;if(S(""),S("─ Audit Summary"),S(` ${String(h.length)} packages scanned`),g.ignoredAdvisories.length>0&&S(` ${String(g.ignoredAdvisories.length)} ${p.name} audit exclusion${g.ignoredAdvisories.length===1?"":"s"} applied`),R>0){const C=P.CRITICAL?.filter(A=>!U(A.entry)).length??0,j=P.HIGH?.filter(A=>!U(A.entry)).length??0;ur(` ${String(R)} vulnerabilit${R===1?"y":"ies"} found`),C>0&&ur(` ${String(C)} critical`),j>0&&se(` ${String(j)} high`)}else ee(" No vulnerabilities found");if(L.length>0){const C=L.filter(j=>!U(j)).length;se(` ${String(C)} package${C===1?"":"s"} with Socket.dev supply chain issues`)}if(k.length>0&&(se(` ${String(k.length)} package${k.length===1?"":"s"} with duplicate versions`),ie(" Run 'vis dedupe' or your package manager's dedupe command to reduce duplicates.")),M>0&&(S(` ${String(M)} acknowledged (accepted risks)`),a||ie(" Use --show-accepted to see acknowledged issues.")),D===0&&ee(`
154
- All issues are acknowledged. No action required.`),t.sync&&d){const C=new Set;for(const A of T)if(A.acceptedRisk){for(const V of A.vulnerabilities)if((V.id.startsWith("CVE-")||V.id.startsWith("GHSA-"))&&C.add(V.id),V.aliases)for(const N of V.aliases)(N.startsWith("CVE-")||N.startsWith("GHSA-"))&&C.add(N)}const j=[...C];if(j.length>0){S("");const A=Fv(p.name,e,j);for(const V of A)ee(` ${V}`)}else S(`
155
- No advisory IDs to sync to native PM config.`)}t.exitCode&&D>0&&(process.exitCode=1)},"executeAudit"),zv={description:"Audit installed packages for vulnerabilities and supply chain risks",examples:[["vis audit","Full audit of all installed packages"],["vis audit --severity high","Show only high/critical issues"],["vis audit --format json","Output as JSON for CI integration"],["vis audit --fix","Show fix suggestions for vulnerabilities"],["vis audit --exit-code","Exit with code 1 if issues found (for CI)"],["vis audit --show-accepted","Include acknowledged risks in output"],["vis audit --sync","Sync accepted risks to native PM config (pnpm-workspace.yaml / .yarnrc.yml)"]],execute:Zt(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!n)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");await Hv(n,t,r,e)},"execute"),group:"Security & Health",name:"audit",options:[{description:"Minimum severity to report: low, medium, high, critical (default: low)",name:"severity",type:String},{description:"Output format: table or json (default: table)",name:"format",type:String},{defaultValue:!1,description:"Show fix suggestions for vulnerabilities",name:"fix",type:Boolean},{defaultValue:!1,description:"Exit with code 1 if any issues found (for CI)",name:"exit-code",type:Boolean},{defaultValue:!1,description:"Include acknowledged (accepted risk) issues in output",name:"show-accepted",type:Boolean},{defaultValue:!1,description:"Sync vis accepted risks to native PM config (pnpm-workspace.yaml / .yarnrc.yml)",name:"sync",type:Boolean}]};var qv=Object.defineProperty,rn=b((e,t)=>qv(e,"name",{value:t,configurable:!0}),"e$8");const $d=rn((e,t,r)=>{const n=rn(o=>st(o)?o:xe(e,o),"normalize");return t&&t.length>0?n(t):r&&r.length>0?n(r):xe(e,fp)},"resolveCacheDirectory"),Jv=/[^\w.-]+/g,Yv=/^-+|-+$/g,Kv=rn(e=>e.trim().replaceAll(Jv,"-").replaceAll(Yv,"").slice(0,64),"sanitizeBranchSegment"),Xv=rn(e=>{try{const t=cl("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return!t||t==="HEAD"?void 0:t}catch{return}},"detectGitBranch"),Qv=rn((e,t,r)=>{if(r!==!0)return e;const n=Xv(t);if(!n)return e;const o=Kv(n);return o.length===0?e:xe(e,"branches",o)},"applyBranchScope"),Zv=rn((e,t)=>{const r=He(t,e);return r.length===0?!1:!(r===".."||r.startsWith("../"))&&!st(r)},"isCacheDirectoryInsideWorkspace");var ew=Object.defineProperty,lt=b((e,t)=>ew(e,"name",{value:t,configurable:!0}),"c$u");const xd=lt(async e=>{let t=0;try{const r=await ll(e,{withFileTypes:!0});for(const n of r){const o=v(e,n.name);if(n.isDirectory())t+=await xd(o);else if(n.isFile()){const i=await dl(o);t+=i.size}}}catch{}return t},"sumDirectorySize"),Dn=lt(async e=>{const t=[];let r;try{r=await ll(e)}catch{return[]}for(const n of r){if(n.startsWith("."))continue;const o=v(e,n);try{const i=await dl(o);if(!i.isDirectory())continue;const s=await xd(o);t.push({hash:n,mtimeMs:i.mtimeMs,path:o,sizeBytes:s})}catch{}}return t.sort((n,o)=>o.mtimeMs-n.mtimeMs),t},"collectCacheEntries"),tw=lt((e,t=Date.now())=>{const r=Math.floor((t-e)/1e3);return r<60?`${String(r)}s`:r<3600?`${String(Math.floor(r/60))}m`:r<86400?`${String(Math.floor(r/3600))}h`:`${String(Math.floor(r/86400))}d`},"formatAge"),rw=lt(e=>new Promise(t=>{const r=gt({input:process.stdin,output:process.stderr});r.question(`${e} (y/N) `,n=>{r.close();const o=n.trim().toLowerCase();t(o==="y"||o==="yes")})}),"confirmPrompt"),nw=lt(async(e,t,r)=>{if(!E(e)){if(t==="json"){process.stdout.write(`${JSON.stringify({directory:e,entries:[],totalBytes:0,totalCount:0},void 0,2)}
156
- `);return}S(`No cache directory found at ${e}`);return}const n=await Dn(e);if(n.length===0){if(t==="json"){process.stdout.write(`${JSON.stringify({directory:e,entries:[],totalBytes:0,totalCount:0},void 0,2)}
157
- `);return}S(`Cache directory is empty: ${e}`);return}const o=n.reduce((p,g)=>p+g.sizeBytes,0);if(t==="json"){const p=Date.now();process.stdout.write(`${JSON.stringify({directory:e,entries:n.map(g=>({ageMs:p-g.mtimeMs,hash:g.hash,mtimeIso:new Date(g.mtimeMs).toISOString(),sizeBytes:g.sizeBytes})),totalBytes:o,totalCount:n.length},void 0,2)}
158
- `);return}S(`Cache directory: ${e}`),S(`Entries: ${String(n.length)} (${On(o,{decimals:1,space:!1})})`),r.info("");const i=Date.now(),s=n.map(p=>({age:tw(p.mtimeMs,i),hash:p.hash.slice(0,12),size:On(p.sizeBytes,{decimals:1,space:!1})})),a=Math.max(4,...s.map(p=>p.hash.length)),c=Math.max(4,...s.map(p=>p.size.length)),d=Math.max(3,...s.map(p=>p.age.length));r.info(` ${"hash".padEnd(a)} ${"size".padEnd(c)} ${"age".padEnd(d)}`),r.info(` ${"-".repeat(a)} ${"-".repeat(c)} ${"-".repeat(d)}`);for(const p of s)r.info(` ${p.hash.padEnd(a)} ${p.size.padEnd(c)} ${p.age.padEnd(d)}`)},"runList"),ow=lt(async(e,t,r)=>{if(!E(e)){S(`No cache directory to clean at ${e}`);return}if(r.dryRun){const o=await Dn(e),i=o.reduce((s,a)=>s+a.sizeBytes,0);S(`Would remove ${String(o.length)} cache entr${o.length===1?"y":"ies"} (${On(i,{decimals:1,space:!1})}) from ${e}`);return}const n=Zv(e,t);try{const o=await ia(e),i=await ia(t);if(o===i){Ze("Refusing to delete the workspace root. The cache directory resolved to the same path as the workspace."),process.exitCode=1;return}}catch{}if(!n&&!r.force){if(se(`Cache directory is outside the workspace root: ${e}`),se("This will recursively delete the entire directory, including anything stored there by other tools."),!process.stdin.isTTY){Ze("Refusing to clean an out-of-workspace cache without --force (stdin is not a TTY)."),process.exitCode=1;return}if(!await rw(" Continue?")){S("Aborted.");return}}n?await new Yc({cacheDirectory:e,workspaceRoot:t}).clear():await Up(e,{force:!0,recursive:!0}),ee(`Cleared cache: ${e}`)},"runClean"),iw=lt(async(e,t,r)=>{if(!E(e)){S(`No cache directory to prune at ${e}`);return}if(r.maxCacheAgeDays!==void 0&&(!Number.isFinite(r.maxCacheAgeDays)||r.maxCacheAgeDays<0)){Ze(`Invalid --max-age-days value: expected a finite number >= 0, got ${String(r.maxCacheAgeDays)}`),process.exitCode=1;return}if(r.maxCacheSize!==void 0){let p;try{p=gp(r.maxCacheSize)}catch(g){Ze(`Invalid --max-size value: ${g instanceof Error?g.message:String(g)}`),process.exitCode=1;return}if(!Number.isFinite(p)||p<=0){Ze(`Invalid --max-size value: expected a positive size, got "${r.maxCacheSize}" (${String(p)} bytes)`),process.exitCode=1;return}}const n=r.maxCacheAgeDays===void 0?void 0:r.maxCacheAgeDays*24*60*60*1e3,o=await Dn(e),i=o.reduce((p,g)=>p+g.sizeBytes,0);await new Yc({cacheDirectory:e,maxCacheAge:n,maxCacheSize:r.maxCacheSize,workspaceRoot:t}).removeOldEntries();const s=await Dn(e),a=s.reduce((p,g)=>p+g.sizeBytes,0),c=o.length-s.length,d=i-a;if(c<=0){S("Nothing to prune — all entries are within the configured limits.");return}ee(`Pruned ${String(c)} entr${c===1?"y":"ies"}, freed ${On(d,{decimals:1,space:!1})}.`)},"runPrune"),sw=lt(async(e,t)=>{if(!E(e)){if(t==="json"){process.stdout.write(`${JSON.stringify({directory:e,exists:!1,totalBytes:0,totalCount:0})}
159
- `);return}S(`No cache directory at ${e}`);return}const r=await Dn(e),n=r.reduce((o,i)=>o+i.sizeBytes,0);if(t==="json"){process.stdout.write(`${JSON.stringify({directory:e,exists:!0,totalBytes:n,totalCount:r.length})}
160
- `);return}S(`Cache directory: ${e}`),S(`Entries: ${String(r.length)}`),S(`Total size: ${On(n,{decimals:1,space:!1})}`)},"runSize"),Ko={description:"Cache directory (overrides config and default). Relative paths are resolved against the workspace root.",name:"cache-dir",type:String},Xo=lt((e,t,r)=>{const n=e??process.cwd(),o=(r??{}).taskRunnerOptions??{};return{cacheDirectory:$d(n,t.cacheDir,o.cacheDirectory),workspaceRoot:n}},"resolveCacheDirectoryFromContext"),aw={commandPath:["cache"],description:"List all cache entries",examples:[["vis cache list","List all cache entries"]],execute:lt(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{const{cacheDirectory:o}=Xo(n,t,r),i=t.format??"table";await nw(o,i,e)},"execute"),group:"Workspace",name:"list",options:[Ko,{description:"Output format: table or json (default: table)",name:"format",type:String}]},cw={commandPath:["cache"],description:"Remove all cache entries",examples:[["vis cache clean","Remove all cache entries"],["vis cache clean --dry-run","Preview what clean would remove"]],execute:lt(async({options:e,visConfig:t,workspaceRoot:r})=>{const{cacheDirectory:n,workspaceRoot:o}=Xo(r,e,t);await ow(n,o,{dryRun:!!e.dryRun,force:!!e.force})},"execute"),group:"Workspace",name:"clean",options:[Ko,{defaultValue:!1,description:"Preview without deleting",name:"dry-run",type:Boolean},{defaultValue:!1,description:"Skip the confirmation prompt for out-of-workspace cache directories",name:"force",type:Boolean}]},lw={commandPath:["cache"],description:"Remove old and oversized cache entries",examples:[["vis cache prune","Remove old and oversized entries"],["vis cache prune --max-age-days=3 --max-size=500MB","Prune with custom limits"]],execute:lt(async({options:e,visConfig:t,workspaceRoot:r})=>{const{cacheDirectory:n,workspaceRoot:o}=Xo(r,e,t);await iw(n,o,{maxCacheAgeDays:typeof e.maxAgeDays=="number"?e.maxAgeDays:void 0,maxCacheSize:e.maxSize})},"execute"),group:"Workspace",name:"prune",options:[Ko,{description:"Remove entries older than N days",name:"max-age-days",type:Number},{description:"Evict oldest entries until cache is under this size (e.g. 500MB)",name:"max-size",type:String}]},dw={commandPath:["cache"],description:"Print the cache directory's on-disk footprint",examples:[["vis cache size --format=json","Print total size as JSON"]],execute:lt(async({options:e,visConfig:t,workspaceRoot:r})=>{const{cacheDirectory:n}=Xo(r,e,t),o=e.format??"table";await sw(n,o)},"execute"),group:"Workspace",name:"size",options:[Ko,{description:"Output format: table or json (default: table)",name:"format",type:String}]},uw=[aw,cw,lw,dw];var pw=Object.defineProperty,fw=b((e,t)=>pw(e,"name",{value:t,configurable:!0}),"a$l");function Bn({current:e,total:t}){const{columns:r}=sn(),n=r||80,o=t>0?e/t:0,i=`${String(Math.round(o*100))}%`,s=Math.max(10,n-4),a=Math.round(s*o),c=s-a;return f(m,{flexDirection:"column",paddingX:1,children:[f(m,{children:[u(ns,{type:"dots"}),f(l,{children:[" ","Checking",String(t)," ","catalog dependencies"," "]}),f(l,{dimColor:!0,children:[String(e),"/",String(t)]})]}),f(m,{children:[u(l,{color:"cyan",children:"━".repeat(a)}),u(l,{dimColor:!0,children:"─".repeat(c)}),f(l,{children:[" ",i]})]})]})}b(Bn,"f$p");fw(Bn,"CheckProgressApp");var gw=Object.defineProperty,Rn=b((e,t)=>gw(e,"name",{value:t,configurable:!0}),"r$n");const po=Rn(e=>{const t=new Map;for(const r of e){const n=t.get(r.catalogName);n?n.push(r):t.set(r.catalogName,[r])}return t},"groupByCatalog"),fo=Rn((e,t,r)=>{let n=e;if(t!=="all"&&(n=t==="security"?n.filter(o=>o.vulnerabilities&&o.vulnerabilities.length>0||o.socketReport&&o.socketReport.alerts.length>0):n.filter(o=>o.updateType===t)),r){const o=r.toLowerCase();n=n.filter(i=>i.packageName.toLowerCase().includes(o))}return n},"filterEntries");class Sd{static{b(this,"UpdateStore")}static{Rn(this,"UpdateStore")}#e;#t=new Set;#n;#o=null;constructor(t,r=null){this.#n=t,r&&(this.#o=new Map(r.recommendations.map(n=>[n.package,n]))),this.#e={aiResult:r,allChecked:!0,applyProgress:null,checkedEntries:new Set(t.map(n=>n.packageName)),entries:t,error:null,filterActive:!1,filterText:"",filterType:"all",focusedPanel:"list",groupedByCatalog:po(t),phase:"browsing",selectedIndex:0}}getSnapshot=Rn(()=>this.#e,"getSnapshot");subscribe=Rn(t=>(this.#t.add(t),()=>{this.#t.delete(t)}),"subscribe");getFilteredEntries(){return fo(this.#n,this.#e.filterType,this.#e.filterText)}getRecommendation(t){return this.#o?.get(t)}getCheckedEntries(){return this.#n.filter(t=>this.#e.checkedEntries.has(t.packageName))}setSelectedIndex(t){const r=this.getFilteredEntries(),n=Math.max(0,Math.min(t,r.length-1));n!==this.#e.selectedIndex&&this.#r({...this.#e,selectedIndex:n})}setFocusedPanel(t){t!==this.#e.focusedPanel&&this.#r({...this.#e,focusedPanel:t})}setFilterType(t){if(t!==this.#e.filterType){const r=fo(this.#n,t,this.#e.filterText);this.#r({...this.#e,entries:r,filterType:t,groupedByCatalog:po(r),selectedIndex:0})}}setFilter(t){const r=fo(this.#n,this.#e.filterType,t);this.#r({...this.#e,entries:r,filterText:t,groupedByCatalog:po(r),selectedIndex:0})}setFilterActive(t){if(t!==this.#e.filterActive)if(t)this.#r({...this.#e,filterActive:!0});else{const r=fo(this.#n,this.#e.filterType,"");this.#r({...this.#e,entries:r,filterActive:!1,filterText:"",groupedByCatalog:po(r),selectedIndex:0})}}toggleCheck(t){const r=new Set(this.#e.checkedEntries);r.has(t)?r.delete(t):r.add(t),this.#r({...this.#e,allChecked:r.size===this.#n.length,checkedEntries:r})}checkAll(){this.#r({...this.#e,allChecked:!0,checkedEntries:new Set(this.#n.map(t=>t.packageName))})}uncheckAll(){this.#r({...this.#e,allChecked:!1,checkedEntries:new Set})}toggleAll(){this.#e.allChecked?this.uncheckAll():this.checkAll()}startApply(){const t=this.getCheckedEntries();this.#r({...this.#e,applyProgress:{current:0,total:t.length},phase:"applying"})}updateApplyProgress(t){this.#e.applyProgress&&this.#r({...this.#e,applyProgress:{...this.#e.applyProgress,current:t}})}markDone(){this.#r({...this.#e,phase:"done"})}setError(t){this.#r({...this.#e,error:t,phase:"error"})}#r(t){this.#e=t;for(const r of this.#t)try{r()}catch{}}}var mw=Object.defineProperty,hw=b((e,t)=>mw(e,"name",{value:t,configurable:!0}),"f$o");const Nr=hw(({autoExitSeconds:e,onCancel:t,visible:r})=>{const{exit:n}=an(),[o,i]=we(e||3),s=Ue(null),a=Ue(0);Pt(()=>(r&&(i(e||3),a.current=Date.now(),s.current=setInterval(()=>{i(d=>Math.max(0,d-1))},1e3)),()=>{s.current&&(clearInterval(s.current),s.current=null)}),[r,e]),Pt(()=>{o<=0&&r&&(s.current&&(clearInterval(s.current),s.current=null),n())},[o,r,n]);const c=Nt(()=>{s.current&&(clearInterval(s.current),s.current=null),t()},[t]);return kt((d,p)=>{Date.now()-a.current<200||(d==="q"?n():c())},{isActive:r}),u(Ar,{backgroundColor:"#1e1e1e",footer:f(l,{dimColor:!0,children:["Press"," ",u(l,{bold:!0,color:"white",children:"q"})," ","to exit,"," ",u(l,{bold:!0,color:"white",children:"any key"})," ","to stay"]}),title:`Exiting in ${o}…`,visible:r,width:50,children:u(l,{dimColor:!0,children:"Stay to explore the results interactively."})})},"QuitDialog");var yw=Object.defineProperty,vw=b((e,t)=>yw(e,"name",{value:t,configurable:!0}),"d$v");const ww={major:"red",minor:"yellow",patch:"green"},kw={CRITICAL:"red",HIGH:"red",LOW:"gray",MODERATE:"yellow",UNKNOWN:"gray"},bw={critical:"red",high:"red",low:"gray",medium:"yellow"},$w={critical:"red",high:"red",low:"green",medium:"yellow"},xw={defer:"gray",review:"yellow",skip:"red",update:"green"},Sw=vw(({changelogUrl:e,entry:t,focused:r,recommendation:n,scrollRef:o})=>{const i=r?"white":"gray";if(!t)return u(m,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:u(l,{dimColor:!0,children:"No package selected"})});const s=ww[t.updateType]??"white",a=t.vulnerabilities&&t.vulnerabilities.length>0,c=t.socketReport?.score.overall??0,d=t.socketReport?Jn(c):"gray";return f(m,{borderColor:i,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[u(m,{flexShrink:0,paddingTop:1,paddingX:2,children:u(l,{bold:!0,color:"white",children:t.packageName})}),f(cn,{flexGrow:1,flexShrink:1,paddingX:2,ref:o,scrollbar:!0,scrollbarColor:"gray",scrollbarStyle:"block",children:[u(l,{}),f(m,{children:[u(m,{width:12,children:u(l,{dimColor:!0,children:"Current:"})}),u(l,{children:t.currentRange})]}),f(m,{children:[u(m,{width:12,children:u(l,{dimColor:!0,children:"Target:"})}),u(l,{children:t.newRange}),f(l,{bold:!0,color:s,children:[" ","(",t.updateType,")"]})]}),f(m,{children:[u(m,{width:12,children:u(l,{dimColor:!0,children:"Version:"})}),u(l,{children:t.targetVersion})]}),f(m,{children:[u(m,{width:12,children:u(l,{dimColor:!0,children:"Catalog:"})}),u(l,{children:t.catalogName})]}),t.acceptedRisk&&f(m,{flexDirection:"column",marginTop:1,children:[u(l,{color:"gray",children:"── "}),u(l,{bold:!0,color:"gray",children:"ACKNOWLEDGED RISK"}),f(m,{flexDirection:"column",paddingLeft:2,children:[f(m,{children:[u(l,{dimColor:!0,children:"Reason: "}),u(l,{children:t.acceptedRisk.reason})]}),f(m,{children:[u(l,{dimColor:!0,children:"Accepted: "}),u(l,{children:t.acceptedRisk.acceptedAt.slice(0,10)})]})]})]}),a&&f(m,{flexDirection:"column",marginTop:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"red",children:"SECURITY"}),u(l,{}),t.vulnerabilities.map(p=>f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{gap:1,children:[f(l,{bold:!0,color:kw[p.severity]??"gray",children:["⚠"," ",p.severity]}),u(l,{bold:!0,children:p.id})]}),u(m,{paddingLeft:2,children:u(l,{children:p.summary})}),f(m,{gap:2,paddingLeft:2,children:[p.cvssScore!==void 0&&f(l,{dimColor:!0,children:["CVSS:",String(p.cvssScore)]}),p.fixedVersions.length>0&&f(l,{dimColor:!0,children:["Fixed in:",p.fixedVersions.join(", ")]})]})]},p.id))]}),t.socketReport&&f(m,{flexDirection:"column",marginTop:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"cyan",children:"SOCKET.DEV"}),u(l,{}),f(m,{gap:2,children:[f(m,{children:[u(l,{dimColor:!0,children:"Overall: "}),f(l,{bold:!0,color:d,children:[String(Math.round(c*100)),"%"]})]}),f(m,{children:[u(l,{dimColor:!0,children:"Supply Chain: "}),f(l,{children:[String(Math.round(t.socketReport.score.supplyChain*100)),"%"]})]}),f(m,{children:[u(l,{dimColor:!0,children:"Quality: "}),f(l,{children:[String(Math.round(t.socketReport.score.quality*100)),"%"]})]})]}),f(m,{gap:2,children:[f(m,{children:[u(l,{dimColor:!0,children:"Maintenance: "}),f(l,{children:[String(Math.round(t.socketReport.score.maintenance*100)),"%"]})]}),f(m,{children:[u(l,{dimColor:!0,children:"Vulnerability: "}),f(l,{children:[String(Math.round(t.socketReport.score.vulnerability*100)),"%"]})]}),f(m,{children:[u(l,{dimColor:!0,children:"License: "}),f(l,{children:[t.socketReport.license||"unknown"," ","(",String(Math.round(t.socketReport.score.license*100)),"%)"]})]})]}),t.socketReport.alerts.length>0&&f(m,{flexDirection:"column",marginTop:1,children:[f(l,{bold:!0,color:"yellow",children:["⚠"," ",String(t.socketReport.alerts.length)," ","alert",t.socketReport.alerts.length===1?"":"s",":"]}),t.socketReport.alerts.map(p=>f(m,{gap:1,paddingLeft:2,children:[f(l,{bold:!0,color:bw[p.severity]??"gray",children:["[",p.severity.toUpperCase(),"]"]}),u(l,{children:p.type}),f(l,{dimColor:!0,children:["(",p.category,")"]})]},p.key))]})]}),n&&f(m,{flexDirection:"column",marginTop:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"AI ANALYSIS"}),u(l,{}),f(m,{gap:2,children:[f(m,{children:[u(l,{dimColor:!0,children:"Action: "}),u(l,{bold:!0,color:xw[n.action]??"white",children:n.action})]}),f(m,{children:[u(l,{dimColor:!0,children:"Risk: "}),u(l,{bold:!0,color:$w[n.riskLevel]??"white",children:n.riskLevel})]}),f(m,{children:[u(l,{dimColor:!0,children:"Effort: "}),u(l,{bold:!0,children:n.effort})]})]}),n.reason&&u(m,{marginTop:1,paddingLeft:2,children:u(l,{children:n.reason})}),n.breakingChanges.length>0&&f(m,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[u(l,{bold:!0,color:"yellow",children:"Breaking changes:"}),n.breakingChanges.map((p,g)=>f(l,{children:[" ","•"," ",p]},String(g)))]})]}),e&&f(m,{flexDirection:"column",marginTop:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"CHANGELOG"}),u(m,{marginTop:1,paddingLeft:2,children:u(l,{color:"cyan",underline:!0,children:e})})]}),f(m,{flexDirection:"column",marginTop:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"LINKS"}),u(m,{flexDirection:"column",marginTop:1,paddingLeft:2,children:f(l,{color:"cyan",underline:!0,children:["https://npmx.dev/",t.packageName]})})]}),!n&&f(m,{flexDirection:"column",marginTop:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"GUIDANCE"}),f(m,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[t.updateType==="major"&&f(En,{children:[f(l,{color:"red",children:["⚠"," ","Major update — likely contains breaking changes."]}),u(l,{dimColor:!0,children:" Review the changelog before updating."}),u(l,{dimColor:!0,children:" Use --changelog to fetch release URLs."})]}),t.updateType==="minor"&&f(En,{children:[f(l,{color:"yellow",children:["ℹ"," ","Minor update — new features, backward compatible."]}),u(l,{dimColor:!0,children:" Generally safe to update."})]}),t.updateType==="patch"&&f(En,{children:[f(l,{color:"green",children:["✓"," ","Patch update — bug fixes only."]}),u(l,{dimColor:!0,children:" Safe to update."})]}),!n&&u(l,{dimColor:!0,children:" Use --ai to get AI-powered analysis."})]})]})]})]})},"PackageDetailPanel");var Cw=Object.defineProperty,js=b((e,t)=>Cw(e,"name",{value:t,configurable:!0}),"b$j");const jw={major:"red",minor:"yellow",patch:"green"},Ew=[{id:"all",label:"All"},{id:"major",label:"Major"},{id:"minor",label:"Minor"},{id:"patch",label:"Patch"},{id:"security",label:"Security"}],Tw=js(({checked:e,entry:t,isSelected:r})=>{const n=jw[t.updateType]??"white",o=t.vulnerabilities&&t.vulnerabilities.length>0,i=t.socketReport&&t.socketReport.alerts.length>0,s=!!t.acceptedRisk,a=e?"☑":"☐",c=t.socketReport?`${String(Math.round(t.socketReport.score.overall*100))}%`:"",d=t.socketReport?Jn(t.socketReport.score.overall):"gray";return f(m,{flexShrink:0,height:1,children:[u(l,{children:r?">":" "}),f(l,{color:e?"white":"gray",children:[" ",a," "]}),o||i?u(l,{color:s?"gray":"red",children:s?"✓ ":"⚠ "}):u(l,{children:" "}),u(m,{flexGrow:1,children:f(l,{bold:r,inverse:r,wrap:"truncate",children:[t.packageName,s?" [ack]":""]})}),c&&f(l,{color:d,children:[" ",c]}),f(l,{dimColor:!0,children:[" ",t.currentRange]}),f(l,{dimColor:!0,children:[" ","→"," "]}),f(l,{children:[t.newRange," "]}),u(l,{bold:!0,color:n,children:t.updateType})]})},"PackageRow"),Rw=js(({count:e,name:t})=>f(m,{flexShrink:0,height:1,marginTop:1,children:[f(l,{dimColor:!0,children:["▼"," "]}),u(l,{bold:!0,color:"white",children:t.toUpperCase()}),f(l,{dimColor:!0,children:[" ","(",e,")"]})]}),"CatalogHeader"),Aw=js(({checkedEntries:e,entries:t,filterActive:r,filteredOutCount:n,filterText:o,filterType:i,focused:s,groupedByCatalog:a,isDryRun:c,scrollOffset:d,selectedIndex:p,totalCatalogEntries:g,totalChecked:h,totalEntries:y,viewportHeight:w})=>{const k=s?"white":"gray";let $=0,x=0,T=0,I=0;for(const j of t)j.updateType==="major"?$++:j.updateType==="minor"?x++:T++,(j.vulnerabilities&&j.vulnerabilities.length>0||j.socketReport&&j.socketReport.alerts.length>0)&&I++;const P=[];$>0&&P.push(`${$} major`),x>0&&P.push(`${x} minor`),T>0&&P.push(`${T} patch`),I>0&&P.push(`${I} vulnerable`);const R=P.length>0?` (${P.join(", ")})`:"";let M=0;for(const j of t)e.has(j.packageName)&&M++;const L=[];let U=0;for(const[j,A]of a){L.push(u(Rw,{count:A.length,name:j},`hdr-${j}`));for(const V of A){const N=U;L.push(u(Tw,{checked:e.has(V.packageName),entry:V,isSelected:N===p},V.packageName)),U++}}let D=0;for(const[,j]of a)D+=2+j.length;const C=D>w&&w>0;return f(m,{borderColor:k,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[f(m,{flexShrink:0,gap:1,paddingX:1,children:[u(l,{bold:!0,inverse:!0,children:" VIS "}),f(l,{wrap:"truncate",children:[y,h>0?`/${h}`:""," ","outdated",R,g>h?` · ${g-h} dupes`:""]}),!c&&M>0&&f(l,{dimColor:!0,children:[" ","—",M," ","selected"]})]}),u(m,{flexShrink:0,paddingX:1,paddingY:1,children:u(il,{isFocused:s,keyMap:{next:[],previous:[],useNumbers:!1,useTab:!1},onChange:b(()=>{},"onChange"),showIndex:!1,value:i,children:Ew.map(({id:j,label:A})=>u(sl,{name:j,children:A},j))})}),r&&f(m,{flexShrink:0,paddingX:1,children:[u(l,{bold:!0,color:"white",children:"/ "}),u(l,{children:o}),u(l,{inverse:!0,children:" "})]}),n>0&&u(m,{flexShrink:0,paddingX:1,children:f(l,{color:"yellow",children:["⚠"," ",n," ","package",n===1?"":"s"," ","filtered out by target constraint — press"," ",u(l,{bold:!0,color:"white",children:"f"})," ","to view"]})}),f(m,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[u(m,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:u(m,{flexDirection:"column",marginTop:-d,children:L})}),C&&u(m,{flexShrink:0,marginLeft:1,marginRight:1,children:u(Gn,{contentHeight:D,placement:"inset",scrollOffset:d,style:"block",viewportHeight:w})})]},`list-${i}-${o}`)]})},"PackageListPanel");var Iw=Object.defineProperty,Ow=b((e,t)=>Iw(e,"name",{value:t,configurable:!0}),"Y$2");const Pw=100,Nw=40,Mw=10,Dw=[],Cd=Ow(({autoExitSeconds:e=0,changelogUrls:t,checkedCount:r=0,filteredOutEntries:n=Dw,isDryRun:o,store:i,totalCatalogEntries:s=0})=>{const{exit:a}=an(),{columns:c,rows:d}=sn(),p=Hn(i.subscribe,i.getSnapshot),[g,h]=we(!1),[y,w]=we(!1),k=Ue(null),$=Ue(null),x=Ue(null),T=Ue(null),[I,P]=we(0),[R,M]=we(!1),[L,U]=we(!1),D=Dt(()=>i.getFilteredEntries(),[p.entries,p.filterType,p.filterText]),C=D[p.selectedIndex]??null,j=C?i.getRecommendation(C.packageName):void 0,A=C&&t?t.get(C.packageName):void 0,V=Nt(X=>{let te=0,fe=0;for(const[,zt]of p.groupedByCatalog){te+=2;for(let K=0;K<zt.length;K++){if(fe===X)return te;te+=1,fe++}}return te},[p.groupedByCatalog]),N=Math.max(1,d-8-(p.filterActive?1:0)),F=Nt(X=>{const te=V(X);P(fe=>te>fe+N-2?Math.max(0,te-N+2):te<fe+1?Math.max(0,te-1):fe)},[V,N]);if(Pt(()=>{x.current?.scrollToTop()},[C?.packageName]),kt((X,te)=>{if(X==="c"&&te.ctrl){a();return}if(!L){if(y){te.escape||X==="f"||X==="q"?w(!1):te.downArrow||X==="j"?$.current?.scrollBy(1):(te.upArrow||X==="k")&&$.current?.scrollBy(-1);return}if(R){X==="u"||te.return?(M(!1),i.startApply(),a(i.getCheckedEntries())):te.escape||X==="q"?M(!1):te.downArrow||X==="j"?T.current?.scrollBy(1):te.upArrow||X==="k"?T.current?.scrollBy(-1):te.pageDown?T.current?.scrollBy(5):te.pageUp&&T.current?.scrollBy(-5);return}if(g){te.escape||X==="?"?h(!1):X==="q"?(h(!1),U(!0)):te.downArrow||X==="j"?k.current?.scrollBy(1):(te.upArrow||X==="k")&&k.current?.scrollBy(-1);return}if(X==="?"){h(!0);return}if(X==="q"){U(!0);return}if(te.tab){i.setFocusedPanel(p.focusedPanel==="list"?"detail":"list");return}if(p.focusedPanel==="list"&&(te.leftArrow||te.rightArrow)){const fe=["all","major","minor","patch","security"],zt=fe.indexOf(p.filterType),K=te.rightArrow?(zt+1)%fe.length:(zt-1+fe.length)%fe.length;P(0),x.current?.scrollToTop(),i.setFilterType(fe[K]);return}if(X==="f"&&n.length>0){w(fe=>!fe);return}if(p.filterActive){if(te.escape){i.setFilterActive(!1);return}if(te.return){i.setFilterActive(!1);return}if(te.backspace){P(0),i.setFilter(p.filterText.slice(0,-1));return}if(X&&!te.ctrl&&!te.meta){P(0),i.setFilter(p.filterText+X);return}return}if(p.focusedPanel==="list"){if(te.downArrow||X==="j"){const fe=Math.min(p.selectedIndex+1,D.length-1);i.setSelectedIndex(fe),F(fe);return}if(te.upArrow||X==="k"){const fe=Math.max(p.selectedIndex-1,0);i.setSelectedIndex(fe),F(fe);return}if(te.pageDown){const fe=Math.min(p.selectedIndex+10,D.length-1);i.setSelectedIndex(fe),F(fe);return}if(te.pageUp){const fe=Math.max(p.selectedIndex-10,0);i.setSelectedIndex(fe),F(fe);return}if(te.home){i.setSelectedIndex(0),P(0);return}if(te.end){const fe=D.length-1;i.setSelectedIndex(fe),F(fe);return}if(X===" "||te.return){C&&i.toggleCheck(C.packageName);return}if(X==="a"){i.toggleAll();return}if(X==="/"){i.setFilterActive(!0);return}if(X==="u"&&!o&&p.checkedEntries.size>0){M(!0);return}if(te.rightArrow){i.setFocusedPanel("detail");return}return}if(p.focusedPanel==="detail"){if(te.escape||te.leftArrow){i.setFocusedPanel("list");return}if(te.downArrow||X==="j"){x.current?.scrollBy(1);return}if(te.upArrow||X==="k"){x.current?.scrollBy(-1);return}if(te.pageDown){x.current?.scrollBy(10);return}if(te.pageUp){x.current?.scrollBy(-10);return}if(te.home){x.current?.scrollToTop();return}te.end&&x.current?.scrollToBottom()}}},{isActive:!0}),c<Nw||d<Mw)return u(m,{alignItems:"center",height:d,justifyContent:"center",width:c,children:f(l,{color:"yellow",children:["Terminal too small (",c,"x",d,")"]})});const J=c>=Pw,Y=[f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"q"}),u(l,{dimColor:!0,children:"QUIT"})]},"q"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"?"}),u(l,{dimColor:!0,children:"HELP"})]},"?"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"↑↓"}),u(l,{dimColor:!0,children:"NAV"})]},"nav"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"Space"}),u(l,{dimColor:!0,children:"CHECK"})]},"sp"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"a"}),u(l,{dimColor:!0,children:"ALL"})]},"a")];!o&&p.checkedEntries.size>0&&Y.push(f(m,{gap:1,children:[u(l,{bold:!0,color:"green",children:"u"}),u(l,{dimColor:!0,children:"APPLY"})]},"u")),n.length>0&&Y.push(f(m,{gap:1,children:[u(l,{bold:!0,color:"yellow",children:"f"}),f(l,{dimColor:!0,children:["FILTERED (",n.length,")"]})]},"fo")),Y.push(f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"←→"}),u(l,{dimColor:!0,children:"FILTER"})]},"lr"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"/"}),u(l,{dimColor:!0,children:"SEARCH"})]},"f"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"Tab"}),u(l,{dimColor:!0,children:"PANEL"})]},"t"));const ce=u(m,{borderBottom:!1,borderColor:"gray",borderLeft:!1,borderRight:!1,borderStyle:"single",flexShrink:0,children:u(m,{flexWrap:"wrap",gap:2,paddingX:1,children:Y})}),le=f(Ar,{footer:f(l,{dimColor:!0,children:[u(l,{bold:!0,color:"white",children:"↑↓"})," ","scroll"," ",u(l,{bold:!0,color:"white",children:"?"}),"/",u(l,{bold:!0,color:"white",children:"Esc"})," ","close"]}),scrollRef:k,title:"KEYBOARD SHORTCUTS",visible:g,width:52,children:[f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"NAVIGATION"})]}),f(m,{children:[u(m,{width:24,children:f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","↑","/k"]}),u(l,{dimColor:!0,children:" Move up"})]})}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","↓","/j"]}),u(l,{dimColor:!0,children:" Move down"})]})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","Tab"]}),u(l,{dimColor:!0,children:" Switch panel"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","→","/","←"]}),u(l,{dimColor:!0,children:" Focus detail/list"})]})]}),f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"SELECTION"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","Space"]}),u(l,{dimColor:!0,children:" Toggle check on package"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","a"]}),u(l,{dimColor:!0,children:" Toggle check all"})]})]}),f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"FILTERS"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","←→"]}),u(l,{dimColor:!0,children:" Switch filter tab"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","/"]}),u(l,{dimColor:!0,children:" Text filter"})]}),n.length>0&&f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","f"]}),u(l,{dimColor:!0,children:" View filtered-out packages"})]})]}),f(m,{flexDirection:"column",children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"ACTIONS"})]}),!o&&f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","u"]}),u(l,{dimColor:!0,children:" Apply selected updates"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","q"]}),u(l,{dimColor:!0,children:" Quit"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","?"]}),u(l,{dimColor:!0,children:" Toggle help"})]})]})]}),be=i.getCheckedEntries(),B=be.filter(X=>X.updateType==="major").length,O=f(m,{alignItems:"center",flexDirection:"column",children:[B>0&&u(m,{marginBottom:1,marginTop:1,children:f(l,{color:"yellow",children:["⚠"," ",B," ","major update",B===1?"":"s"," ","— review breaking changes"]})}),f(l,{dimColor:!0,children:["Press"," ",u(l,{bold:!0,color:"white",children:"u"})," ","or"," ",u(l,{bold:!0,color:"white",children:"Enter"})," ","to confirm,"," ",u(l,{bold:!0,color:"white",children:"Esc"})," ","to cancel"]})]}),H=u(Ar,{footer:O,scrollRef:T,title:`Apply ${be.length} update${be.length===1?"":"s"}?`,visible:R,width:70,children:be.map(X=>f(m,{gap:1,children:[f(l,{children:[" ",X.packageName]}),f(l,{dimColor:!0,children:[X.currentRange," ","→"," ",X.newRange]}),u(l,{bold:!0,color:X.updateType==="major"?"red":X.updateType==="minor"?"yellow":"green",children:X.updateType})]},X.packageName))}),ye=n.length>0?u(Ar,{footer:f(l,{dimColor:!0,children:[u(l,{bold:!0,color:"white",children:"↑↓"})," ","scroll"," ",u(l,{bold:!0,color:"white",children:"f"}),"/",u(l,{bold:!0,color:"white",children:"Esc"})," ","close"]}),scrollRef:$,title:`${n.length} PACKAGE${n.length===1?"":"S"} FILTERED BY TARGET`,visible:y,width:70,children:f(m,{flexDirection:"column",children:[u(m,{marginBottom:1,children:f(l,{dimColor:!0,children:["These packages have newer versions available but are excluded by the current target constraint. Use"," ",u(l,{bold:!0,color:"white",children:"--target latest"})," ","to include them."]})}),n.map(X=>f(m,{gap:1,children:[f(l,{children:[" ",X.packageName]}),f(l,{dimColor:!0,children:[X.currentRange," ","→"," ",X.newRange]}),u(l,{bold:!0,color:X.updateType==="major"?"red":X.updateType==="minor"?"yellow":"green",children:X.updateType})]},X.packageName))]})}):null,Ee=u(Aw,{checkedEntries:p.checkedEntries,entries:D,filterActive:p.filterActive,filteredOutCount:n.length,filterText:p.filterText,filterType:p.filterType,focused:p.focusedPanel==="list",groupedByCatalog:p.groupedByCatalog,isDryRun:o,scrollOffset:I,selectedIndex:p.selectedIndex,totalCatalogEntries:s,totalChecked:r,totalEntries:D.length,viewportHeight:N}),Ae=u(Sw,{changelogUrl:A,entry:C,focused:p.focusedPanel==="detail",recommendation:j,scrollRef:x});if(J){const X=Math.floor(c*.35);return f(m,{flexDirection:"column",height:d,width:c,children:[f(m,{flexDirection:"row",flexGrow:1,children:[u(m,{flexGrow:1,children:Ee}),u(m,{width:X,children:Ae})]}),ce,H,ye,u(Nr,{autoExitSeconds:e||3,onCancel:b(()=>{U(!1)},"onCancel"),visible:L}),le]})}const Tt=Math.floor(d*.55);return f(m,{flexDirection:"column",height:d,width:c,children:[u(m,{height:Tt,children:Ee}),u(m,{flexGrow:1,children:Ae}),ce,H,ye,u(Nr,{autoExitSeconds:e||3,onCancel:b(()=>{U(!1)},"onCancel"),visible:L}),le]})},"VisUpdateApp");var Bw=Object.defineProperty,Fw=b((e,t)=>Bw(e,"name",{value:t,configurable:!0}),"T$f");const Lw={alias:["c","outdated"],argument:{description:"Specific packages to check (checks all if omitted)",name:"packages",type:String},description:"Check for outdated dependencies, security vulnerabilities, and supply chain settings",examples:[["vis check","Check all catalog dependencies"],["vis check react","Check specific packages"],["vis check --target minor","Only show minor/patch updates"],["vis check --exclude '@types/*'","Exclude packages by pattern"],["vis check --no-security","Skip vulnerability scanning"],["vis check --security-config","Audit supply chain security settings"],["vis check --security-config --sync","Sync security config to pnpm-workspace.yaml"]],execute:Fw(async({argument:e,logger:t,options:r,visConfig:n,workspaceRoot:o})=>{if(!o)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const i=o;if(r.securityConfig){const M=Ne(i);if(Ev(n??{},M.name),r.sync&&M.name==="pnpm"){const L=Tv(n??{});if(L.length>0){S(`
161
- Settings that would sync to pnpm-workspace.yaml:`);for(const U of L)ee(` ${U}`)}else S("No security settings to sync.")}else r.sync&&M.name!=="pnpm"&&(S(`--sync is only available for pnpm projects. Your project uses ${M.name}.`),S("vis enforces security settings at the vis layer for non-pnpm projects."));if(!r.security&&!e?.length)return}const{packageManager:s}=Mo(i),a=$s(i),c=n?.update??{},d=Jo(i,s,{dev:r.dev,prod:r.prod});if(d.size===0){t.info("No catalogs found.");return}const p=r.target??c.target??"latest";if(!["latest","minor","patch"].includes(p))throw new Error(`Invalid target "${p}". Use: latest, minor, or patch.`);const g={exclude:[...bt(r.exclude),...bt(c.exclude)],ignore:bt(c.ignore),include:[...bt(r.include),...bt(c.include),...e],includeLocked:!!r.includeLocked,includePrerelease:r.prerelease||c.prerelease||!1,security:!r.noSecurity,target:p};let h=0;for(const M of d.values())h+=M.size;const y=!!process.stdout.isTTY&&!ft;let w;const k=y?(M,L)=>{w?w.rerender(Q.createElement(Bn,{current:M,total:L})):w=Xt(Q.createElement(Bn,{current:M,total:L}),{interactive:!0,patchConsole:!1})}:(M,L)=>{t.info(`Checking ${String(M)}/${String(L)} dependencies...`)};y||t.info(`Checking ${String(h)} catalog dependencies against npm registry...
162
- `);const $=Lr(n?.security?.socket),{failed:x,outdated:T}=await xs(d,g,a,k,i,$,n?.security?.socket?.acceptedRisks);if(w&&(w.clear(),w.unmount()),x.length>0&&t.warn(`Failed to fetch: ${x.join(", ")}`),T.length===0){t.info("All catalog dependencies are up to date.");return}const I=r.format??c.format??"table",P=vs(r.aiType??"impact"),R=r.ai?await ws(T,t,n?.ai,P):void 0;if(y&&I==="table"){const M=new Sd(T,R??null),L=n?.tui?.autoExit??!1,U=L===!0?3:typeof L=="number"?L:0;await Xt(Q.createElement(Cd,{autoExitSeconds:U,isDryRun:!0,store:M}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit();const D=process.stdout.columns||80;process.stdout.write(`
163
- `);for(const C of T){const j=C.vulnerabilities?.length||C.socketReport&&C.socketReport.alerts.length>0,A=!!C.acceptedRisk,V=j?A?"✓":"⚠":"✓",N=A?"gray":C.updateType==="major"?"red":C.updateType==="minor"?"yellow":"green",F=C.socketReport?.score.overall,J=F===void 0?"":` [${String(Math.round(F*100))}%]`,Y=F===void 0?void 0:Jn(F);process.stdout.write(`${Oe(Q.createElement(l,null," ",Q.createElement(l,{color:N},V),` ${C.packageName} ${C.currentRange} → ${C.newRange}`,Q.createElement(l,{dimColor:!0},` ${C.updateType}`),Y?Q.createElement(l,{color:Y},J):null),{columns:D})}
164
- `)}process.stdout.write(`
165
- `),t.info(Eo(T))}else if(I==="json"){const M={failed:x,outdated:T};R&&(M.aiAnalysis=R),process.stdout.write(`${JSON.stringify(M,void 0,2)}
166
- `)}else I==="minimal"?process.stdout.write(`${pd(T)}
167
- `):(fd(T,t),t.info(Eo(T)),R&&(t.info(""),t.info(jo(R))));r.exitCode&&T.length>0&&(process.exitCode=1)},"execute"),group:"Security & Health",name:"check",options:[{alias:"t",description:"Update target: latest, minor, or patch (default: latest)",name:"target",type:String},{description:"Glob pattern to include packages (repeatable)",lazyMultiple:!0,name:"include",type:String},{description:"Glob pattern to exclude packages (repeatable)",lazyMultiple:!0,name:"exclude",type:String},{defaultValue:!1,description:"Include prerelease versions",name:"prerelease",type:Boolean},{defaultValue:!1,description:"Skip security vulnerability scanning",name:"no-security",type:Boolean},{defaultValue:!1,description:"Audit supply chain security settings",name:"security-config",type:Boolean},{defaultValue:!1,description:"Sync security settings to pnpm-workspace.yaml (pnpm only, requires --security-config)",name:"sync",type:Boolean},{description:"Output format: table, json, or minimal (default: table)",name:"format",type:String},{defaultValue:!1,description:"Exit with code 1 if outdated dependencies found (for CI)",name:"exit-code",type:Boolean},{defaultValue:!1,description:"Run AI analysis on outdated packages",name:"ai",type:Boolean},{description:"AI analysis type: impact, security, compatibility, or recommend",name:"ai-type",type:String},{alias:"D",defaultValue:!1,description:"Check only devDependencies (npm/yarn mode)",name:"dev",type:Boolean},{alias:"P",defaultValue:!1,description:"Check only dependencies (npm/yarn mode)",name:"prod",type:Boolean}]};var Vw=Object.defineProperty,jd=b((e,t)=>Vw(e,"name",{value:t,configurable:!0}),"r$m");const _w=jd(()=>process.env.GITHUB_BASE_REF?{base:`origin/${process.env.GITHUB_BASE_REF}`,head:process.env.GITHUB_SHA??"HEAD"}:process.env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME?{base:`origin/${process.env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME}`,head:process.env.CI_COMMIT_SHA??"HEAD"}:process.env.CIRCLE_BRANCH&&process.env.CIRCLE_SHA1?{base:"origin/main",head:process.env.CIRCLE_SHA1}:{base:"origin/main",head:"HEAD"},"detectCiRefs"),Uw={argument:{description:"Comma-separated list of targets to run (e.g., lint,test,build)",name:"targets",type:String},description:"Run affected targets in a CI-optimized pipeline",examples:[["vis ci lint,test,build","Run lint, test, and build on affected projects"],["vis ci test --base=origin/main","Override the base ref"],["vis ci build --no-install","Skip the install step (assume deps already present)"],["vis ci build --parallel=6","Increase concurrency"]],execute:jd(async({argument:e,logger:t,options:r,runtime:n,workspaceRoot:o})=>{const i=e[0];if(!i)throw new Error("Missing targets. Usage: vis ci <target>[,<target>…]");const s=i.split(",").map(g=>g.trim()).filter(Boolean);if(s.length===0)throw new Error("Missing targets. Usage: vis ci <target>[,<target>…]");if(!o)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const{base:a,head:c}=_w(),d=r.base??a,p=r.head??c;r.install===!1?t.info("▸ Skipping install (--no-install)"):(t.info("▸ Installing dependencies"),await n.runCommand("install",{argv:["--frozen-lockfile"]}));for(const g of s){t.info(`▸ Running affected ${g} (base=${d}, head=${p})`);const h=[g,`--base=${d}`,`--head=${p}`,`--upstream=${String(r.upstream??"none")}`,`--downstream=${String(r.downstream??"deep")}`];r.parallel!==void 0&&h.push(`--parallel=${String(r.parallel)}`),r.partition&&h.push(`--partition=${String(r.partition)}`),r.query&&h.push(`--query=${String(r.query)}`),await n.runCommand("affected",{argv:h})}t.info("▸ CI pipeline complete")},"execute"),group:"Run & Execute",name:"ci",options:[{defaultValue:!0,description:"Install dependencies before running targets (use --no-install to skip)",name:"install",type:Boolean},{description:"Git base ref for affected detection (default: auto-detected from CI env)",name:"base",type:String},{description:"Git head ref for affected detection (default: HEAD)",name:"head",type:String},{defaultValue:"none",description:"Upstream scope: none | direct | deep",name:"upstream",type:String},{defaultValue:"deep",description:"Downstream scope: none | direct | deep",name:"downstream",type:String},{defaultValue:4,description:"Maximum number of parallel tasks per target",name:"parallel",type:Number},{description:'Partition tasks for distributed CI (e.g., "1/4")',name:"partition",type:String},{description:"Filter affected projects by a query (e.g. 'language=typescript && tag=lib')",name:"query",type:String}]};var Ww=Object.defineProperty,Es=b((e,t)=>Ww(e,"name",{value:t,configurable:!0}),"a$j");const Gw=Es(e=>{const t=[],r=[e];for(;r.length>0;){const n=r.pop();let o;try{o=Ve(n)}catch{continue}for(const i of o){const s=v(n,i);try{const a=tl(s);if(a.isSymbolicLink()||!a.isDirectory())continue}catch{continue}i==="node_modules"?t.push(s):i!==".git"&&i!==".hg"&&r.push(s)}}return t},"findNodeModulesDirectories"),Hw=["pnpm-lock.yaml","package-lock.json","npm-shrinkwrap.json","yarn.lock","bun.lock","bun.lockb"],zw=Es((e,t,r)=>{let n=0,o=!1;for(const i of Hw){const s=v(e,i);if(E(s)){if(t){r.info(` ${s}`),n++;continue}try{Dr(s),ee(`Removed ${s}`),n++}catch(a){Ze(`${s}: ${Ni(a)}`),o=!0}}}return{hadError:o,removed:n}},"removeLockfiles"),qw={description:"Remove node_modules from all workspace projects",examples:[["vis clean","Remove all node_modules directories"],["vis clean --lockfile","Also remove lockfiles"],["vis clean --dry-run","Preview what would be removed"]],execute:Es(async({logger:e,options:t,workspaceRoot:r})=>{const n=r??process.cwd(),o=t.lockfile||!1;if(t.dryRun){const a=Gw(n);if(a.length>0){S("Would remove:");for(const c of a)e.info(` ${c}`)}else S("No node_modules directories found.");o&&zw(n,!0,e);return}const i=Go();if(!i){Ze("Native bindings unavailable. Ensure the correct platform binary is installed."),process.exitCode=1;return}const s=i.cleanWorkspace(n,o);for(const a of s.removed)ee(`Removed ${a}`);for(const a of s.lockfilesRemoved)ee(`Removed ${a}`);for(const a of s.errors)Ze(a);s.removed.length===0&&s.lockfilesRemoved.length===0?S("No node_modules directories found."):S(`Cleaned ${s.removed.length} node_modules director${s.removed.length===1?"y":"ies"}`),s.errors.length>0&&(process.exitCode=1)},"execute"),group:"Workspace",name:"clean",options:[{alias:"l",defaultValue:!1,description:"Also remove lockfiles (pnpm-lock.yaml, package-lock.json, etc.)",name:"lockfile",type:Boolean},{defaultValue:!1,description:"Preview what would be removed without deleting",name:"dry-run",type:Boolean}]};var Jw=Object.defineProperty,Qo=b((e,t)=>Jw(e,"name",{value:t,configurable:!0}),"e$7");const Yw={"vis:app":"builtin:app","vis:application":"builtin:app","vis:generator":"builtin:generator","vis:lib":"builtin:library","vis:library":"builtin:library","vis:monorepo":"builtin:monorepo"},Kw=["https://github.com/","https://gitlab.com/","https://bitbucket.org/","https://raw.githubusercontent.com/","https://git.sr.ht/","git@github.com:","git@gitlab.com:","git@bitbucket.org:","git@git.sr.ht:","github:","gh:","gitlab:","bitbucket:","sourcehut:","git:","http://","https://"],Xw=Qo(e=>{for(const t of Kw)if(e.startsWith(t))return!0;return!!(!e.startsWith("@")&&/^[^/#@][^/#]*\/[^/#]+/.test(e))},"isGitUrl"),Qw=new Set(["sv"]),Zw=Qo(e=>{if(Qw.has(e)||e.startsWith("create-")||e.startsWith("@")&&e.includes("/create-"))return e;if(e.startsWith("@")){const t=e.indexOf("/");if(t!==-1){const r=e.slice(0,t),n=e.slice(t+1);return`${r}/create-${n}`}return e}return`create-${e}`},"expandCreateShorthand"),ek=Qo((e,t=[])=>{if(!e)throw new Error("No template specified.");const r=e.toLowerCase(),n=Yw[r];return n?{args:t,source:r,type:n}:Xw(e)?{args:t,source:e,type:"remote:git"}:{args:t,source:Zw(e),type:"remote:npm"}},"discoverTemplate"),tk=Qo(e=>{switch(e){case"builtin:app":return"apps";case"builtin:generator":case"builtin:library":return"packages";default:return"."}},"inferParentDir");var rk=Object.defineProperty,nk=b((e,t)=>rk(e,"name",{value:t,configurable:!0}),"o$h");const ok=nk(()=>`${sa()}-${sa()}`,"randomName");var ik=Object.defineProperty,Qn=b((e,t)=>ik(e,"name",{value:t,configurable:!0}),"r$l");const Ed=Qn(e=>e?Wp(e).validForNewPackages:!1,"isValidPackageName"),Fn=Qn(e=>e.toLowerCase().trim().replaceAll(/\s+/g,"-").replaceAll(/[^a-z\d\-~]/g,"-").replace(/^[._-]+/,"").replaceAll(/-{2,}/g,"-").replace(/-$/,""),"toValidPackageName"),sk=new Set([".DS_Store",".git",".gitkeep","Thumbs.db"]),Td=Qn(e=>E(e)?Ve(e).every(t=>sk.has(t)):!0,"isEmptyDir"),ak=Qn((e,t)=>{const r=xe(t,e);return{packageName:Fn(Do(r)),targetDir:r}},"resolveTargetDir"),ck=Qn(e=>Td(e),"canSafelyOverwrite");var lk=Object.defineProperty,Zo=b((e,t)=>lk(e,"name",{value:t,configurable:!0}),"l$m");const An=Zo((e,t)=>new Promise(r=>{e.question(t,n=>{r(n.trim())})}),"ask"),$i=Zo(async(e,t,r=!0)=>{const n=await An(e,` ${t} ${re(r?"[Y/n]":"[y/N]")} `);return n===""?r:n.toLowerCase()==="y"||n.toLowerCase()==="yes"},"confirm"),Va=Zo(async(e,t,r)=>{process.stderr.write(` ${t}
168
- `);for(const[n,o]of r.entries()){const i=ve(Fe(` ${String(n+1)}.`)),s=o.hint?re(` — ${o.hint}`):"";process.stderr.write(`${i} ${o.label}${s}
169
- `)}for(;;){const n=await An(e,`
170
- ${re(`Enter choice (1-${String(r.length)}):`)} `),o=Number.parseInt(n,10);if(o>=1&&o<=r.length)return r[o-1].value;const i=r.find(s=>s.value===n||s.label.toLowerCase()===n.toLowerCase());if(i)return i.value;process.stderr.write(` ${re("Invalid choice. Try again.")}
171
- `)}},"select"),dk=Zo(async e=>{const t=gt({input:process.stdin,output:process.stdout});try{process.stderr.write(`
172
- ${ve(Fe("vis create"))} ${re("— project scaffolding")}
173
-
174
- `);const r=e.inMonorepo?[{hint:"Scaffold via create-vite",label:"Vis Application",value:"vis:app"},{hint:"Reusable package scaffold",label:"Vis Library",value:"vis:library"},{hint:"Code generator scaffold",label:"Vis Generator",value:"vis:generator"},{hint:"Enter an npm create-* package or GitHub URL",label:"Custom template",value:"__custom__"}]:[{hint:"Full workspace setup",label:"Vis Monorepo",value:"vis:monorepo"},{hint:"Scaffold via create-vite",label:"Vis Application",value:"vis:app"},{hint:"Reusable package scaffold",label:"Vis Library",value:"vis:library"},{hint:"Code generator scaffold",label:"Vis Generator",value:"vis:generator"},{hint:"Enter an npm create-* package or GitHub URL",label:"Custom template",value:"__custom__"}];let n=await Va(t,"Select a template:",r);if(n==="__custom__"&&(n=await An(t,`
175
- ${re("Template (npm package or GitHub URL):")} `),!n))throw new Error("No template specified.");const o=ok(),i=await An(t,`
176
- ${re(`Project name (${o}):`)} `)||o;if(!Ed(Fn(i)))throw new Error(`Invalid project name: "${i}". Must be a valid npm package name.`);const s=Fn(i),a=await An(t,` ${re(`Target directory (${s}):`)} `)||s;let c=!1;const d=xe(e.cwd,a);if(!Td(d)&&(c=await $i(t,`Directory "${a}" is not empty. Overwrite?`,!1),!c))throw new Error("Aborted — directory not empty.");let p;e.inMonorepo||(e.defaultPm?(p=e.defaultPm,process.stderr.write(` ${re(`Package manager: ${p} (from config)`)}
177
- `)):p=await Va(t,"Package manager:",[{label:"pnpm",value:"pnpm"},{label:"npm",value:"npm"},{label:"yarn",value:"yarn"},{label:"bun",value:"bun"}]));let g=!1;e.inMonorepo||(g=await $i(t,"Initialize a git repository?",e.defaultGitInit??!1));const h=e.defaultEditor==="vscode",y=await $i(t,"Generate VS Code configuration?",h)?"vscode":void 0;return process.stderr.write(`
178
- `),{editor:y,gitInit:g,overwrite:c,pm:p,projectName:i,targetDir:a,template:n}}finally{t.close()}},"runInteractivePrompts");var uk=Object.defineProperty,Vr=b((e,t)=>uk(e,"name",{value:t,configurable:!0}),"i$e");const pk=Vr((e,t)=>{S("Scaffolding application via create-vite...");const r=[He(t.cwd,t.targetDir)||".",...e.args];return r.includes("--no-immediate")||r.push("--no-immediate"),us(t.pm,{additionalPackages:[],args:r,package:"create-vite",shellMode:!1,silent:!1},t.cwd,t.logger)},"executeApp"),fk=Vr(e=>`${JSON.stringify({devDependencies:{typescript:"^5.0.0",vitest:"^3.0.0"},exports:{".":{default:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist"],main:"./dist/index.js",name:e,scripts:{build:"tsc",dev:"tsc --watch",test:"vitest run","test:watch":"vitest"},type:"module",types:"./dist/index.d.ts",version:"0.0.1"},null,4)}
179
- `,"libraryPackageJson"),gk=Vr(()=>`${JSON.stringify({compilerOptions:{declaration:!0,declarationMap:!0,esModuleInterop:!0,module:"Node16",moduleResolution:"Node16",outDir:"./dist",rootDir:"./src",skipLibCheck:!0,sourceMap:!0,strict:!0,target:"ES2022"},include:["src/**/*"]},null,4)}
180
- `,"libraryTsconfig"),mk=Vr(e=>`/**
181
- * ${e} — library entry point.
182
- */
183
-
184
- export const greet = (name: string): string => \`Hello from ${e}, \${name}!\`;
185
- `,"librarySrcIndex"),hk=Vr(e=>`import { describe, expect, it } from "vitest";
186
-
187
- import { greet } from "../src/index";
188
-
189
- describe("${e}", () => {
190
- it("should greet", () => {
191
- expect(greet("world")).toBe("Hello from ${e}, world!");
192
- });
193
- });
194
- `,"libraryTestIndex"),yk=Vr((e,t)=>{const{projectName:r,targetDir:n}=t;return S("Scaffolding library package..."),Se(n),Se(v(n,"src")),Se(v(n,"__tests__")),Z(v(n,"package.json"),fk(r)),ee("Created package.json"),Z(v(n,"tsconfig.json"),gk()),ee("Created tsconfig.json"),Z(v(n,"src","index.ts"),mk(r)),ee("Created src/index.ts"),Z(v(n,"__tests__","index.test.ts"),hk(r)),ee("Created __tests__/index.test.ts"),Z(v(n,".gitignore"),`node_modules/
195
- dist/
196
- .env
197
- .DS_Store
198
- `),ee("Created .gitignore"),0},"executeLibrary"),vk=Vr((e,t)=>{switch(e.type){case"builtin:app":return pk(e,t);case"builtin:library":return yk(e,t);default:throw new Error(`Unknown built-in template type: ${e.type}`)}},"executeBuiltin");var wk=Object.defineProperty,Zn=b((e,t)=>wk(e,"name",{value:t,configurable:!0}),"n$8");const kk=Zn((e,t)=>`${JSON.stringify({bin:{[e]:"./bin/index.js"},description:t,devDependencies:{typescript:"^5.0.0"},name:e,private:!0,scripts:{build:"tsc",dev:"tsc --watch"},type:"module",version:"0.0.1"},null,4)}
199
- `,"packageJson"),bk=Zn(e=>`#!/usr/bin/env node
200
-
201
- /**
202
- * ${e} — code generator
203
- *
204
- * Usage: npx ${e} [options]
205
- */
206
-
207
- console.log("Hello from ${e}!");
208
- `,"binIndex"),$k=Zn(()=>`${JSON.stringify({compilerOptions:{declaration:!0,esModuleInterop:!0,module:"Node16",moduleResolution:"Node16",outDir:"./dist",rootDir:"./src",skipLibCheck:!0,strict:!0,target:"ES2022"},include:["src/**/*","bin/**/*"]},null,4)}
209
- `,"tsconfigJson"),xk=Zn(()=>`/**
210
- * Generator core logic — export functions used by the CLI entry point.
211
- */
212
-
213
- export const generate = (): void => {
214
- // TODO: Implement your generator logic here
215
- };
216
- `,"srcIndex"),Sk=Zn((e,t="")=>{const{projectName:r,targetDir:n}=e;S("Scaffolding code generator..."),Se(n),Se(v(n,"bin")),Se(v(n,"src")),Z(v(n,"package.json"),kk(r,t||`Code generator: ${r}`)),ee("Created package.json");const o=v(n,"bin","index.js");return Z(o,bk(r)),rl(o,493),ee("Created bin/index.js (executable)"),Z(v(n,"tsconfig.json"),$k()),ee("Created tsconfig.json"),Z(v(n,"src","index.ts"),xk()),ee("Created src/index.ts"),0},"executeGeneratorTemplate");var Ck=Object.defineProperty,fn=b((e,t)=>Ck(e,"name",{value:t,configurable:!0}),"s$p");const jk=fn(e=>`${JSON.stringify({devDependencies:{"@visulima/vis":"latest"},name:e,packageManager:"pnpm@latest",private:!0,scripts:{build:"vis run build",dev:"vis run dev",lint:"vis run lint",test:"vis run test"},type:"module",version:"0.0.0"},null,4)}
217
- `,"rootPackageJson"),Ek=fn(()=>`packages:
218
- - "apps/*"
219
- - "packages/*"
220
- `,"pnpmWorkspaceYaml"),Tk=fn(()=>`# Dependencies
221
- node_modules/
222
-
223
- # Build output
224
- dist/
225
- .output/
226
-
227
- # Environment
228
- .env
229
- .env.local
230
- .env.*.local
231
-
232
- # IDE
233
- .vscode/*
234
- !.vscode/settings.json
235
- !.vscode/extensions.json
236
- .idea/
237
-
238
- # OS
239
- .DS_Store
240
- Thumbs.db
241
-
242
- # Logs
243
- *.log
244
- npm-debug.log*
245
- pnpm-debug.log*
246
-
247
- # Cache
248
- .turbo/
249
- .cache/
250
- `,"gitignore"),Rk=fn(()=>`root = true
251
-
252
- [*]
253
- indent_style = space
254
- indent_size = 4
255
- end_of_line = lf
256
- charset = utf-8
257
- trim_trailing_whitespace = true
258
- insert_final_newline = true
259
-
260
- [*.{yml,yaml}]
261
- indent_size = 2
262
-
263
- [*.md]
264
- trim_trailing_whitespace = false
265
- `,"editorconfig"),Ak=fn(e=>`# ${e}
266
-
267
- A monorepo powered by [vis](https://visulima.com/packages/vis).
268
-
269
- ## Getting Started
270
-
271
- \`\`\`bash
272
- # Install dependencies
273
- pnpm install
274
-
275
- # Run all apps in development mode
276
- pnpm dev
277
-
278
- # Build all packages
279
- pnpm build
280
-
281
- # Run tests
282
- pnpm test
283
- \`\`\`
284
-
285
- ## Structure
286
-
287
- \`\`\`
288
- ├── apps/ # Applications
289
- ├── packages/ # Shared packages & libraries
290
- ├── pnpm-workspace.yaml
291
- └── package.json
292
- \`\`\`
293
- `,"readmeMd"),Ik=fn(e=>{const{projectName:t,targetDir:r}=e;return S("Scaffolding monorepo workspace..."),Se(r),Se(v(r,"apps")),Se(v(r,"packages")),Z(v(r,"package.json"),jk(t)),ee("Created package.json"),Z(v(r,"pnpm-workspace.yaml"),Ek()),ee("Created pnpm-workspace.yaml"),Z(v(r,".gitignore"),Tk()),ee("Created .gitignore"),Z(v(r,".editorconfig"),Rk()),ee("Created .editorconfig"),Z(v(r,"README.md"),Ak(t)),ee("Created README.md"),Z(v(r,"apps",".gitkeep"),""),Z(v(r,"packages",".gitkeep"),""),0},"executeMonorepoTemplate");var Ok=Object.defineProperty,Ts=b((e,t)=>Ok(e,"name",{value:t,configurable:!0}),"i$d");const Pk={"create-nuxt":{monoArgs:["--no-gitInit"]},"create-vite":{args:["--no-immediate"]},sv:{args:["--no-install"],prependCommand:"create"}},Nk=Ts((e,t,r)=>{const n=Pk[e];if(!n)return t;const o=[...t];if(n.prependCommand&&!o.includes(n.prependCommand)&&o.unshift(n.prependCommand),n.args)for(const i of n.args)o.includes(i)||o.push(i);if(r&&n.monoArgs)for(const i of n.monoArgs)o.includes(i)||o.push(i);return o},"applyAutoFixes"),Mk=Ts((e,t)=>{const r=He(t.cwd,t.targetDir)||".",n=[...e.args];n.includes(r)||n.unshift(r);const o=Nk(e.source,n,t.inMonorepo);return S(`Running ${e.source} via ${t.pm.name} dlx...`),us(t.pm,{additionalPackages:[],args:o,package:e.source,shellMode:!1,silent:!1},t.cwd,t.logger)},"executeRemoteNpm"),Dk=Ts(async(e,t)=>{const{createConfig:r}=t;S(`Downloading template from ${e.source}...`);try{const n=await pl(e.source,{auth:r?.auth||process.env.GIGET_AUTH||process.env.GITHUB_TOKEN||process.env.GH_TOKEN||void 0,dir:t.targetDir,force:!0,preferOffline:r?.preferOffline,provider:r?.defaultProvider,registry:r?.registry});return S(`Downloaded to ${n.dir}`),0}catch(n){const o=n instanceof Error?n.message:String(n);return se(`Failed to download template: ${o}`),1}},"executeRemoteGit");var Bk=Object.defineProperty,Fk=b((e,t)=>Bk(e,"name",{value:t,configurable:!0}),"r$j");const Lk=Fk(async(e,t)=>{switch(e.type){case"builtin:app":case"builtin:library":return vk(e,t);case"builtin:generator":return Sk(t);case"builtin:monorepo":return Ik(t);case"remote:git":return Dk(e,t);case"remote:npm":return Mk(e,t);default:throw new Error(`Unknown template type: ${e.type}`)}},"executeTemplate");var Vk=Object.defineProperty,vr=b((e,t)=>Vk(e,"name",{value:t,configurable:!0}),"m$j");const _k=vr(e=>{const t=v(e,".vscode");Se(t);const r=v(t,"settings.json"),n={"editor.defaultFormatter":"oxc.oxc-vscode","editor.formatOnSave":!0};if(E(r))try{const s=ue(r);Z(r,`${JSON.stringify({...n,...s},null,4)}
294
- `),ee("Merged .vscode/settings.json")}catch{se("Could not merge .vscode/settings.json, skipping")}else Z(r,`${JSON.stringify(n,null,4)}
295
- `),ee("Created .vscode/settings.json");const o=v(t,"extensions.json"),i={recommendations:["oxc.oxc-vscode"]};if(E(o))try{const s=ue(o);Z(o,`${JSON.stringify({...s,recommendations:[...new Set([...s.recommendations||[],...i.recommendations])]},null,4)}
296
- `),ee("Merged .vscode/extensions.json")}catch{se("Could not merge .vscode/extensions.json, skipping")}else Z(o,`${JSON.stringify(i,null,4)}
297
- `),ee("Created .vscode/extensions.json")},"generateVscodeConfig"),Uk=vr((e,t)=>{const r=v(e,".ai");Se(r);const n=v(r,"instructions");if(E(n))return;const o=`# Project Instructions
298
-
299
- This project was scaffolded with vis create.
300
-
301
- ## Development
302
-
303
- - Package manager: ${t}
304
- - Build: \`${t} run build\`
305
- - Test: \`${t} run test\`
306
- - Lint: \`${t} run lint\`
307
-
308
- ## Conventions
309
-
310
- - Use TypeScript strict mode
311
- - ESM modules (\`"type": "module"\`)
312
- - Follow Angular-style conventional commits
313
- `;Z(n,o),ee("Created .ai/instructions")},"generateAiInstructions"),Wk=vr(e=>{De("git",["init"],{cwd:e,stdio:"pipe"}).status===0?ee("Initialized git repository"):se("Failed to initialize git repository")},"initGitRepo"),Gk=vr((e,t,r,n=!1)=>(S("Installing dependencies..."),Ho(t,{dev:!1,filter:[],force:!1,frozenLockfile:!1,ignoreScripts:!1,lockfileOnly:!1,noOptional:!1,offline:n,prod:!1,recursive:!1,silent:!1,workspaceRoot:!1},e,r)===0?(ee("Dependencies installed"),!0):(se("Dependency installation failed (you can run install manually)"),!1)),"installDependencies"),Hk=vr(e=>{const t=e.split("#")[0].split("?")[0].replace(/\/+$/,"").replace(/\.git$/,"").split("/").filter(Boolean).at(-1)??"",r=t.includes(":")?t.split(":").pop()??t:t;return Fn(r)||"my-project"},"extractRepoName"),zk=vr(e=>{if(S(""),S(" Built-in templates:"),S(` ${ve(Fe("vis:monorepo"))} ${re("Full pnpm workspace setup")}`),S(` ${ve(Fe("vis:app"))} ${re("Application scaffold via create-vite")}`),S(` ${ve(Fe("vis:library"))} ${re("Reusable TypeScript library package")}`),S(` ${ve(Fe("vis:generator"))} ${re("Code generator scaffold with bin entry")}`),e&&Object.keys(e).length>0){S(""),S(" Config aliases (vis.config.ts → create.templates):");for(const[t,r]of Object.entries(e))S(` ${ve(Fe(t))}${" ".repeat(Math.max(1,16-t.length))}${re(r)}`)}S(""),S(" Remote templates:"),S(` ${re("Any npm create-* package:")} vis create vite`),S(` ${re("GitHub repository:")} vis create user/repo`),S(` ${re("GitLab / Bitbucket:")} vis create gitlab:user/repo`),S(` ${re("Full URL:")} vis create https://github.com/user/repo`),S(""),S(` ${re("Template args after --:")} vis create vite -- --template react-ts`),S("")},"listTemplates"),qk=vr((e,t,r,n)=>{const o=xe(t)===xe(e)?"":e;process.stderr.write(`
314
- `),ee("Project created successfully!"),process.stderr.write(`
315
- `),ie("Next steps:"),o&&S(` cd ${o}`),n||S(` ${r} install`),S(` ${r} run dev`),process.stderr.write(`
316
- `)},"printNextSteps"),Jk={argument:{description:"Template to use (e.g., vis:app, create-vite, user/repo) — omit for interactive mode",name:"template",type:String},description:"Create a new project from a template",examples:[["vis create","Interactive project scaffolding"],["vis create vis:monorepo my-workspace","Create a monorepo workspace"],["vis create vis:app my-app","Scaffold a Vite application"],["vis create vis:library my-lib","Create a TypeScript library"],["vis create vite my-app -- --template react-ts","Use create-vite with React TypeScript"],["vis create user/repo my-project","Clone a GitHub template"],["vis create --list","Show available templates"]],execute:vr(async({argument:e,logger:t,options:r,rawUnknown:n,visConfig:o,workspaceRoot:i})=>{const s=Array.isArray(e)?e:e?[e]:[],a=o?.create;if(r.list){zk(a?.templates);return}const c=r.cwd||i||process.cwd(),d=!!i,p=!!process.stdin.isTTY,g=Ne(c);let h,y,w,k=a?.defaultEditor,$=a?.gitInit??!1,x=[],T=g,I=!1;if(s.length===0&&p&&!r.noInteractive){const j=await dk({cwd:c,defaultEditor:a?.defaultEditor,defaultGitInit:a?.gitInit,defaultPm:a?.defaultPm,inMonorepo:d});h=j.template,y=j.projectName,w=xe(c,j.targetDir),k=j.editor??k,$=j.gitInit,I=j.overwrite,j.pm&&(T={name:j.pm,version:g.version})}else{if(s.length===0)throw new Error(`No template specified. Usage: vis create <template> [name] [-- args...]
317
- Use --list to see available templates, or run interactively in a terminal.`);{let j=[...n??[]];if(j.length===0){const N=process.argv.slice(2),F=N.indexOf("--");F!==-1&&(j=N.slice(F+1))}const A=s.indexOf("--"),V=A===-1?s:s.slice(0,A);x=[...A===-1?[]:s.slice(A+1),...j],h=V[0],y=V[1],y||(y=Hk(h)),k=r.editor==="vscode"?"vscode":k,$=!!r.gitInit||$}}if(!h)throw new Error("No template specified.");const P=a?.templates?.[h]??h,R=ek(P,x);if(!w){const j=d?tk(R.type):".",A=ak(y,xe(c,j));w=A.targetDir,y=A.packageName}const M=Fn(y??"");if(!Ed(M))throw new Error(`Invalid project name: "${y}". Use lowercase alphanumeric characters and hyphens.`);y=M;const L=xe(w),U=He(xe(c),L);if(U===".."||U.startsWith(`..${qc}`)||st(U))throw new Error(`Target directory "${w}" is outside the working directory. Use a name without "../" path segments.`);if(!I&&!ck(w))throw new Error(`Target directory "${w}" is not empty.
318
- Use a different name or clear the directory first.`);P!==h&&S(`Alias: ${ve(Fe(h))} → ${re(P)}`),S(`Template: ${ve(Fe(P))}`),S(`Project: ${ve(y)}`),S(`Target: ${re(w)}`),process.stderr.write(`
319
- `);const D=await Lk(R,{createConfig:a,cwd:c,inMonorepo:d,logger:t,pm:T,projectName:y,targetDir:w});if(D!==0){process.exitCode=D;return}k==="vscode"&&_k(w),E(w)&&Uk(w,T.name),$&&!d&&Wk(w);let C=!1;a?.install!==!1&&E(v(w,"package.json"))&&(C=Gk(w,T,t,a?.preferOffline)),qk(w,c,T.name,C)},"execute"),group:"Scaffold & Config",name:"create",options:[{defaultValue:!1,description:"Show available templates",name:"list",type:Boolean},{description:"Generate editor configs (vscode)",name:"editor",type:String},{defaultValue:!1,description:"Initialize a git repository",name:"git-init",type:Boolean},{defaultValue:!1,description:"Skip interactive prompts",name:"no-interactive",type:Boolean}]};var Yk=Object.defineProperty,Kk=b((e,t)=>Yk(e,"name",{value:t,configurable:!0}),"i$c");const Xk={description:"Deduplicate dependencies using the detected package manager",examples:[["vis dedupe","Run deduplication"],["vis dedupe --check","Preview changes without modifying (CI-friendly)"]],execute:Kk(async({logger:e,options:t,workspaceRoot:r})=>{const n=r??process.cwd(),o=Ne(n),i=Sm(o,t.check||!1,n,e);i!==0&&(process.exitCode=i)},"execute"),group:"Dependencies",name:"dedupe",options:[{defaultValue:!1,description:"Preview changes without modifying files (dry-run)",name:"check",type:Boolean}]},nn=[{config:{customizations:{vscode:{extensions:["dbaeumer.vscode-eslint","esbenp.prettier-vscode"]}},features:{"ghcr.io/devcontainers/features/git:1":{},"ghcr.io/devcontainers/features/github-cli:1":{}},forwardPorts:[3e3],image:"mcr.microsoft.com/devcontainers/javascript-node:22",name:"Node.js",postCreateCommand:"npm install"},description:"Node.js 22 with Git and GitHub CLI",id:"node",name:"Node.js"},{config:{customizations:{vscode:{extensions:["dbaeumer.vscode-eslint","esbenp.prettier-vscode"]}},features:{"ghcr.io/devcontainers/features/git:1":{},"ghcr.io/devcontainers/features/github-cli:1":{}},forwardPorts:[3e3],image:"mcr.microsoft.com/devcontainers/javascript-node:22",mounts:[{source:"${localWorkspaceFolderBasename}-node_modules",target:"${containerWorkspaceFolder}/node_modules",type:"volume"},{source:"${localWorkspaceFolderBasename}-pnpm-store",target:"/home/node/.local/share/pnpm/store",type:"volume"}],name:"Node.js + pnpm Monorepo",postCreateCommand:"corepack enable && pnpm install",remoteUser:"node",workspaceFolder:"/workspaces/${localWorkspaceFolderBasename}"},description:"Node.js 22 with pnpm, corepack, and optimized volume mounts",id:"node-pnpm",name:"Node.js + pnpm"},{config:{customizations:{vscode:{extensions:["dbaeumer.vscode-eslint","esbenp.prettier-vscode","ms-azuretools.vscode-docker"]}},dockerComposeFile:"docker-compose.yml",forwardPorts:[3e3,5432],name:"Node.js + PostgreSQL",postCreateCommand:"npm install",service:"app",workspaceFolder:"/workspaces/${localWorkspaceFolderBasename}"},description:"Node.js with PostgreSQL via Docker Compose",id:"node-postgres",name:"Node.js + PostgreSQL"},{config:{customizations:{vscode:{extensions:["dbaeumer.vscode-eslint","esbenp.prettier-vscode","ms-azuretools.vscode-docker"]}},features:{"ghcr.io/devcontainers/features/docker-in-docker:2":{},"ghcr.io/devcontainers/features/git:1":{},"ghcr.io/devcontainers/features/github-cli:1":{}},forwardPorts:[3e3],image:"mcr.microsoft.com/devcontainers/javascript-node:22",name:"Node.js + Docker",postCreateCommand:"npm install"},description:"Node.js 22 with Docker-in-Docker for container workflows",id:"node-dind",name:"Node.js + Docker-in-Docker"},{config:{customizations:{vscode:{extensions:["dbaeumer.vscode-eslint","esbenp.prettier-vscode","ms-azuretools.vscode-docker"]}},dockerComposeFile:"docker-compose.yml",features:{"ghcr.io/devcontainers/features/docker-in-docker:2":{}},forwardPorts:[3e3,5432,6379],name:"Full Stack",postCreateCommand:"npm install",service:"app",workspaceFolder:"/workspaces/${localWorkspaceFolderBasename}"},description:"Node.js + PostgreSQL + Redis + Docker via Compose",id:"fullstack",name:"Full Stack"},{config:{customizations:{vscode:{extensions:["ms-python.python","ms-python.vscode-pylance"],settings:{"editor.formatOnSave":!0,"python.defaultInterpreterPath":"/usr/local/bin/python"}}},features:{"ghcr.io/devcontainers/features/git:1":{},"ghcr.io/devcontainers/features/github-cli:1":{},"ghcr.io/devcontainers/features/python:1":{version:"3.12"}},forwardPorts:[8e3],image:"mcr.microsoft.com/devcontainers/python:3.12",name:"Python",postCreateCommand:"pip install -r requirements.txt || true"},description:"Python 3.12 with pip and venv",id:"python",name:"Python"},{config:{customizations:{vscode:{extensions:["golang.go"],settings:{"editor.formatOnSave":!0,"go.toolsManagement.autoUpdate":!0}}},features:{"ghcr.io/devcontainers/features/git:1":{},"ghcr.io/devcontainers/features/go:1":{version:"1.22"}},forwardPorts:[8080],image:"mcr.microsoft.com/devcontainers/go:1.22",name:"Go",postCreateCommand:"go mod download || true"},description:"Go 1.22 development environment",id:"go",name:"Go"},{config:{customizations:{vscode:{extensions:["rust-lang.rust-analyzer","tamasfe.even-better-toml"],settings:{"editor.formatOnSave":!0}}},features:{"ghcr.io/devcontainers/features/git:1":{},"ghcr.io/devcontainers/features/rust:1":{}},image:"mcr.microsoft.com/devcontainers/rust:latest",name:"Rust",postCreateCommand:"cargo build || true"},description:"Rust development with cargo and rust-analyzer",id:"rust",name:"Rust"},{config:{customizations:{vscode:{extensions:["vscjava.vscode-java-pack","vscjava.vscode-maven"]}},features:{"ghcr.io/devcontainers/features/git:1":{},"ghcr.io/devcontainers/features/java:1":{version:"17"}},forwardPorts:[8080],image:"mcr.microsoft.com/devcontainers/java:17",name:"Java",postCreateCommand:"./mvnw install || ./gradlew build || true"},description:"Java 17 with Maven/Gradle support",id:"java",name:"Java"},{config:{customizations:{vscode:{extensions:["ms-azuretools.vscode-docker","ms-kubernetes-tools.vscode-kubernetes-tools","hashicorp.terraform"]}},features:{"ghcr.io/devcontainers/features/aws-cli:1":{},"ghcr.io/devcontainers/features/azure-cli:1":{},"ghcr.io/devcontainers/features/docker-in-docker:2":{},"ghcr.io/devcontainers/features/kubectl-helm-minikube:1":{},"ghcr.io/devcontainers/features/terraform:1":{}},image:"mcr.microsoft.com/devcontainers/base:ubuntu",name:"DevOps"},description:"Docker, Kubernetes, Terraform, AWS & Azure CLIs",id:"devops",name:"DevOps"},{config:{features:{"ghcr.io/devcontainers/features/common-utils:2":{}},image:"mcr.microsoft.com/devcontainers/base:ubuntu",name:"Minimal",remoteUser:"vscode"},description:"Bare Ubuntu with common utilities",id:"minimal",name:"Minimal"},{config:{image:"mcr.microsoft.com/devcontainers/base:ubuntu",name:"Custom"},description:"Minimal Ubuntu base - configure from scratch",id:"custom",name:"Custom (Blank)"}];var Qk=Object.defineProperty,Rd=b((e,t)=>Qk(e,"name",{value:t,configurable:!0}),"s$n");const Zk=Rd(e=>{const t=v(e,".devcontainer","devcontainer.json");if(!E(t))return null;const r=q(t),n=Gp(r),o=n!==r;let i;try{i=JSON.parse(n)}catch(s){const a=s instanceof Error?s.message:String(s);throw new Error(`Failed to parse ${t}: ${a}`)}return{config:i,hadComments:o}},"readDevcontainerJson"),eb=Rd((e,t,r)=>{const n=r?Lt(r):v(e,".devcontainer"),o=r??v(n,"devcontainer.json");Se(n),me(o,`${JSON.stringify(t,null,2)}
320
- `,"utf8")},"writeDevcontainerJson");var tb=Object.defineProperty,rb=b((e,t)=>tb(e,"name",{value:t,configurable:!0}),"s$m");const nb={bun:[{source:"${localWorkspaceFolderBasename}-node_modules",target:"${containerWorkspaceFolder}/node_modules",type:"volume"},{source:"${localWorkspaceFolderBasename}-bun-cache",target:"/home/node/.bun/install/cache",type:"volume"}],npm:[{source:"${localWorkspaceFolderBasename}-node_modules",target:"${containerWorkspaceFolder}/node_modules",type:"volume"},{source:"${localWorkspaceFolderBasename}-npm-cache",target:"/home/node/.npm",type:"volume"}],pnpm:[{source:"${localWorkspaceFolderBasename}-node_modules",target:"${containerWorkspaceFolder}/node_modules",type:"volume"},{source:"${localWorkspaceFolderBasename}-pnpm-store",target:"/home/node/.local/share/pnpm/store",type:"volume"}],yarn:[{source:"${localWorkspaceFolderBasename}-node_modules",target:"${containerWorkspaceFolder}/node_modules",type:"volume"},{source:"${localWorkspaceFolderBasename}-yarn-cache",target:"/home/node/.yarn/cache",type:"volume"}]},ob=[{featureMatch:"docker-in-docker",mounts:[]},{featureMatch:"docker-outside-of-docker",mounts:[{source:"/var/run/docker.sock",target:"/var/run/docker.sock",type:"bind"}]},{featureMatch:"/features/git:",mounts:[{source:"${localWorkspaceFolderBasename}-git-config",target:"/home/node/.gitconfig",type:"volume"}]}],_a=rb((e,t,r)=>{const n=[],o=new Set(r.map(s=>typeof s=="string"?s:s.target));if(e)for(const s of nb[e])o.has(s.target)||n.push(s);const i=Object.keys(t);for(const{featureMatch:s,mounts:a}of ob)if(i.some(c=>c.includes(s)))for(const c of a)o.has(c.target)||n.push(c);return n},"getSuggestedMounts"),Cr=["general","features","ports","lifecycle","extensions","environment","mounts","compose"];var ib=Object.defineProperty,wo=b((e,t)=>ib(e,"name",{value:t,configurable:!0}),"c$r");const kn=wo(e=>structuredClone(e),"deepClone");class sb{static{b(this,"DevcontainerStore")}static{wo(this,"DevcontainerStore")}#e=new Set;#t;constructor(t,r,n=null){const o=t===null,i=t??{name:""},s=kn(i);this.#t={config:s,detectedPm:n,extensionSearch:"",featureSearch:"",fieldEditing:!1,fieldIndex:0,hadComments:r,isDirty:!1,mode:o?"create":"edit",originalConfig:o?null:kn(i),section:"general",showTemplateSelector:o,suggestedMounts:_a(n,s.features??{},s.mounts??[]),templateIndex:0}}getSnapshot=wo(()=>this.#t,"getSnapshot");subscribe=wo(t=>(this.#e.add(t),()=>{this.#e.delete(t)}),"subscribe");setSection(t){t!==this.#t.section&&this.#r({...this.#t,fieldEditing:!1,fieldIndex:0,section:t})}nextSection(){const t=(Cr.indexOf(this.#t.section)+1)%Cr.length;this.setSection(Cr[t])}previousSection(){const t=(Cr.indexOf(this.#t.section)-1+Cr.length)%Cr.length;this.setSection(Cr[t])}setFieldIndex(t){t!==this.#t.fieldIndex&&this.#r({...this.#t,fieldIndex:Math.max(0,t)})}setFieldEditing(t){t!==this.#t.fieldEditing&&this.#r({...this.#t,fieldEditing:t})}setTemplateIndex(t){const r=Math.max(0,Math.min(t,nn.length-1));r!==this.#t.templateIndex&&this.#r({...this.#t,templateIndex:r})}applyTemplate(t){const r=nn.find(n=>n.id===t);r&&this.#r(this.#o({...this.#t,config:kn(r.config),isDirty:!0,showTemplateSelector:!1}))}dismissTemplateSelector(){this.#r({...this.#t,showTemplateSelector:!1})}updateConfig(t){this.#r({...this.#t,config:{...this.#t.config,...t},isDirty:!0})}toggleFeature(t){const r={...this.#t.config.features};r[t]===void 0?r[t]={}:delete r[t],this.#r(this.#o({...this.#t,config:{...this.#t.config,features:r},isDirty:!0}))}setFeatureSearch(t){this.#r({...this.#t,featureSearch:t,fieldIndex:0})}addPort(t){const r=this.#t.config.forwardPorts??[];if(r.includes(t))return;const n=[...r,t];this.#r({...this.#t,config:{...this.#t.config,forwardPorts:n},isDirty:!0})}removePort(t){const r=[...this.#t.config.forwardPorts??[]];r.splice(t,1),this.#r({...this.#t,config:{...this.#t.config,forwardPorts:r.length>0?r:void 0},isDirty:!0})}toggleExtension(t){const r={...this.#t.config.customizations},n={...r.vscode},o=[...n.extensions??[]],i=o.indexOf(t);i===-1?o.push(t):o.splice(i,1),n.extensions=o.length>0?o:void 0,r.vscode=n.extensions||n.settings?n:void 0,this.#r({...this.#t,config:{...this.#t.config,customizations:r.vscode||r.jetbrains?r:void 0},isDirty:!0})}setExtensionSearch(t){this.#r({...this.#t,extensionSearch:t,fieldIndex:0})}addEnvVar(t,r,n){const o=t==="container"?"containerEnv":"remoteEnv",i={...this.#t.config[o],[r]:n};this.#r({...this.#t,config:{...this.#t.config,[o]:i},isDirty:!0})}removeEnvVar(t,r){const n=t==="container"?"containerEnv":"remoteEnv",o={...this.#t.config[n]};delete o[r],this.#r({...this.#t,config:{...this.#t.config,[n]:Object.keys(o).length>0?o:void 0},isDirty:!0})}addMount(t){const r=[...this.#t.config.mounts??[],t];this.#r(this.#o({...this.#t,config:{...this.#t.config,mounts:r},isDirty:!0}))}removeMount(t){const r=[...this.#t.config.mounts??[]];r.splice(t,1),this.#r(this.#o({...this.#t,config:{...this.#t.config,mounts:r.length>0?r:void 0},isDirty:!0}))}applySuggestedMounts(){if(this.#t.suggestedMounts.length===0)return;const t=[...this.#t.config.mounts??[],...this.#t.suggestedMounts];this.#r(this.#o({...this.#t,config:{...this.#t.config,mounts:t},isDirty:!0}))}setLifecycleCommand(t,r){this.#r({...this.#t,config:{...this.#t.config,[t]:r||void 0},isDirty:!0})}markClean(){this.#r({...this.#t,isDirty:!1,originalConfig:kn(this.#t.config)})}getJsonPreview(){return JSON.stringify(this.#n(),null,2)}cleanConfig(){return this.#n()}#n(){const t=kn(this.#t.config);for(const[r,n]of Object.entries(t))(n===""||n===void 0)&&delete t[r];return t.build&&(t.build.dockerfile===""&&delete t.build.dockerfile,t.build.context===""&&delete t.build.context,t.build.args&&Object.keys(t.build.args).length===0&&delete t.build.args,Object.keys(t.build).length===0&&delete t.build),t.forwardPorts?.length===0&&delete t.forwardPorts,t.mounts?.length===0&&delete t.mounts,t.runServices?.length===0&&delete t.runServices,t.capAdd?.length===0&&delete t.capAdd,t.securityOpt?.length===0&&delete t.securityOpt,t.features&&Object.keys(t.features).length===0&&delete t.features,t.customizations?.vscode?.extensions?.length===0&&delete t.customizations.vscode.extensions,t.customizations?.vscode&&Object.keys(t.customizations.vscode).length===0&&delete t.customizations.vscode,t.customizations&&Object.keys(t.customizations).length===0&&delete t.customizations,t.containerEnv&&Object.keys(t.containerEnv).length===0&&delete t.containerEnv,t.remoteEnv&&Object.keys(t.remoteEnv).length===0&&delete t.remoteEnv,t}#o(t){return{...t,suggestedMounts:_a(t.detectedPm,t.config.features??{},t.config.mounts??[])}}#r(t){this.#t=t;for(const r of this.#e)try{r()}catch{}}}const Ua=[{category:"linting",description:"Integrates ESLint into the editor",id:"dbaeumer.vscode-eslint",name:"ESLint"},{category:"linting",description:"Stylelint CSS/SCSS linting",id:"stylelint.vscode-stylelint",name:"Stylelint"},{category:"formatting",description:"Opinionated code formatter",id:"esbenp.prettier-vscode",name:"Prettier"},{category:"formatting",description:"EditorConfig file support",id:"editorconfig.editorconfig",name:"EditorConfig"},{category:"formatting",description:"Fast Rust-based formatter and linter",id:"biomejs.biome",name:"Biome"},{category:"language",description:"Rich TypeScript and JavaScript support",id:"ms-vscode.vscode-typescript-next",name:"TypeScript Nightly"},{category:"language",description:"Tailwind CSS IntelliSense",id:"bradlc.vscode-tailwindcss",name:"Tailwind CSS"},{category:"language",description:"YAML language support with schemas",id:"redhat.vscode-yaml",name:"YAML"},{category:"language",description:"TOML language support",id:"tamasfe.even-better-toml",name:"TOML"},{category:"language",description:"Dockerfile and Docker Compose support",id:"ms-azuretools.vscode-docker",name:"Docker"},{category:"language",description:"Python language support with Pylance",id:"ms-python.python",name:"Python"},{category:"language",description:"Go language support",id:"golang.go",name:"Go"},{category:"language",description:"Rust language support via rust-analyzer",id:"rust-lang.rust-analyzer",name:"rust-analyzer"},{category:"git",description:"Git supercharged: blame, history, stash, etc.",id:"eamodio.gitlens",name:"GitLens"},{category:"git",description:"GitHub Pull Requests and Issues",id:"github.vscode-pull-request-github",name:"GitHub PR"},{category:"testing",description:"Vitest test explorer integration",id:"vitest.explorer",name:"Vitest Explorer"},{category:"testing",description:"Jest test runner and assertions",id:"orta.vscode-jest",name:"Jest"},{category:"debugging",description:"REST client for testing APIs",id:"humao.rest-client",name:"REST Client"},{category:"debugging",description:"Error Lens: inline error highlighting",id:"usernamehw.errorlens",name:"Error Lens"},{category:"other",description:"Intelligent code completion with AI",id:"github.copilot",name:"GitHub Copilot"},{category:"other",description:"Path autocompletion for imports",id:"christian-kohler.path-intellisense",name:"Path Intellisense"},{category:"other",description:"Import cost display in editor",id:"wix.vscode-import-cost",name:"Import Cost"},{category:"other",description:"Todo Tree: highlight and list TODOs",id:"gruntfuggly.todo-tree",name:"Todo Tree"}],Wa=[{category:"language",description:"Node.js runtime via nvm with optional pnpm/yarn",id:"ghcr.io/devcontainers/features/node:1",name:"Node.js"},{category:"language",description:"Python runtime with pip and optional tools",id:"ghcr.io/devcontainers/features/python:1",name:"Python"},{category:"language",description:"Go compiler and tools",id:"ghcr.io/devcontainers/features/go:1",name:"Go"},{category:"language",description:"Rust toolchain via rustup",id:"ghcr.io/devcontainers/features/rust:1",name:"Rust"},{category:"language",description:"Java runtime and JDK via SDKMAN",id:"ghcr.io/devcontainers/features/java:1",name:"Java"},{category:"language",description:".NET SDK and runtime",id:"ghcr.io/devcontainers/features/dotnet:2",name:".NET"},{category:"tool",description:"Common utilities: zsh, Oh My Zsh, git, curl, etc.",id:"ghcr.io/devcontainers/features/common-utils:2",name:"Common Utilities"},{category:"tool",description:"Git version control",id:"ghcr.io/devcontainers/features/git:1",name:"Git"},{category:"tool",description:"Git Large File Storage support",id:"ghcr.io/devcontainers/features/git-lfs:1",name:"Git LFS"},{category:"tool",description:"GitHub CLI for repository management",id:"ghcr.io/devcontainers/features/github-cli:1",name:"GitHub CLI"},{category:"tool",description:"Run Docker containers inside the dev container",id:"ghcr.io/devcontainers/features/docker-in-docker:2",name:"Docker-in-Docker"},{category:"tool",description:"Access host Docker daemon from inside the container",id:"ghcr.io/devcontainers/features/docker-outside-of-docker:1",name:"Docker-from-Docker"},{category:"tool",description:"kubectl, Helm, and Minikube for Kubernetes",id:"ghcr.io/devcontainers/features/kubectl-helm-minikube:1",name:"Kubernetes Tools"},{category:"tool",description:"Infrastructure as code with Terraform",id:"ghcr.io/devcontainers/features/terraform:1",name:"Terraform"},{category:"tool",description:"Nix package manager",id:"ghcr.io/devcontainers/features/nix:1",name:"Nix"},{category:"tool",description:"SSH server for remote connections to the container",id:"ghcr.io/devcontainers/features/sshd:1",name:"SSH Server"},{category:"cloud",description:"Amazon Web Services CLI v2",id:"ghcr.io/devcontainers/features/aws-cli:1",name:"AWS CLI"},{category:"cloud",description:"Microsoft Azure CLI",id:"ghcr.io/devcontainers/features/azure-cli:1",name:"Azure CLI"},{category:"cloud",description:"Google Cloud Platform CLI",id:"ghcr.io/devcontainers/features/gcloud:1",name:"Google Cloud CLI"},{category:"database",description:"PostgreSQL client tools",id:"ghcr.io/devcontainers-extra/features/postgres-client:1",name:"PostgreSQL Client"},{category:"database",description:"Redis client tools",id:"ghcr.io/devcontainers-extra/features/redis-client:1",name:"Redis Client"}];var ab=Object.defineProperty,Ad=b((e,t)=>ab(e,"name",{value:t,configurable:!0}),"r$g");const Rs=Ad(e=>{if(!e)return Wa;const t=e.toLowerCase();return Wa.filter(r=>r.name.toLowerCase().includes(t)||r.id.toLowerCase().includes(t)||r.description.toLowerCase().includes(t))},"filterFeatures"),As=Ad(e=>{if(!e)return Ua;const t=e.toLowerCase();return Ua.filter(r=>r.name.toLowerCase().includes(t)||r.id.toLowerCase().includes(t)||r.description.toLowerCase().includes(t))},"filterExtensions");var cb=Object.defineProperty,lb=b((e,t)=>cb(e,"name",{value:t,configurable:!0}),"l$h");const Id=["dockerComposeFile","service"],db={dockerComposeFile:"Compose File",service:"Service"},Ga={dockerComposeFile:"docker-compose.yml",service:"app"},ub={dockerComposeFile:"Path to Docker Compose file (relative to .devcontainer/)",service:"Which service in the compose file to connect the IDE to"},pb=lb(({config:e,fieldEditing:t,fieldIndex:r,onUpdate:n})=>{const o=!!e.dockerComposeFile,i=!!(e.image||e.build);return f(m,{flexDirection:"column",paddingX:1,children:[u(m,{marginBottom:1,children:u(l,{bold:!0,color:"cyan",children:"Docker Compose Integration"})}),i&&o&&u(m,{marginBottom:1,children:u(l,{color:"yellow",children:"Note: When using Docker Compose, the image/build settings in General are ignored."})}),Id.map((s,a)=>{const c=a===r,d=e[s]??"",p=Array.isArray(e[s])?e[s].join(", "):d;return f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{children:[u(m,{width:20,children:f(l,{bold:c,color:c?"cyan":"white",children:[c?"❯ ":" ",db[s],":"]})}),u(m,{flexGrow:1,children:c&&t?u(is,{defaultValue:p,onChange:b(g=>{n({[s]:g||void 0})},"onChange"),placeholder:Ga[s]}):u(l,{color:p?"white":"gray",children:p||Ga[s]})})]}),u(m,{paddingLeft:4,children:u(l,{dimColor:!0,children:ub[s]})})]},s)}),u(m,{marginTop:1,children:f(l,{dimColor:!0,children:[u(l,{bold:!0,color:"white",children:"Enter"})," ","edit field"," ",u(l,{bold:!0,color:"white",children:"↑↓"})," ","navigate"," ",u(l,{bold:!0,color:"white",children:"Esc"})," ","stop editing"]})})]})},"DockerComposeSection"),fb=Id.length;var gb=Object.defineProperty,Od=b((e,t)=>gb(e,"name",{value:t,configurable:!0}),"h$n");const mb=Od(({config:e,fieldIndex:t})=>{const r=e.containerEnv??{},n=e.remoteEnv??{},o=Object.keys(r),i=Object.keys(n),s=o.length,a=o.length+1,c=a+i.length,d=t<=s,p=t>s;return f(m,{flexDirection:"column",paddingX:1,children:[f(m,{borderColor:d?"cyan":"gray",borderStyle:"single",flexDirection:"column",paddingX:1,paddingY:0,children:[f(m,{flexShrink:0,marginBottom:o.length>0?1:0,children:[u(l,{bold:!0,color:d?"cyan":"white",children:"containerEnv"}),u(l,{dimColor:!0,children:" — baked into the container image"})]}),o.map((g,h)=>{const y=h===t;return u(m,{flexShrink:0,children:f(l,{color:y?"cyan":void 0,inverse:y,wrap:"truncate",children:[y?" ❯ ":" ",u(l,{bold:!0,children:g}),u(l,{dimColor:!0,children:" = "}),u(l,{children:r[g]})]})},g)}),u(m,{flexShrink:0,marginTop:o.length>0?1:0,children:f(l,{color:t===s?"cyan":"gray",inverse:t===s,children:[" ","+ Add variable..."]})})]}),f(m,{borderColor:p?"cyan":"gray",borderStyle:"single",flexDirection:"column",marginTop:1,paddingX:1,paddingY:0,children:[f(m,{flexShrink:0,marginBottom:i.length>0?1:0,children:[u(l,{bold:!0,color:p?"cyan":"white",children:"remoteEnv"}),u(l,{dimColor:!0,children:" — set at runtime by the IDE"})]}),i.map((g,h)=>{const y=a+h===t;return u(m,{flexShrink:0,children:f(l,{color:y?"cyan":void 0,inverse:y,wrap:"truncate",children:[y?" ❯ ":" ",u(l,{bold:!0,children:g}),u(l,{dimColor:!0,children:" = "}),u(l,{children:n[g]})]})},g)}),u(m,{flexShrink:0,marginTop:i.length>0?1:0,children:f(l,{color:t===c?"cyan":"gray",inverse:t===c,children:[" ","+ Add variable..."]})})]}),u(m,{flexShrink:0,marginTop:1,children:f(l,{dimColor:!0,wrap:"truncate",children:[u(l,{bold:!0,color:"white",children:"a"}),"/",u(l,{bold:!0,color:"white",children:"Enter"})," ","add on + row"," ",u(l,{bold:!0,color:"white",children:"d"})," ","remove"," ",u(l,{bold:!0,color:"white",children:"↑↓"})," ","navigate"]})})]})},"EnvironmentSection"),hb=Od(e=>{const t=Object.keys(e.containerEnv??{}).length,r=Object.keys(e.remoteEnv??{}).length;return t+1+r+1},"getEnvFieldCount");var yb=Object.defineProperty,vb=b((e,t)=>yb(e,"name",{value:t,configurable:!0}),"h$m");const wb=vb(({config:e,fieldIndex:t,scrollOffset:r,searchText:n,viewportHeight:o})=>{const i=Dt(()=>new Set(e.customizations?.vscode?.extensions),[e.customizations?.vscode?.extensions]),s=Dt(()=>As(n),[n]),a=s.length,c=a>o&&o>0;return f(m,{flexDirection:"column",flexGrow:1,children:[f(m,{flexShrink:0,gap:1,paddingX:1,children:[f(l,{bold:!0,color:"cyan",children:[i.size," ","selected"]}),n&&f(l,{dimColor:!0,children:["— filter:"," ",u(l,{color:"yellow",children:n})," ","(",s.length," ","results)"]})]}),f(m,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[u(m,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:u(m,{flexDirection:"column",marginTop:-r,children:s.map((d,p)=>{const g=p===t,h=i.has(d.id);return f(m,{flexShrink:0,height:1,children:[u(l,{children:g?">":" "}),f(l,{color:h?"white":"gray",children:[" ",h?"☑":"☐"," "]}),u(m,{flexGrow:1,children:f(l,{bold:g,inverse:g,wrap:"truncate",children:[d.name,f(l,{dimColor:!0,children:[" ","-",d.id]})]})})]},d.id)})})}),c&&u(m,{flexShrink:0,marginLeft:1,marginRight:1,children:u(Gn,{contentHeight:a,placement:"inset",scrollOffset:r,style:"block",viewportHeight:o})})]}),s.length===0&&u(m,{paddingX:1,children:u(l,{dimColor:!0,children:"No extensions match the search."})})]})},"ExtensionsSection");var kb=Object.defineProperty,bb=b((e,t)=>kb(e,"name",{value:t,configurable:!0}),"p$w");const $b=bb(({config:e,fieldIndex:t,scrollOffset:r,searchText:n,viewportHeight:o})=>{const i=Dt(()=>new Set(Object.keys(e.features??{})),[e.features]),s=Dt(()=>Rs(n),[n]),a=s.length,c=a>o&&o>0;return f(m,{flexDirection:"column",flexGrow:1,children:[f(m,{flexShrink:0,gap:1,paddingX:1,children:[f(l,{bold:!0,color:"cyan",children:[i.size," ","selected"]}),n&&f(l,{dimColor:!0,children:["— filter:"," ",u(l,{color:"yellow",children:n})," ","(",s.length," ","results)"]})]}),f(m,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[u(m,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:u(m,{flexDirection:"column",marginTop:-r,children:s.map((d,p)=>{const g=p===t,h=i.has(d.id);return f(m,{flexShrink:0,height:1,children:[u(l,{children:g?">":" "}),f(l,{color:h?"white":"gray",children:[" ",h?"☑":"☐"," "]}),u(m,{flexGrow:1,children:f(l,{bold:g,inverse:g,wrap:"truncate",children:[d.name,f(l,{dimColor:!0,children:[" ","-",d.description]})]})})]},d.id)})})}),c&&u(m,{flexShrink:0,marginLeft:1,marginRight:1,children:u(Gn,{contentHeight:a,placement:"inset",scrollOffset:r,style:"block",viewportHeight:o})})]}),s.length===0&&u(m,{paddingX:1,children:u(l,{dimColor:!0,children:"No features match the search."})})]})},"FeaturesSection");var xb=Object.defineProperty,Sb=b((e,t)=>xb(e,"name",{value:t,configurable:!0}),"u$j");const Fi=["name","image","workspaceFolder","workspaceMount","remoteUser","containerUser","shutdownAction"],Cb={containerUser:"Container User",image:"Image",name:"Name",remoteUser:"Remote User",shutdownAction:"Shutdown Action",workspaceFolder:"Workspace Folder",workspaceMount:"Workspace Mount"},Ha={containerUser:"root",image:"mcr.microsoft.com/devcontainers/javascript-node:22",name:"My Dev Container",remoteUser:"node",shutdownAction:"none | stopContainer",workspaceFolder:"/workspaces/${localWorkspaceFolderBasename}",workspaceMount:"source=${localWorkspaceFolder},target=...,type=bind"},Ro=["privileged","overrideCommand"],jb={overrideCommand:"Override Command",privileged:"Privileged"},Eb=Fi.length+Ro.length,Tb=Sb(({config:e,fieldEditing:t,fieldIndex:r,onUpdate:n})=>f(m,{flexDirection:"column",paddingX:1,children:[u(m,{marginBottom:1,children:u(l,{bold:!0,color:"cyan",children:"General Configuration"})}),Fi.map((o,i)=>{const s=i===r,a=e[o]??"";return f(m,{marginBottom:1,children:[u(m,{width:20,children:f(l,{bold:s,color:s?"cyan":"white",children:[s?"❯ ":" ",Cb[o],":"]})}),u(m,{flexGrow:1,children:s&&t?u(is,{defaultValue:a,onChange:b(c=>{n({[o]:c})},"onChange"),placeholder:Ha[o]}):u(l,{color:a?"white":"gray",children:a||Ha[o]})})]},o)}),Ro.map((o,i)=>{const s=Fi.length+i===r,a=e[o]??!1;return f(m,{marginBottom:i<Ro.length-1?1:0,children:[u(m,{width:20,children:f(l,{bold:s,color:s?"cyan":"white",children:[s?"❯ ":" ",jb[o],":"]})}),u(m,{flexGrow:1,children:f(l,{color:a?"green":"gray",children:[a?"yes":"no",s&&u(l,{dimColor:!0,children:" (Space to toggle)"})]})})]},o)}),u(m,{marginTop:1,children:f(l,{dimColor:!0,children:[u(l,{bold:!0,color:"white",children:"Enter"})," ","edit field"," ",u(l,{bold:!0,color:"white",children:"Space"})," ","toggle"," ",u(l,{bold:!0,color:"white",children:"↑↓"})," ","navigate"," ",u(l,{bold:!0,color:"white",children:"Esc"})," ","stop editing"]})})]}),"GeneralSection"),Pd=Eb,xi=Ro;var Rb=Object.defineProperty,Ab=b((e,t)=>Rb(e,"name",{value:t,configurable:!0}),"s$k");const Nd=["postCreateCommand","postStartCommand","postAttachCommand","onCreateCommand"],Ib={onCreateCommand:"On Create",postAttachCommand:"Post Attach",postCreateCommand:"Post Create",postStartCommand:"Post Start"},Ob={onCreateCommand:"Runs once when the container is first created",postAttachCommand:"Runs each time the IDE attaches",postCreateCommand:"Runs after the container is created and workspace mounted",postStartCommand:"Runs each time the container starts"},Pb=Ab(({config:e,fieldEditing:t,fieldIndex:r,onSetCommand:n})=>f(m,{flexDirection:"column",paddingX:1,children:[u(m,{marginBottom:1,children:u(l,{bold:!0,color:"cyan",children:"Lifecycle Commands"})}),Nd.map((o,i)=>{const s=i===r,a=e[o],c=Array.isArray(a)?a.join(" && "):a??"";return f(m,{flexDirection:"column",marginBottom:1,children:[u(m,{children:f(l,{bold:s,color:s?"cyan":"white",children:[s?"❯ ":" ",Ib[o]]})}),u(m,{paddingLeft:4,children:u(l,{dimColor:!0,children:Ob[o]})}),u(m,{paddingLeft:4,children:s&&t?u(is,{defaultValue:c,onChange:b(d=>{n(o,d)},"onChange"),placeholder:"e.g. npm install"}):u(l,{color:c?"green":"gray",children:c||"(not set)"})})]},o)}),u(m,{marginTop:1,children:f(l,{dimColor:!0,children:[u(l,{bold:!0,color:"white",children:"Enter"})," ","edit command"," ",u(l,{bold:!0,color:"white",children:"↑↓"})," ","navigate"," ",u(l,{bold:!0,color:"white",children:"Esc"})," ","stop editing"]})})]}),"LifecycleSection"),Nb=Nd.length;var Mb=Object.defineProperty,Md=b((e,t)=>Mb(e,"name",{value:t,configurable:!0}),"s$j");const za=Md(e=>typeof e=="string"?e:`[${e.type}] ${e.source} → ${e.target}`,"formatMount"),Db=Md(({addingMount:e,config:t,detectedPm:r,fieldIndex:n,mountPhase:o,mountSource:i,mountTarget:s,mountType:a,suggestedMounts:c})=>{const d=t.mounts??[];return f(m,{flexDirection:"column",paddingX:1,children:[f(m,{flexShrink:0,gap:1,paddingX:1,children:[f(l,{bold:!0,color:"cyan",children:[d.length," ","mounts"]}),r&&f(l,{dimColor:!0,children:["— detected:"," ",u(l,{color:"white",children:r})]})]}),c.length>0&&!e&&f(m,{borderColor:"yellow",borderStyle:"single",flexDirection:"column",marginBottom:1,marginTop:1,paddingX:1,children:[f(m,{flexShrink:0,children:[u(l,{bold:!0,color:"yellow",children:"Suggested mounts"}),f(l,{dimColor:!0,children:[" ","— press"," ",u(l,{bold:!0,color:"white",children:"A"})," ","to add all"]})]}),c.map((p,g)=>u(m,{flexShrink:0,children:f(l,{dimColor:!0,wrap:"truncate",children:[" + ",za(p)]})},`suggestion-${String(g)}`))]}),d.length>0&&u(m,{flexDirection:"column",marginBottom:1,children:d.map((p,g)=>{const h=g===n;return f(m,{flexShrink:0,height:1,children:[u(l,{children:h?">":" "}),u(m,{flexGrow:1,children:f(l,{bold:h,inverse:h,wrap:"truncate",children:[" ",za(p)]})})]},`mount-${String(g)}`)})}),!e&&u(m,{flexShrink:0,children:f(l,{color:n===d.length?"cyan":"gray",inverse:n===d.length,children:[" ","+ Add mount..."]})}),e&&f(m,{borderColor:"cyan",borderStyle:"single",flexDirection:"column",marginTop:1,paddingX:1,children:[u(m,{flexShrink:0,marginBottom:1,children:u(l,{bold:!0,color:"cyan",children:"New Mount"})}),f(m,{flexShrink:0,children:[u(m,{width:12,children:f(l,{bold:o==="source",color:o==="source"?"cyan":"white",children:[o==="source"?"❯ ":" ","Source:"]})}),u(l,{color:i?"yellow":"gray",children:i||(o==="source"?"_":"(type source, Enter to continue)")})]}),f(m,{flexShrink:0,children:[u(m,{width:12,children:f(l,{bold:o==="target",color:o==="target"?"cyan":"white",children:[o==="target"?"❯ ":" ","Target:"]})}),u(l,{color:s?"yellow":"gray",children:s||(o==="target"?"_":"/container/path")})]}),f(m,{flexShrink:0,children:[u(m,{width:12,children:f(l,{bold:o==="type",color:o==="type"?"cyan":"white",children:[o==="type"?"❯ ":" ","Type:"]})}),o==="type"?f(l,{children:[u(l,{bold:a==="volume",color:a==="volume"?"cyan":"gray",children:"[1] volume"})," ",u(l,{bold:a==="bind",color:a==="bind"?"cyan":"gray",children:"[2] bind"})," ",u(l,{bold:a==="tmpfs",color:a==="tmpfs"?"cyan":"gray",children:"[3] tmpfs"})]}):u(l,{color:"gray",children:a})]}),u(m,{flexShrink:0,marginTop:1,children:u(l,{dimColor:!0,wrap:"truncate",children:o==="type"?"1/2/3 select type, Enter confirm, Esc cancel":"Type text, Enter next step, Esc cancel"})})]}),d.length===0&&!e&&c.length===0&&u(m,{marginTop:1,children:u(l,{dimColor:!0,children:"Tip: Use volume mounts for node_modules and caches to improve performance."})})]})},"MountsSection");var Bb=Object.defineProperty,Fb=b((e,t)=>Bb(e,"name",{value:t,configurable:!0}),"m$g");const Lb=Fb(({addingPort:e,addPortValue:t,config:r,fieldIndex:n})=>{const o=r.forwardPorts??[],i=n===o.length;return f(m,{flexDirection:"column",paddingX:1,children:[f(m,{marginBottom:1,children:[u(l,{bold:!0,color:"cyan",children:"Forwarded Ports"}),f(l,{dimColor:!0,children:[" ","(",o.length," ","ports)"]})]}),o.map((s,a)=>{const c=a===n;return u(m,{children:f(l,{color:c?"cyan":void 0,inverse:c,children:[" ",String(s)]})},`port-${String(s)}`)}),u(m,{marginTop:o.length>0?1:0,children:f(l,{color:i?"cyan":"gray",inverse:i,children:[" ",i&&e?f(l,{children:["Enter port:"," ",u(l,{color:"yellow",children:t||"_"})]}):"+ Add port..."]})}),u(m,{marginTop:1,children:f(l,{dimColor:!0,children:[u(l,{bold:!0,color:"white",children:"Enter"})," ",i?"type port number, Enter to confirm":"select"," ",u(l,{bold:!0,color:"white",children:"d"})," ","remove selected"," ",u(l,{bold:!0,color:"white",children:"↑↓"})," ","navigate"]})})]})},"PortsSection");var Vb=Object.defineProperty,_b=b((e,t)=>Vb(e,"name",{value:t,configurable:!0}),"a$i");const Ub=_b(({focused:e,hadComments:t,jsonPreview:r,mode:n,scrollRef:o})=>f(m,{borderColor:e?"cyan":"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,children:[f(m,{flexShrink:0,paddingX:1,children:[u(l,{bold:!0,color:e?"cyan":"white",children:"Preview"}),f(l,{dimColor:!0,children:[" ","(",n==="create"?"new":"edit",")"]})]}),t&&n==="edit"&&u(m,{flexShrink:0,paddingX:1,children:u(l,{color:"yellow",children:"Comments will not be preserved."})}),u(cn,{flexGrow:1,ref:o,scrollbar:!0,scrollbarColor:"gray",children:r.split(`
321
- `).map((i,s)=>u(l,{color:"green",children:i},`line-${String(s)}`))})]}),"PreviewPanel");var Wb=Object.defineProperty,Gb=b((e,t)=>Wb(e,"name",{value:t,configurable:!0}),"r$f");const Hb=Gb(e=>{const t=[],r=[],n=[];if(!e.image&&!e.build&&!e.dockerComposeFile&&t.push({field:"image",message:'One of "image", "build", or "dockerComposeFile" is required'}),e.build&&(e.image&&r.push({field:"image",message:'Both "image" and "build" are set; "build" takes precedence'}),e.build.dockerfile||t.push({field:"build.dockerfile",message:'"build" requires a "dockerfile" path'})),e.dockerComposeFile&&!e.service&&t.push({field:"service",message:'"service" is required when using "dockerComposeFile"'}),e.features!==void 0&&(typeof e.features!="object"||Array.isArray(e.features))&&t.push({field:"features",message:'"features" must be an object mapping feature IDs to options'}),e.forwardPorts)if(Array.isArray(e.forwardPorts))for(const[o,i]of e.forwardPorts.entries())typeof i=="number"&&(i<1||i>65535)&&t.push({field:"forwardPorts",message:`Invalid port ${String(i)} at index ${String(o)}`});else t.push({field:"forwardPorts",message:'"forwardPorts" must be an array'});return e.customizations?.vscode?.extensions&&!Array.isArray(e.customizations.vscode.extensions)&&t.push({field:"customizations.vscode.extensions",message:"Extensions must be an array"}),e.customizations?.vscode?.settings&&typeof e.customizations.vscode.settings!="object"&&t.push({field:"customizations.vscode.settings",message:"Settings must be an object"}),e.name||n.push({field:"name",message:"Consider adding a name for better identification"}),(!e.features||Object.keys(e.features).length===0)&&n.push({field:"features",message:"Consider adding features for common tools"}),(!e.customizations?.vscode?.extensions||e.customizations.vscode.extensions.length===0)&&n.push({field:"extensions",message:"Consider adding VS Code extensions for your stack"}),e.privileged&&r.push({field:"privileged",message:"Running in privileged mode is a security risk"}),{errors:t,suggestions:n,valid:t.length===0,warnings:r}},"validateConfig");var zb=Object.defineProperty,Dd=b((e,t)=>zb(e,"name",{value:t,configurable:!0}),"$$c");const qa=80,Ja=15,qb=120,Ya=[{description:"Container name, base image, workspace folder, and user",id:"general",label:"General"},{description:"Installable tools and runtimes (Node, Python, Docker, etc.)",id:"features",label:"Features"},{description:"Ports to forward from the container to your host",id:"ports",label:"Ports"},{description:"Commands to run at different stages of the container lifecycle",id:"lifecycle",label:"Lifecycle"},{description:"VS Code extensions to auto-install in the container",id:"extensions",label:"Extensions"},{description:"Environment variables for the container and IDE",id:"environment",label:"Env"},{description:"Volume and bind mounts for persistent data and caches",id:"mounts",label:"Mounts"},{description:"Docker Compose integration for multi-container setups",id:"compose",label:"Compose"}],Jb=Dd((e,t,r,n)=>{switch(e){case"compose":return fb;case"environment":return hb(t);case"extensions":return As(n).length;case"features":return Rs(r).length;case"general":return Pd;case"lifecycle":return Nb;case"mounts":return(t.mounts?.length??0)+1;case"ports":return(t.forwardPorts?.length??0)+1;default:return 0}},"getFieldCount"),Yb=Dd(({onSave:e,store:t})=>{const{exit:r}=an(),{columns:n,rows:o}=sn(),i=Hn(t.subscribe,t.getSnapshot),[s,a]=we(!1),[c,d]=we(!1),[p,g]=we(!1),[h,y]=we(null),[w,k]=we("editor"),[$,x]=we(0),[T,I]=we(!1),[P,R]=we(""),[M,L]=we(null),[U,D]=we(""),[C,j]=we(""),[A,V]=we("key"),[N,F]=we(!1),[J,Y]=we(""),[ce,le]=we(""),[be,B]=we("volume"),[O,H]=we("source"),ye=Ue(null),Ee=Ue(null),Ae=Ue(null),Tt=Ue(!0);Pt(()=>(Tt.current=!0,()=>{Tt.current=!1,Ae.current&&clearTimeout(Ae.current)}),[]);const X=Jb(i.section,i.config,i.featureSearch,i.extensionSearch),te=Math.max(1,o-9);Pt(()=>{i.section!=="features"&&i.section!=="extensions"||x(G=>i.fieldIndex>=G+te?i.fieldIndex-te+1:i.fieldIndex<G?i.fieldIndex:G)},[i.fieldIndex,i.section,te]),Pt(()=>{x(0)},[i.section,i.featureSearch,i.extensionSearch]);const fe=Nt(()=>{const G=t.cleanConfig(),z=Hb(G);if(!z.valid){const ne=z.errors[0];y(ne?`Error: ${ne.message}`:"Validation failed"),Ae.current&&clearTimeout(Ae.current),Ae.current=setTimeout(()=>{Tt.current&&y(null)},3e3);return}e(G),t.markClean();const W=z.warnings.length;y(W>0?`Saved! (${String(W)} warning${W>1?"s":""})`:"Saved!"),Ae.current&&clearTimeout(Ae.current),Ae.current=setTimeout(()=>{Tt.current&&y(null)},2e3)},[e,t]);kt((G,z)=>{if(z.downArrow||G==="j")t.setTemplateIndex(i.templateIndex+1);else if(z.upArrow||G==="k")t.setTemplateIndex(i.templateIndex-1);else if(z.return){const W=nn[i.templateIndex];W&&t.applyTemplate(W.id)}else z.escape&&t.dismissTemplateSelector()},{isActive:i.showTemplateSelector}),kt((G,z)=>{if(z.escape){I(!1),R("");return}if(z.return){const W=Number.parseInt(P,10);!Number.isNaN(W)&&W>0&&W<=65535&&t.addPort(W),I(!1),R("");return}if(z.backspace){R(W=>W.slice(0,-1));return}G&&/^\d$/u.test(G)&&R(W=>W+G)},{isActive:T}),kt((G,z)=>{if(z.escape){L(null),D(""),j(""),V("key");return}if(z.return){if(A==="key"&&U){V("value");return}if(A==="value"&&U){t.addEnvVar(M,U,C),L(null),D(""),j(""),V("key");return}}if(z.backspace){A==="key"?D(W=>W.slice(0,-1)):j(W=>W.slice(0,-1));return}G&&!z.ctrl&&!z.meta&&(A==="key"?D(W=>W+G):j(W=>W+G))},{isActive:M!==null}),kt((G,z)=>{if(z.escape){F(!1),Y(""),le(""),H("source");return}if(z.return){if(O==="source"&&J){H("target");return}if(O==="target"&&ce){H("type");return}if(O==="type"){t.addMount({source:J,target:ce,type:be}),F(!1),Y(""),le(""),H("source");return}}if(O==="type"){switch(G){case"1":{B("volume");break}case"2":{B("bind");break}case"3":{B("tmpfs");break}}return}if(z.backspace){O==="source"?Y(W=>W.slice(0,-1)):O==="target"&&le(W=>W.slice(0,-1));return}G&&!z.ctrl&&!z.meta&&(O==="source"?Y(W=>W+G):O==="target"&&le(W=>W+G))},{isActive:N}),kt((G,z)=>{if(G==="c"&&z.ctrl){r();return}if(!c){if(s){z.escape||G==="?"?a(!1):z.downArrow||G==="j"?ye.current?.scrollBy(1):z.upArrow||G==="k"?ye.current?.scrollBy(-1):G==="q"&&(a(!1),d(!0));return}if(p){if(z.escape){g(!1),i.section==="features"?t.setFeatureSearch(""):t.setExtensionSearch("");return}if(z.return){g(!1);return}if(z.backspace){i.section==="features"?t.setFeatureSearch(i.featureSearch.slice(0,-1)):t.setExtensionSearch(i.extensionSearch.slice(0,-1));return}if(G&&!z.ctrl&&!z.meta){i.section==="features"?t.setFeatureSearch(i.featureSearch+G):t.setExtensionSearch(i.extensionSearch+G);return}return}if(i.fieldEditing){if(z.escape){t.setFieldEditing(!1);return}if(z.return){t.setFieldEditing(!1);return}return}if(G==="?"){a(!0);return}if(G==="q"){i.isDirty?d(!0):r();return}if(G==="s"){fe();return}if(z.tab){k(W=>W==="editor"?"preview":"editor");return}if(w==="preview"){if(z.downArrow||G==="j"){Ee.current?.scrollBy(1);return}if(z.upArrow||G==="k"){Ee.current?.scrollBy(-1);return}if(z.pageDown){Ee.current?.scrollBy(10);return}if(z.pageUp){Ee.current?.scrollBy(-10);return}if(z.home){Ee.current?.scrollToTop();return}if(z.end){Ee.current?.scrollToBottom();return}z.escape&&k("editor");return}if(z.downArrow||G==="j"){X>0&&t.setFieldIndex(Math.min(i.fieldIndex+1,X-1));return}if(z.upArrow||G==="k"){t.setFieldIndex(Math.max(i.fieldIndex-1,0));return}if(z.return){switch(i.section){case"compose":case"general":case"lifecycle":{t.setFieldEditing(!0);break}case"environment":{const W=Object.keys(i.config.containerEnv??{}).length,ne=W,he=W+1+Object.keys(i.config.remoteEnv??{}).length;i.fieldIndex===ne?(L("container"),D(""),j(""),V("key")):i.fieldIndex===he&&(L("remote"),D(""),j(""),V("key"));break}case"mounts":{const W=i.config.mounts??[];i.fieldIndex===W.length&&(F(!0),Y(""),le(""),B("volume"),H("source"));break}case"ports":{const W=i.config.forwardPorts??[];i.fieldIndex===W.length&&(I(!0),R(""));break}}return}if(G===" "){switch(i.section){case"extensions":{const W=As(i.extensionSearch)[i.fieldIndex];W&&t.toggleExtension(W.id);break}case"features":{const W=Rs(i.featureSearch)[i.fieldIndex];W&&t.toggleFeature(W.id);break}case"general":{const W=Pd-xi.length,ne=i.fieldIndex-W;if(ne>=0&&ne<xi.length){const he=xi[ne];t.updateConfig({[he]:!i.config[he]})}break}}return}if(G==="/"){(i.section==="features"||i.section==="extensions")&&g(!0);return}if(G==="A"&&i.section==="mounts"){t.applySuggestedMounts();return}if(G==="a"){if(i.section==="environment"){const W=Object.keys(i.config.containerEnv??{}).length,ne=i.fieldIndex<=W?"container":"remote";L(ne),D(""),j(""),V("key")}else i.section==="mounts"&&(F(!0),Y(""),le(""),B("volume"),H("source"));return}if(G==="d")switch(i.section){case"environment":{const W=Object.keys(i.config.containerEnv??{}),ne=Object.keys(i.config.remoteEnv??{});if(i.fieldIndex<W.length)t.removeEnvVar("container",W[i.fieldIndex]),W.length===1||i.fieldIndex>=W.length-1&&t.setFieldIndex(W.length-2);else{const he=i.fieldIndex-W.length-1;he>=0&&he<ne.length&&(t.removeEnvVar("remote",ne[he]),ne.length===1||he>=ne.length-1&&t.setFieldIndex(i.fieldIndex-1))}break}case"mounts":{const W=i.config.mounts??[];if(i.fieldIndex<W.length){t.removeMount(i.fieldIndex);const ne=W.length-1;i.fieldIndex>=ne&&ne>0&&t.setFieldIndex(ne-1)}break}case"ports":{const W=i.config.forwardPorts??[];if(i.fieldIndex<W.length){t.removePort(i.fieldIndex);const ne=W.length-1;i.fieldIndex>=ne&&ne>0&&t.setFieldIndex(ne-1)}break}}}},{isActive:!i.showTemplateSelector&&!T&&M===null&&!N});const zt=Dt(()=>t.getJsonPreview(),[i.config]);if(n<qa||o<Ja)return u(m,{alignItems:"center",height:o,justifyContent:"center",width:n,children:f(l,{color:"yellow",children:["Terminal too small (",n,"x",o,"), need"," ",qa,"x",Ja]})});if(i.showTemplateSelector)return u(m,{alignItems:"center",flexDirection:"column",height:o,justifyContent:"center",width:n,children:f(m,{borderColor:"cyan",borderStyle:"round",flexDirection:"column",paddingX:2,paddingY:1,width:60,children:[u(m,{justifyContent:"center",marginBottom:1,children:u(l,{bold:!0,color:"cyan",children:"Select a Template"})}),nn.map((G,z)=>{const W=z===i.templateIndex;return u(m,{children:f(l,{color:W?"cyan":void 0,inverse:W,children:[W?" ❯ ":" ",u(l,{bold:W,children:G.name}),f(l,{dimColor:!0,children:[" ","-",G.description]})]})},G.id)}),u(m,{justifyContent:"center",marginTop:1,children:f(l,{dimColor:!0,children:[u(l,{bold:!0,color:"white",children:"↑↓"})," ","navigate"," ",u(l,{bold:!0,color:"white",children:"Enter"})," ","select"," ",u(l,{bold:!0,color:"white",children:"Esc"})," ","blank"]})})]})});let K;switch(i.section){case"compose":{K=u(pb,{config:i.config,fieldEditing:i.fieldEditing,fieldIndex:i.fieldIndex,onUpdate:b(G=>{t.updateConfig(G)},"onUpdate")});break}case"environment":{K=f(m,{flexDirection:"column",children:[u(mb,{config:i.config,fieldIndex:i.fieldIndex}),M!==null&&u(m,{marginTop:1,paddingX:1,children:f(l,{color:"cyan",children:["Add"," ",M," ","env:"," ",A==="key"?f(l,{children:["key=",u(l,{color:"yellow",children:U||"_"})," ","(Enter to set value)"]}):f(l,{children:[U,"=",u(l,{color:"yellow",children:C||"_"})," ","(Enter to confirm, Esc to cancel)"]})]})})]});break}case"extensions":{K=u(wb,{config:i.config,fieldIndex:i.fieldIndex,scrollOffset:$,searchText:i.extensionSearch,viewportHeight:te});break}case"features":{K=u($b,{config:i.config,fieldIndex:i.fieldIndex,scrollOffset:$,searchText:i.featureSearch,viewportHeight:te});break}case"general":{K=u(Tb,{config:i.config,fieldEditing:i.fieldEditing,fieldIndex:i.fieldIndex,onUpdate:b(G=>{t.updateConfig(G)},"onUpdate")});break}case"lifecycle":{K=u(Pb,{config:i.config,fieldEditing:i.fieldEditing,fieldIndex:i.fieldIndex,onSetCommand:b((G,z)=>{t.setLifecycleCommand(G,z)},"onSetCommand")});break}case"mounts":{K=u(Db,{addingMount:N,config:i.config,detectedPm:i.detectedPm,fieldIndex:i.fieldIndex,mountPhase:O,mountSource:J,mountTarget:ce,mountType:be,suggestedMounts:i.suggestedMounts});break}case"ports":{K=u(Lb,{addingPort:T,addPortValue:P,config:i.config,fieldIndex:i.fieldIndex});break}default:K=u(l,{children:"Unknown section"})}const de=f(m,{borderBottom:!1,borderColor:"gray",borderLeft:!1,borderRight:!1,borderStyle:"single",flexShrink:0,children:[f(m,{flexGrow:1,flexWrap:"wrap",gap:2,paddingX:1,children:[f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"q"}),u(l,{dimColor:!0,children:"QUIT"})]}),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"?"}),u(l,{dimColor:!0,children:"HELP"})]}),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"↑↓"}),u(l,{dimColor:!0,children:"NAV"})]}),(i.section==="features"||i.section==="extensions")&&f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"Space"}),u(l,{dimColor:!0,children:"CHECK"})]}),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"←→"}),u(l,{dimColor:!0,children:"TABS"})]}),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"Tab"}),u(l,{dimColor:!0,children:"PANEL"})]}),(i.section==="features"||i.section==="extensions")&&f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"/"}),u(l,{dimColor:!0,children:"FILTER"})]}),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"s"}),u(l,{dimColor:!0,children:"SAVE"})]})]}),f(m,{paddingX:1,children:[h&&f(l,{color:h.startsWith("Error")?"red":"green",children:[h," "]}),i.isDirty&&u(l,{color:"yellow",children:"[modified]"}),!i.isDirty&&!h&&u(l,{dimColor:!0,children:"[saved]"})]})]}),pe=f(Ar,{footer:f(l,{dimColor:!0,children:[u(l,{bold:!0,color:"white",children:"↑↓"})," ","scroll"," ",u(l,{bold:!0,color:"white",children:"?"}),"/",u(l,{bold:!0,color:"white",children:"Esc"})," ","close"]}),scrollRef:ye,title:"KEYBOARD SHORTCUTS",visible:s,width:56,children:[f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"NAVIGATION"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"←→"}),u(l,{dimColor:!0,children:" Switch tabs"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"↑↓"}),"/",u(l,{bold:!0,color:"white",children:"j/k"}),u(l,{dimColor:!0,children:" Navigate within section"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"Tab"}),u(l,{dimColor:!0,children:" Switch editor/preview panel"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"Enter"}),u(l,{dimColor:!0,children:" Edit selected field"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"Esc"}),u(l,{dimColor:!0,children:" Stop editing / cancel"})]})]}),f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"FEATURES / EXTENSIONS"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"Space"}),u(l,{dimColor:!0,children:" Toggle selection"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"/"}),u(l,{dimColor:!0,children:" Search / filter"})]})]}),f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"LISTS (Ports, Mounts, Env)"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"a"}),u(l,{dimColor:!0,children:" Add new entry"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"d"}),u(l,{dimColor:!0,children:" Delete selected entry"})]})]}),f(m,{flexDirection:"column",children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"ACTIONS"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"s"}),u(l,{dimColor:!0,children:" Save configuration"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"q"}),u(l,{dimColor:!0,children:" Quit"})]}),f(l,{children:[" ",u(l,{bold:!0,color:"white",children:"?"}),u(l,{dimColor:!0,children:" Toggle help"})]})]})]}),Me=u(Ub,{focused:w==="preview",hadComments:i.hadComments,jsonPreview:zt,mode:i.mode,scrollRef:Ee}),Ie=n>=qb,vt=Ie?Math.floor(n*.38):0;return f(m,{flexDirection:"column",height:o,width:n,children:[f(m,{flexShrink:0,gap:1,paddingX:1,children:[u(l,{bold:!0,inverse:!0,children:" VIS "}),f(l,{wrap:"truncate",children:[i.mode==="create"?"Create":"Edit"," ","devcontainer"]})]}),u(m,{flexShrink:0,paddingX:1,paddingY:1,children:u(il,{defaultValue:i.section,keyMap:{useNumbers:!1,useTab:!1},onChange:b(G=>{t.setSection(G),k("editor")},"onChange"),showIndex:!1,children:Ya.map(({id:G,label:z})=>u(sl,{name:G,children:z},G))})}),u(m,{flexShrink:0,paddingRight:2,children:u(l,{dimColor:!0,wrap:"truncate",children:Ya.find(G=>G.id===i.section)?.description??""})}),f(m,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[u(m,{borderColor:w==="editor"?"white":"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,overflow:"hidden",children:K}),Ie&&u(m,{flexShrink:0,width:vt,children:Me})]}),de,u(Nr,{autoExitSeconds:3,onCancel:b(()=>{d(!1)},"onCancel"),visible:c}),pe]})},"VisDevcontainerApp");var Kb=Object.defineProperty,Ka=b((e,t)=>Kb(e,"name",{value:t,configurable:!0}),"c$q");const Xb={alias:"dc",description:"Create or update .devcontainer/devcontainer.json interactively",examples:[["vis devcontainer","Launch interactive devcontainer config editor"],["vis dc","Alias for devcontainer"],["vis devcontainer --template node-pnpm","Start from Node.js + pnpm template"]],execute:Ka(async({logger:e,options:t,workspaceRoot:r})=>{if(!r)throw new Error("Could not determine workspace root. Run this command inside a monorepo or project directory.");const n=r,o=t.template,i=t.output,s=!!process.stdout.isTTY&&!ft;let a=null;try{a=Ne(n).name}catch{}const c=Zk(n);let d=c?.config??null;const p=c?.hadComments??!1;if(o&&!c){const w=nn.find(k=>k.id===o);if(!w){const k=nn.map($=>$.id).join(", ");throw new Error(`Unknown template "${o}". Valid templates: ${k}`)}d=w.config}if(!s){d?e.info(JSON.stringify(d,null,2)):(e.error("No existing devcontainer.json found. Use --template to generate one in non-TTY mode."),process.exitCode=1);return}process.stdin.isTTY&&typeof process.stdin.setRawMode=="function"&&(process.stdin.setRawMode(!0),process.stdin.ref(),process.stdin.resume());const g=setInterval(()=>{},1e3),h=new sb(d,p,a);o&&!c&&h.dismissTemplateSelector();let y=null;if(await Xt(Q.createElement(Yb,{onSave:Ka(w=>{eb(n,w,i),y=w},"onSave"),store:h}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit(),clearInterval(g),y){const w=i??".devcontainer/devcontainer.json";e.info(`DevContainer config saved to ${w}`)}},"execute"),group:"Scaffold & Config",name:"devcontainer",options:[{alias:"t",description:"Start from a template: node, node-pnpm, node-postgres, node-dind, fullstack, python, go, rust, java, devops, minimal, custom",name:"template",type:String},{alias:"o",description:"Output path (default: .devcontainer/devcontainer.json)",name:"output",type:String}]};var Qb=Object.defineProperty,Zb=b((e,t)=>Qb(e,"name",{value:t,configurable:!0}),"o$f");const e$={argument:{description:"Package to execute (optionally with @version)",name:"package",type:String},description:"Execute a remote package without permanent installation",examples:[["vis dlx create-vite my-app","Scaffold a new project"],["vis dlx typescript@5.5.4 tsc --version","Run specific version"],["vis dlx -p cowsay -p lolcatjs -c 'echo hi | cowsay | lolcatjs'","Multiple packages with shell"]],execute:Zb(async({argument:e,logger:t,options:r,workspaceRoot:n})=>{const o=e;if(!o||o.length===0)throw new Error("No package specified. Usage: vis dlx <package[@version]> [args...]");const[i,...s]=o,a=n??process.cwd(),c=Ne(a),d=r.package?Array.isArray(r.package)?r.package:[r.package]:[],p=us(c,{additionalPackages:d,args:s,package:i,shellMode:r.shellMode||!1,silent:r.silent||!1},a,t);p!==0&&(process.exitCode=p)},"execute"),group:"Run & Execute",name:"dlx",options:[{alias:"p",description:"Additional packages to install (repeatable)",multiple:!0,name:"package",type:String},{alias:"c",defaultValue:!1,description:"Execute within shell environment",name:"shell-mode",type:Boolean},{alias:"s",defaultValue:!1,description:"Suppress output except command results",name:"silent",type:Boolean}]};var t$=Object.defineProperty,_r=b((e,t)=>t$(e,"name",{value:t,configurable:!0}),"f$j");const r$=_r((e,t)=>{const r=new Set,n=[e],o=new Set([e]);for(;n.length>0;){const i=n.shift(),s=t.dependencies[i]??[];for(const a of s)o.has(a.target)||(o.add(a.target),r.add(a.target),n.push(a.target))}return r},"collectTransitiveProjectDeps"),ko="vis-docker-manifest.json",n$=["package.json","project.json"],o$=["package.json","pnpm-workspace.yaml","pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","bun.lockb",".npmrc","vis.config.ts","vis.config.mts","vis.config.cts","vis.config.js","vis.config.mjs","vis.config.cjs"],Bd=_r((e,t)=>{const r=new Set(e);for(const n of e){const o=r$(n,t);for(const i of o)r.add(i)}return r},"resolveFocusProjects"),Ln=_r(e=>{Se(e)},"ensureDir"),Xa=_r((e,t)=>{try{return Ln(Lt(t)),rs(e,t),!0}catch(r){if(r.code==="ENOENT")return!1;throw r}},"copyFileIfExists"),Fd=_r((e,t)=>{let r;try{r=tl(e)}catch{return}if(!r.isSymbolicLink()){if(r.isFile()){Ln(Lt(t)),rs(e,t);return}Ln(t);for(const n of Ve(e,{withFileTypes:!0}))n.name==="node_modules"||n.name===".git"||n.isSymbolicLink()||Fd(v(e,n.name),v(t,n.name))}},"copyTreeExcludingNodeModules"),i$=_r(e=>{const{focus:t,includeSources:r=!1,outDir:n,projectGraph:o,workspace:i,workspaceRoot:s}=e,a=t.filter(g=>i.projects[g]===void 0);if(a.length>0)throw new Error(`Unknown focus project(s): ${a.join(", ")}. Check project names in your workspace.`);const c=Bd(t,o),d=v(n,"workspace"),p=v(n,"sources");at(d,{force:!0,recursive:!0}),at(p,{force:!0,recursive:!0}),Ln(d);for(const g of o$)Xa(v(s,g),v(d,g));for(const g of c){const h=i.projects[g];if(h?.root)for(const y of n$)Xa(v(s,h.root,y),v(d,h.root,y))}if(r){Ln(p);for(const g of t){const h=i.projects[g];h?.root&&Fd(v(s,h.root),v(p,h.root))}}return Z(v(n,ko),`${JSON.stringify({focus:t,projects:[...c].sort()},null,2)}
322
- `),{projects:[...c]}},"scaffoldDockerContext"),s$=_r(e=>{const{contextRoot:t,workspace:r,workspaceRoot:n}=e,o=v(t,ko);if(!E(o))throw new Error(`No ${ko} at ${t}. Run \`vis docker scaffold\` first.`);const i=ue(o);if(!Array.isArray(i.projects))throw new TypeError(`Invalid ${ko}: "projects" must be an array.`);const s=new Set(i.projects),a=[];for(const[c,d]of Object.entries(r.projects)){if(s.has(c)||!d.root)continue;const p=v(n,d.root),g=He(n,p);g===""||g==="."||g.startsWith("..")||(at(p,{force:!0,recursive:!0}),a.push(g))}return{removed:a}},"pruneDockerContext");var a$=Object.defineProperty,c$=b((e,t)=>a$(e,"name",{value:t,configurable:!0}),"p$u");const l$={argument:{description:"Docker subcommand: scaffold | prune",name:"subcommand",type:String},description:"Docker integration — scaffold a minimal context or prune unfocused deps",examples:[["vis docker scaffold --focus=my-app","Generate .vis/docker/workspace for my-app + its deps"],["vis docker scaffold --focus=my-app --include-sources","Also copy focus source trees"],["vis docker scaffold --focus=my-app,other --out=.vis/docker","Focus multiple projects"],["vis docker prune --context=.vis/docker","Strip unfocused projects inside a build stage"]],execute:c$(async({argument:e,logger:t,options:r,visConfig:n,workspaceRoot:o})=>{const i=e[0];if(!i)throw new Error("Missing subcommand. Usage: vis docker <scaffold|prune>");if(!o)throw new Error("Could not determine workspace root. Run inside a monorepo.");const{packageJsons:s,workspace:a}=mt(o,n);if(i==="scaffold"){const c=nr(o,a,s),d=r.focus;if(!d)throw new Error("Missing --focus. Pass one or more project names, comma-separated.");const p=d.split(",").map(y=>y.trim()).filter(Boolean);if(p.length===0)throw new Error("--focus resolved to an empty list. Provide at least one project name.");const g=v(o,r.out??".vis/docker"),{projects:h}=i$({focus:p,includeSources:!!r.includeSources,outDir:g,projectGraph:c,workspace:a,workspaceRoot:o});t.info(`Scaffolded ${h.length} project(s) into ${g}`),t.info(`Focus closure: ${h.sort().join(", ")}`);return}if(i==="prune"){const c=v(o,r.context??".vis/docker"),{removed:d}=s$({contextRoot:c,workspace:a,workspaceRoot:o});t.info(`Pruned ${d.length} unfocused project(s)`),d.length>0&&t.debug?.(d.join(`
323
- `));return}throw new Error(`Unknown subcommand: "${i}". Expected scaffold or prune.`)},"execute"),group:"Workspace",name:"docker",options:[{description:"Project name(s) to focus on — comma-separated for multiple",name:"focus",type:String},{description:"Output directory for the scaffold (default: .vis/docker)",name:"out",type:String},{defaultValue:!1,description:"Also copy focus project source trees to <out>/sources",name:"include-sources",type:Boolean},{description:"Scaffold root for `vis docker prune` (default: .vis/docker)",name:"context",type:String}]};var d$=Object.defineProperty,jt=b((e,t)=>d$(e,"name",{value:t,configurable:!0}),"c$p");const u$=["dependencies","devDependencies","peerDependencies","peerDependenciesMeta","optionalDependencies","bundleDependencies"],p$=["overrides","pnpm","resolutions"],f$=["engines","files"],g$=jt(e=>{const t=Wn(e)?.major;return t!==void 0&&t>=10},"isPnpmV10Plus"),m$=jt(e=>{const t=v(e,"pnpm-workspace.yaml");if(!E(t))return{overrides:{},source:"pnpm-workspace.yaml"};try{return{overrides:ln(t)?.overrides??{},source:"pnpm-workspace.yaml"}}catch{return{overrides:{},source:"pnpm-workspace.yaml"}}},"readPnpmWorkspaceOverrides"),h$=jt((e,t)=>{let r={};return t==="pnpm"?r=e.pnpm?.overrides??{}:t==="yarn"||t==="bun"?r=e.resolutions??{}:r=e.overrides??{},{overrides:r,source:"package.json"}},"readPkgJsonOverrides"),y$=jt((e,t,r)=>r.name==="pnpm"&&g$(r.version)?m$(e):h$(t,r.name),"readOverrides"),Qa=jt((e,t)=>{const r=t;for(const o of p$){const i=e.indexOf(o);if(i!==-1&&o!==r)return r==="overrides"?i:i+1}let n=-1;for(const o of u$){const i=e.indexOf(o);i>n&&(n=i)}if(n!==-1)return n+1;for(const o of f$){const i=e.indexOf(o);if(i!==-1)return i}return e.length},"findInsertIndex"),v$=jt(e=>/\n(\s+)/.exec(e)?.[1]??" ","detectIndent"),w$=jt((e,t)=>{const r=v(e,"pnpm-workspace.yaml");if(!E(r))throw new Error(`pnpm-workspace.yaml not found at ${r}. Cannot write overrides for pnpm v10+.`);let n=q(r);const o=`overrides:
324
- ${Object.entries(t).map(([i,s])=>` '${i}': '${s}'`).join(`
325
- `)}
326
- `;n=/^overrides:\s*$/m.test(n)||/^overrides:\s*\n/m.test(n)?n.replace(/^overrides:\s*\n(?:(?:[ \t].*)?\n)*/m,o):`${n.trimEnd()}
327
-
328
- ${o}`,Z(r,n)},"writePnpmWorkspaceOverrides"),k$=jt((e,t,r,n)=>{const o=q(e),i=v$(o);if(n==="pnpm"){const s=t.pnpm??{};if(s.overrides=r,t.pnpm)t.pnpm=s,Z(e,`${JSON.stringify(t,null,i)}
329
- `);else{const a=Object.keys(t),c=Qa(a,"pnpm"),d=Object.entries(t);d.splice(c,0,["pnpm",s]),Z(e,`${JSON.stringify(Object.fromEntries(d),null,i)}
330
- `)}}else{const s=n==="yarn"||n==="bun"?"resolutions":"overrides";if(t[s])t[s]=r,Z(e,`${JSON.stringify(t,null,i)}
331
- `);else{const a=Object.keys(t),c=Qa(a,s),d=Object.entries(t);d.splice(c,0,[s,r]),Z(e,`${JSON.stringify(Object.fromEntries(d),null,i)}
332
- `)}}},"writePkgJsonOverrides"),Ld=jt((e,t,r,n)=>{const o=q(t),i=JSON.parse(o),{overrides:s,source:a}=y$(e,i,n),c=[],d=[],p=new Set;if(n.name==="npm")for(const h of["dependencies","devDependencies"]){const y=i[h];if(y)for(const w of Object.keys(y))p.add(w)}for(const h of r){const y=s[h.original];if(typeof y=="object")continue;let w=h.spec;n.name==="npm"&&p.has(h.original)&&(w=`$${h.original}`),y!==w&&(y?d.push(h.original):c.push(h.original),s[h.original]=w)}if(c.length===0&&d.length===0)return{added:c,updated:d};const g=Object.fromEntries(Object.entries(s).sort(([h],[y])=>h.localeCompare(y)));return a==="pnpm-workspace.yaml"?w$(e,g):k$(t,i,g,n.name),{added:c,updated:d}},"applyOverrides"),Vd=jt((e,t)=>{const r={bun:["bun.lock"],npm:["npm-shrinkwrap.json","package-lock.json"],pnpm:["pnpm-lock.yaml"],yarn:["yarn.lock"]};for(const n of r[t]??[]){const o=v(e,n);try{return q(o)}catch{continue}}return""},"readLockfileText"),b$=jt((e,t,r)=>{if(!e)return!1;const n=t.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);switch(r){case"bun":return e.includes(`"${t}":`)||new RegExp(String.raw`(^|\s|[",])${n}@`,"m").test(e);case"npm":return e.includes(`"${t}":`)||e.includes(`"node_modules/${t}":`);case"pnpm":return new RegExp(String.raw`(^|\s|['"/])${n}(@|['"]?:)`,"m").test(e);case"yarn":return new RegExp(String.raw`(^|\s|[",])${n}@`,"m").test(e);default:return!1}},"lockfileContainsPackage");var $$=Object.defineProperty,ei=b((e,t)=>$$(e,"name",{value:t,configurable:!0}),"p$t");const x$=ei(e=>{for(const t of[".nvmrc",".node-version"]){const r=v(e,t);if(E(r))try{return q(r).trim().replace(/^v/,"")}catch{}}},"readNodeVersionFile"),go=ei((e,t)=>{const r=e.split(/[.\-+]/).map(i=>Number.parseInt(i,10)||0),n=t.split(/[.\-+]/).map(i=>Number.parseInt(i,10)||0),o=Math.max(r.length,n.length);for(let i=0;i<o;i++){const s=r[i]??0,a=n[i]??0;if(s!==a)return s-a}return 0},"compareVersions"),S$=ei((e,t)=>{const r=t.trim();if(r===""||r==="*")return!0;const n=r.split(/\s+/).filter(Boolean);for(const o of n)if(o.startsWith(">=")){if(go(e,o.slice(2).trim())<0)return!1}else if(o.startsWith("<=")){if(go(e,o.slice(2).trim())>0)return!1}else if(o.startsWith(">")){if(go(e,o.slice(1).trim())<=0)return!1}else if(o.startsWith("<")){if(go(e,o.slice(1).trim())>=0)return!1}else if(/^\d/.test(o)){const i=e.split("."),s=o.split(".");for(const[a,c]of s.entries())if(c!==i[a])return!1}return!0},"satisfiesRange"),_d=ei(e=>{const t=[],r=v(e,"package.json");let n={};try{n=ue(r)}catch{return t}const o=process.versions.node;if(n.engines?.node){const s=n.engines.node;S$(o,s)||t.push({actual:o,expected:s,kind:"node",message:`package.json engines.node requires ${s}, but the current Node.js is ${o}.`,severity:"error"})}const i=x$(e);if(i){const[s,a]=i.split("."),[c,d]=o.split(".");(s!==c||a!==void 0&&a!==d)&&t.push({actual:o,expected:i,kind:"node",message:`.nvmrc pins Node ${i} but the current Node.js is ${o}. Run \`nvm use\` or switch runtimes.`,severity:"warning"})}if(n.packageManager){const[s,a]=n.packageManager.split("@"),c=(process.env.npm_config_user_agent??"").split(" ")[0]??"",[d,p]=c.split("/");d&&s&&d!==s?t.push({actual:d,expected:s,kind:"packageManager",message:`package.json packageManager pins ${n.packageManager} but the current invocation is ${c}. Install the correct package manager.`,severity:"error"}):p&&a&&p!==a&&t.push({actual:p,expected:a,kind:"packageManager",message:`package.json packageManager pins ${s}@${a} but the current invocation uses ${s}@${p}.`,severity:"warning"})}return t},"checkRuntimeVersions");var C$=Object.defineProperty,Cn=b((e,t)=>C$(e,"name",{value:t,configurable:!0}),"s$h");const j$=Cn((e,t,r)=>{let n=e;if(t!=="all"&&(n=n.filter(o=>o.category===t)),r){const o=r.toLowerCase();n=n.filter(i=>i.packageName.toLowerCase().includes(o))}return n},"filterEntries");let E$=class{static{b(this,"c")}static{Cn(this,"OptimizeStore")}#e;#t=new Set;constructor(t){this.#e={applyProgress:null,checkedEntries:new Set,entries:t,error:null,filterActive:!1,filterText:"",filterType:"all",focusedPanel:"list",phase:"browsing",selectedIndex:0}}getSnapshot=Cn(()=>this.#e,"getSnapshot");subscribe=Cn(t=>(this.#t.add(t),()=>{this.#t.delete(t)}),"subscribe");getFilteredEntries=Cn(()=>j$(this.#e.entries,this.#e.filterType,this.#e.filterText),"getFilteredEntries");#n(){this.#e={...this.#e};for(const t of this.#t)t()}select(t){const r=this.getFilteredEntries();this.#e.selectedIndex=r.length===0?-1:Math.max(0,Math.min(t,r.length-1)),this.#n()}toggleCheck(t){const r=new Set(this.#e.checkedEntries);r.has(t)?r.delete(t):r.add(t),this.#e.checkedEntries=r,this.#n()}toggleAll(){const t=this.getFilteredEntries(),r=new Set(this.#e.checkedEntries);if(t.every(n=>r.has(n.packageName)))for(const n of t)r.delete(n.packageName);else for(const n of t)r.add(n.packageName);this.#e.checkedEntries=r,this.#n()}setFilter(t){this.#e.filterType=t,this.#e.selectedIndex=0,this.#n()}setFilterText(t){this.#e.filterText=t,this.#e.selectedIndex=0,this.#n()}setFilterActive(t){this.#e.filterActive=t,this.#n()}setFocusedPanel(t){this.#e.focusedPanel=t,this.#n()}setPhase(t){this.#e.phase=t,this.#n()}setProgress(t,r){this.#e.applyProgress={current:t,total:r},this.#n()}setError(t){this.#e.error=t,this.#e.phase="error",this.#n()}getCheckedEntries(){return this.#e.entries.filter(t=>this.#e.checkedEntries.has(t.packageName))}};const Ud={"micro-utility":"gray",native:"green",preferred:"yellow",socket:"cyan"},T$={"micro-utility":"MICRO",native:"NATIVE",preferred:"PREF",socket:"SOCKET"},R$={"micro-utility":"Trivial utility package that can be replaced with inline code.",native:"Polyfill for a native JS/Node.js API. Use the built-in instead.",preferred:"A lighter or faster alternative package exists.",socket:"Security-hardened replacement from Socket.dev's @socketregistry."};var A$=Object.defineProperty,I$=b((e,t)=>A$(e,"name",{value:t,configurable:!0}),"a$h");const O$=I$(({entry:e,focused:t,scrollRef:r})=>{const n=t?"white":"gray";if(!e)return u(m,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:u(l,{dimColor:!0,children:"No entry selected"})});const o=Ud[e.category]??"gray";return f(m,{borderColor:n,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[u(m,{flexShrink:0,paddingTop:1,paddingX:2,children:u(l,{bold:!0,color:"white",children:e.packageName})}),f(cn,{flexGrow:1,flexShrink:1,paddingX:2,ref:r,scrollbar:!0,scrollbarColor:"gray",children:[u(l,{}),f(m,{children:[u(m,{width:14,children:u(l,{dimColor:!0,children:"Category:"})}),u(l,{bold:!0,color:o,children:e.category})]}),f(m,{children:[u(m,{width:14,children:u(l,{dimColor:!0,children:"Replace with:"})}),u(l,{children:e.replacement})]}),e.overrideSpec&&f(m,{children:[u(m,{width:14,children:u(l,{dimColor:!0,children:"Override:"})}),u(l,{color:"cyan",children:e.overrideSpec})]}),f(m,{children:[u(m,{width:14,children:u(l,{dimColor:!0,children:"Codemod:"})}),u(l,{color:e.hasCodemod?"green":"gray",children:e.hasCodemod?"available ⚙":"not available"})]}),f(m,{flexDirection:"column",marginTop:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"DESCRIPTION"}),u(m,{marginTop:1,paddingLeft:2,children:u(l,{children:R$[e.category]??""})})]}),e.category==="native"&&f(m,{flexDirection:"column",marginTop:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"green",children:"ACTION"}),u(m,{flexDirection:"column",marginTop:1,paddingLeft:2,children:e.hasCodemod?f(En,{children:[f(l,{color:"green",children:["✓"," ","Codemod will rewrite imports to use native API."]}),u(l,{dimColor:!0,children:" The package can then be removed from dependencies."})]}):f(En,{children:[f(l,{color:"yellow",children:["ℹ"," ","No automated codemod available."]}),u(l,{dimColor:!0,children:" Manual migration required — replace usage with native equivalent."})]})})]}),e.category==="socket"&&f(m,{flexDirection:"column",marginTop:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"cyan",children:"ACTION"}),f(m,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[f(l,{color:"cyan",children:["✓"," ","Override will redirect resolution to the hardened package."]}),u(l,{dimColor:!0,children:" No source code changes needed — drop-in replacement."})]})]}),f(m,{flexDirection:"column",marginTop:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"LINKS"}),u(m,{flexDirection:"column",marginTop:1,paddingLeft:2,children:f(l,{color:"cyan",underline:!0,children:["https://npmx.dev/",e.packageName]})})]})]})]})},"OptimizeDetailPanel");var P$=Object.defineProperty,Wd=b((e,t)=>P$(e,"name",{value:t,configurable:!0}),"b$c");const N$=[{key:"all",label:"All",shortcut:"1"},{key:"native",label:"Native",shortcut:"2"},{key:"preferred",label:"Preferred",shortcut:"3"},{key:"micro-utility",label:"Micro",shortcut:"4"},{key:"socket",label:"Socket",shortcut:"5"}],M$=Wd(({checked:e,entry:t,isSelected:r})=>{const n=Ud[t.category]??"white",o=T$[t.category]??t.category,i=e?"☑":"☐",s=t.hasCodemod?"⚙":" ";return f(m,{flexShrink:0,height:1,children:[u(l,{children:r?">":" "}),f(l,{color:e?"white":"gray",children:[" ",i," "]}),u(l,{bold:!0,color:n,children:`[${o}]`.padEnd(9)}),f(l,{children:[" ",s," "]}),u(m,{flexGrow:1,children:u(l,{bold:r,inverse:r,wrap:"truncate",children:t.packageName})}),u(l,{dimColor:!0,children:" → "}),u(l,{wrap:"truncate",children:t.replacement})]})},"EntryRow"),D$=Wd(({checkedEntries:e,entries:t,filterActive:r,filterText:n,filterType:o,focused:i,isDryRun:s,scrollOffset:a,selectedIndex:c,totalEntries:d,viewportHeight:p})=>{const g=i?"white":"gray";let h=0,y=0,w=0,k=0;for(const M of t)switch(M.category){case"micro-utility":{w++;break}case"native":{h++;break}case"preferred":{y++;break}case"socket":{k++;break}}const $=[];h>0&&$.push(`${h} native`),y>0&&$.push(`${y} preferred`),w>0&&$.push(`${w} micro`),k>0&&$.push(`${k} socket`);const x=$.length>0?` (${$.join(", ")})`:"",T=e.size,I=[];for(const[M,L]of t.entries())I.push(u(M$,{checked:e.has(L.packageName),entry:L,isSelected:M===c},L.packageName));const P=t.length,R=P>p&&p>0;return f(m,{borderColor:g,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[f(m,{flexShrink:0,gap:1,paddingX:1,children:[u(l,{bold:!0,inverse:!0,children:" VIS OPTIMIZE "}),f(l,{wrap:"truncate",children:[d," ","optimizations",x]}),!s&&T>0&&f(l,{dimColor:!0,children:[" ","—",T," ","selected"]})]}),u(m,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:N$.map(M=>{const L=o===M.key;return f(m,{children:[u(l,{dimColor:!L,children:"["}),u(l,{bold:L,color:L?"cyan":"gray",children:M.shortcut}),u(l,{dimColor:!L,children:"]"}),f(l,{color:L?"white":"gray",children:[" ",M.label]})]},M.key)})}),r&&f(m,{flexShrink:0,paddingX:1,children:[u(l,{bold:!0,color:"white",children:"/ "}),u(l,{children:n}),u(l,{inverse:!0,children:" "})]}),f(m,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[u(m,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:u(m,{flexDirection:"column",marginTop:-a,children:I})}),R&&u(m,{flexShrink:0,marginLeft:1,marginRight:1,children:u(Gn,{contentHeight:P,placement:"inset",scrollOffset:a,style:"block",viewportHeight:p})})]})]})},"OptimizeListPanel");var B$=Object.defineProperty,F$=b((e,t)=>B$(e,"name",{value:t,configurable:!0}),"S$b");const L$=100,Za=10,ec={1:"all",2:"native",3:"preferred",4:"micro-utility",5:"socket"},V$=F$(({isDryRun:e,store:t})=>{const{exit:r}=an(),{columns:n,rows:o}=sn(),i=Hn(t.subscribe,t.getSnapshot),s=Ue(null),[a,c]=we(0),[d,p]=we(!1),g=t.getFilteredEntries(),h=g[i.selectedIndex]??null,y=n>=L$,w=Math.max(0,o-5),k=Nt($=>{r($)},[r]);return kt(($,x)=>{if(d){$==="y"||$==="Y"?k():p(!1);return}if(i.filterActive){x.escape?(t.setFilterActive(!1),t.setFilterText("")):x.return?t.setFilterActive(!1):x.backspace||x.delete?t.setFilterText(i.filterText.slice(0,-1)):$&&!x.ctrl&&!x.meta&&t.setFilterText(i.filterText+$);return}if($==="q"){!e&&i.checkedEntries.size>0?p(!0):k();return}if($==="/"){t.setFilterActive(!0);return}if(ec[$]){t.setFilter(ec[$]);return}if(x.tab){t.setFocusedPanel(i.focusedPanel==="list"?"detail":"list");return}if(i.focusedPanel==="list")if(x.upArrow||$==="k"){const T=Math.max(0,i.selectedIndex-1);t.select(T),T<a&&c(T)}else if(x.downArrow||$==="j"){const T=Math.min(g.length-1,i.selectedIndex+1);t.select(T),T>=a+w&&c(T-w+1)}else $===" "?h&&t.toggleCheck(h.packageName):$==="a"?t.toggleAll():x.return&&!e&&i.checkedEntries.size>0&&k(t.getCheckedEntries());else i.focusedPanel==="detail"&&(x.upArrow||$==="k"?s.current?.scrollBy(-1):(x.downArrow||$==="j")&&s.current?.scrollBy(1))},{isActive:i.phase==="browsing"}),o<Za?u(m,{alignItems:"center",justifyContent:"center",children:f(l,{color:"yellow",children:["Terminal too small. Resize to at least",Za," ","rows."]})}):f(m,{flexDirection:"column",height:o,width:n,children:[f(m,{flexDirection:y?"row":"column",flexGrow:1,children:[u(m,{flexBasis:y?"50%":void 0,flexGrow:1,children:u(D$,{checkedEntries:i.checkedEntries,entries:g,filterActive:i.filterActive,filterText:i.filterText,filterType:i.filterType,focused:i.focusedPanel==="list",isDryRun:e,scrollOffset:a,selectedIndex:i.selectedIndex,totalEntries:i.entries.length,viewportHeight:w})}),u(m,{flexBasis:y?"50%":void 0,flexGrow:1,children:u(O$,{entry:h,focused:i.focusedPanel==="detail",scrollRef:s})})]}),u(m,{flexShrink:0,paddingX:1,children:f(l,{dimColor:!0,children:[e?"Preview mode":"space:toggle a:all enter:apply"," ","| tab:switch panel /: filter q:quit |","⚙","=codemod available"]})}),u(Nr,{autoExitSeconds:3,onCancel:b(()=>{p(!1)},"onCancel"),visible:d})]})},"VisOptimizeApp");var _$=Object.defineProperty,Bt=b((e,t)=>_$(e,"name",{value:t,configurable:!0}),"f$h");const Ao=Bt((e,t)=>{const r=new Set;try{const n=ue(e),o=t?[n.dependencies,n.optionalDependencies]:[n.dependencies,n.devDependencies,n.peerDependencies,n.optionalDependencies];for(const i of o)if(i)for(const s of Object.keys(i))r.add(s)}catch{}return r},"collectDepsFromPkgJson"),Is=Bt(e=>{const t=Wo(e);if(t)return Or(e,t);const r=v(e,"package.json");if(!E(r))return[];try{const n=ue(r),o=Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages;return o?Or(e,o):[]}catch{return[]}},"discoverWorkspacePackages"),Gd=Bt(e=>{const t=[],r=Bt((n,o)=>{for(const[,i]of Object.entries(n.mappings)){if(!e.has(i.moduleName))continue;const s=[];for(const a of i.replacements){const c=n.replacements[a];c&&s.push(c.description??c.id)}t.push({category:o,hasCodemod:!1,overrideSpec:void 0,packageName:i.moduleName,replacement:s.join(", ")||i.replacements.join(", ")})}},"scanManifest");return r(qp,"native"),r(Jp,"preferred"),r(zp,"micro-utility"),t},"buildE18eEntries"),Hd=Bt((e,t,r,n)=>{const o=Hp("npm")??[],i=[];for(const[,s]of o){if(s.deprecated)continue;const a=e.has(s.package),c=t?b$(t,s.package,r.name):!1;if(!a&&!c)continue;const d=Wn(s.version)?.major;if(d===void 0)continue;const p=n?`npm:${s.name}@${s.version}`:`npm:${s.name}@^${String(d)}`;i.push({category:"socket",hasCodemod:!1,overrideSpec:p,packageName:s.package,replacement:s.name})}return i},"buildSocketEntries");let mo;const zd=Bt(async()=>{if(mo)return mo;try{return mo=(await import("module-replacements-codemods")).codemods,mo}catch{return{}}},"loadCodemods"),qd=Bt(async e=>{try{const t=await zd();for(const r of e)r.category!=="socket"&&t[r.packageName]&&(r.hasCodemod=!0)}catch{}},"markCodemodAvailability"),Jd=Bt(async(e,t)=>{let r=0;try{const n=(await zd())[t];if(!n)return{filesChanged:0,packageName:t};const o=n({}),i=await U$(e);for(const s of i){const a=q(s);if(a.includes(t))try{const c=await o.transform({file:{filename:s,source:a}});c!==a&&(me(s,c,"utf8"),r++)}catch(c){process.stderr.write(`warn: codemod transform failed for ${s}: ${c instanceof Error?c.message:String(c)}
333
- `)}}}catch{}return{filesChanged:r,packageName:t}},"runCodemod"),U$=Bt(async e=>dp("**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}",{absolute:!0,cwd:e,ignore:["**/.*/**","**/.*","**/node_modules/**","**/dist/**","**/coverage/**","**/.git/**","**/.next/**","**/.nuxt/**"]}),"collectSourceFiles"),W$={description:"Analyze and optimize dependencies using e18e replacements and @socketregistry overrides",examples:[["vis optimize","Interactive TUI to select and apply optimizations"],["vis optimize --dry-run","Preview available optimizations"],["vis optimize --pin","Pin Socket.dev overrides to exact versions"],["vis optimize --prod","Only optimize production dependencies"]],execute:Bt(async({logger:e,options:t,workspaceRoot:r})=>{if(!r)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const n=Ne(r),o=!!t.dryRun,i=!!t.prod,s=!!t.pin;S(`Detected ${n.name} v${n.version}.`);const a=Ao(v(r,"package.json"),i),c=Is(r),d=new Set(a);for(const R of c){const M=Ao(v(xe(r,R),"package.json"),i);for(const L of M)d.add(L)}c.length>0&&S(`Scanned ${String(c.length)} workspace package${c.length===1?"":"s"}.`),S(`Scanning dependencies...
334
- `);const p=Vd(r,n.name),g=Gd(d),h=Hd(d,p,n,s),y=new Set(g.map(R=>R.packageName)),w=h.filter(R=>!y.has(R.packageName)),k=[...g,...w];if(await qd(k),k.length===0){S("No optimizations found for your dependencies.");return}const $=!!process.stdout.isTTY&&!ft,x=t.format==="json"||!!t.json;if($&&!o&&!x){const R=new E$(k),M=await Xt(Q.createElement(V$,{isDryRun:!1,store:R}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit(),L=Array.isArray(M)?M:[];if(L.length===0){S("No optimizations selected.");return}const U=L.filter(j=>j.category!=="socket"&&j.hasCodemod),D=L.filter(j=>j.category!=="socket"&&!j.hasCodemod),C=L.filter(j=>j.category==="socket");if(U.length>0){S(`
335
- Running ${String(U.length)} codemod${U.length===1?"":"s"}...
336
- `);for(const j of U){const A=await Jd(r,j.packageName);A.filesChanged>0?ee(` ${j.packageName}: ${String(A.filesChanged)} file${A.filesChanged===1?"":"s"} updated`):S(` ${j.packageName}: no files changed`)}}if(D.length>0){se(`
337
- ${String(D.length)} selected replacement${D.length===1?"":"s"} require manual migration (no codemod available):`);for(const j of D)S(` ${j.packageName} → ${j.replacement}`);ie(" Replace usage in your source code, then remove from dependencies.")}if(C.length>0){const j=C.filter(V=>V.overrideSpec).map(V=>({original:V.packageName,spec:V.overrideSpec})),A=Ld(r,v(r,"package.json"),j,n);A.added.length>0&&ee(`
338
- Added ${String(A.added.length)} override${A.added.length===1?"":"s"}.`),A.updated.length>0&&ee(`Updated ${String(A.updated.length)} override${A.updated.length===1?"":"s"}.`)}if(C.length>0&&!t.noInstall){S(`
339
- Running ${n.name} install to update lockfile...`);const j=Ho(n,{dev:!1,filter:[],force:!1,frozenLockfile:!1,ignoreScripts:!1,lockfileOnly:!1,noOptional:!1,offline:!1,prod:!1,recursive:!1,silent:!1,workspaceRoot:!1},r,e);j!==0&&se(`${n.name} install exited with code ${String(j)}. Run it manually.`)}S(""),ee("Optimization complete.");return}if(x){process.stdout.write(`${JSON.stringify({e18e:g.map(R=>({category:R.category,hasCodemod:R.hasCodemod,packageName:R.packageName,replacement:R.replacement})),packageManager:n.name,socket:w.map(R=>({overrideSpec:R.overrideSpec,packageName:R.packageName,replacement:R.replacement})),total:k.length,workspaces:c.length},void 0,2)}
340
- `);return}const T=g.filter(R=>R.category==="native"),I=g.filter(R=>R.category==="preferred"),P=g.filter(R=>R.category==="micro-utility");if(T.length>0){S(`Native replacements (${String(T.length)}):`);for(const R of T)S(` ${R.hasCodemod?"⚙":" "} ${R.packageName} → ${R.replacement}`)}if(I.length>0){S(`
341
- Preferred alternatives (${String(I.length)}):`);for(const R of I)S(` ${R.hasCodemod?"⚙":" "} ${R.packageName} → ${R.replacement}`)}if(P.length>0){S(`
342
- Micro-utilities (${String(P.length)}):`);for(const R of P)S(` ${R.hasCodemod?"⚙":" "} ${R.packageName} → ${R.replacement}`)}if(w.length>0){S(`
343
- Socket.dev overrides (${String(w.length)}):`);for(const R of w)S(` ${R.packageName} → ${R.overrideSpec}`)}S(`
344
- Total: ${String(k.length)} optimizations available (⚙ = codemod available).`),o&&ie("Run without --dry-run for interactive selection.")},"execute"),group:"Workspace",name:"optimize",options:[{alias:"d",defaultValue:!1,description:"Preview available optimizations without applying",name:"dry-run",type:Boolean},{defaultValue:!1,description:"Pin Socket.dev overrides to exact versions",name:"pin",type:Boolean},{defaultValue:!1,description:"Only optimize production dependencies",name:"prod",type:Boolean},{defaultValue:!1,description:"Skip running install after applying overrides",name:"no-install",type:Boolean},{description:"Output format: table or json (default: table)",name:"format",type:String}]};var G$=Object.defineProperty,eo=b((e,t)=>G$(e,"name",{value:t,configurable:!0}),"b$a");const H$=eo(async(e,t,r=!1)=>{const n=Ne(e),{packageManager:o}=Mo(e),i=Ao(v(e,"package.json"),!1),s=Is(e),a=new Set(i);for(const D of s){const C=Ao(v(xe(e,D),"package.json"),!1);for(const j of C)a.add(j)}const c=$s(e),d=Jo(e,o),p=Lr(t?.security?.socket),g=t?.security?.socket?.acceptedRisks,h=Vd(e,n.name),y={exclude:[],ignore:[],include:[],includeLocked:!1,includePrerelease:!1,security:!0,target:"latest"},w=bd(e,n.name),[k,$,x,T]=await Promise.all([d.size>0?xs(d,y,c,void 0,e,p,g):Promise.resolve({failed:[],ignored:[],outdated:[]}),Promise.resolve(kd(e)),Promise.resolve(Gd(a)),Promise.resolve(Hd(a,h,n,!1))]),I=new Set(x.map(D=>D.packageName)),P=T.filter(D=>!I.has(D.packageName)),R=[...x,...P];r&&await qd(R);let M=0,L=0;if(p&&$.length>0){const D=await pn($.map(C=>({name:C.name,version:C.version})),p);for(const C of D.values())C.alerts.length>0&&(M+=C.alerts.length),C.score.overall<lr&&L++}let U=0;for(const D of k.outdated)D.vulnerabilities&&D.vulnerabilities.length>0&&(U+=D.vulnerabilities.length);if($.length>0){const D=await Yo($.map(C=>({name:C.name,version:C.version})));for(const C of D.values())U+=C.length}return{duplicates:w,installedCount:$.length,optimizations:R,outdated:k.outdated,socketIssues:{alerts:M,lowScore:L},vulnCount:U,workspaceCount:s.length}},"runAllScans"),wt=eo(e=>e?Ot("✓"):Ge("✗"),"icon"),ar=Re("⚠"),z$=eo(e=>{const{duplicates:t,installedCount:r,optimizations:n,outdated:o,socketIssues:i,vulnCount:s}=e;if(S(""),S($e("── Dependencies ────────────────────────")),S(` ${wt(!0)} ${String(r)} packages installed`),o.length>0){const y=o.filter(x=>x.updateType==="major").length,w=o.filter(x=>x.updateType==="minor").length,k=o.filter(x=>x.updateType==="patch").length,$=[];y>0&&$.push(`${String(y)} major`),w>0&&$.push(`${String(w)} minor`),k>0&&$.push(`${String(k)} patch`),S(` ${ar} ${String(o.length)} outdated (${$.join(", ")})`)}else S(` ${wt(!0)} All dependencies up to date`);t.length>0?S(` ${ar} ${String(t.length)} packages with duplicate versions`):S(` ${wt(!0)} No duplicate dependencies`),S(""),S($e("── Security ────────────────────────────")),s>0?S(` ${wt(!1)} ${String(s)} vulnerabilit${s===1?"y":"ies"} found`):S(` ${wt(!0)} No known vulnerabilities`),i.alerts>0&&S(` ${ar} ${String(i.alerts)} Socket.dev security alert${i.alerts===1?"":"s"}`),i.lowScore>0&&S(` ${ar} ${String(i.lowScore)} package${i.lowScore===1?"":"s"} with low security score`),i.alerts===0&&i.lowScore===0&&s===0&&S(` ${wt(!0)} No security issues detected`),S(""),S($e("── Optimization ────────────────────────"));let a=0,c=0,d=0,p=0;for(const y of n)switch(y.category){case"micro-utility":{d++;break}case"native":{a++;break}case"preferred":{c++;break}case"socket":{p++;break}}n.length>0?(a>0&&S(` ${ar} ${String(a)} replaceable with native APIs`),c>0&&S(` ${ar} ${String(c)} with lighter alternatives`),d>0&&S(` ${ar} ${String(d)} trivial micro-utilities`),p>0&&S(` ${ar} ${String(p)} @socketregistry overrides available`)):S(` ${wt(!0)} No optimizations available`),S(""),S($e("── Summary ─────────────────────────────"));const g=s,h=o.length+t.length+n.length;g===0&&h===0?ee(" Everything looks good!"):(g>0&&ur(` ${String(g)} security issue${g===1?"":"s"}`),h>0&&S(` ${String(h)} improvement${h===1?"":"s"} available`))},"displayResults"),q$=eo(e=>{const t=[];if(e.outdated.length>0&&t.push("vis update — update outdated dependencies"),(e.vulnCount>0||e.socketIssues.alerts>0)&&t.push("vis audit — detailed security analysis"),e.optimizations.length>0&&t.push("vis optimize — apply optimizations interactively"),e.duplicates.length>0&&t.push("vis dedupe — reduce duplicate versions"),t.length>0){S(""),ie(" Next steps:");for(const r of t)ie(` ${r}`)}S("")},"displayActions"),J$={description:"Run a full project health check (outdated, security, duplicates, optimizations)",examples:[["vis doctor","Full project health check"],["vis doctor --fix","Check and auto-apply safe fixes"],["vis doctor --format json","Machine-readable output for CI"],["vis doctor --exit-code","Exit with code 1 if security issues found"],["vis doctor --exit-code --strict","Fail on any issue (outdated, duplicates, security)"]],execute:eo(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!n)throw new Error("Could not determine workspace root.");const o=Ne(n);S(`
345
- ${$e("VIS DOCTOR")} — project health check
346
- `),S(` ${wt(!0)} Detected ${o.name} v${o.version}`);const i=Is(n);i.length>0&&S(` ${wt(!0)} ${String(i.length)} workspace package${i.length===1?"":"s"}`);const s=_d(n);if(s.length===0)S(` ${wt(!0)} Runtime: Node.js ${process.versions.node} ${Ot("✓")}`);else for(const h of s){const y=h.severity==="error"?Ge:Re;S(` ${wt(!1)} Runtime: ${y(h.message)}`)}S(`
347
- Scanning...`);const a=await H$(n,r,!!t.fix);let c=0,d=0,p=0,g=0;for(const h of a.optimizations)switch(h.category){case"micro-utility":{p++;break}case"native":{c++;break}case"preferred":{d++;break}case"socket":{g++;break}}if(t.format==="json"||t.json){process.stdout.write(`${JSON.stringify({dependencies:{duplicates:a.duplicates.length,installed:a.installedCount,outdated:a.outdated.length},optimizations:{microUtilities:p,native:c,preferred:d,socket:g,total:a.optimizations.length},packageManager:o.name,security:{alerts:a.socketIssues.alerts,lowScorePackages:a.socketIssues.lowScore,vulnerabilities:a.vulnCount},workspaces:a.workspaceCount},void 0,2)}
348
- `),t.exitCode&&(a.vulnCount>0||a.socketIssues.alerts>0)&&(process.exitCode=1);return}if(z$(a),t.fix&&a.optimizations.length>0){S(""),S(`Applying fixes...
349
- `);const h=a.optimizations.filter(w=>w.category==="socket"&&w.overrideSpec).map(w=>({original:w.packageName,spec:w.overrideSpec}));if(h.length>0){const w=Ld(n,v(n,"package.json"),h,o);w.added.length>0&&ee(` Added ${String(w.added.length)} security override${w.added.length===1?"":"s"}.`),w.updated.length>0&&ee(` Updated ${String(w.updated.length)} override${w.updated.length===1?"":"s"}.`)}const y=a.optimizations.filter(w=>w.category!=="socket"&&w.hasCodemod);for(const w of y){const k=await Jd(n,w.packageName);k.filesChanged>0&&ee(` ${w.packageName}: ${String(k.filesChanged)} file${k.filesChanged===1?"":"s"} updated`)}h.length>0&&(S(`
350
- Running ${o.name} install to update lockfile...`),Ho(o,{dev:!1,filter:[],force:!1,frozenLockfile:!1,ignoreScripts:!1,lockfileOnly:!1,noOptional:!1,offline:!1,prod:!1,recursive:!1,silent:!1,workspaceRoot:!1},n,e)),S(""),ee("Fixes applied.")}else q$(a);t.exitCode&&(t.strict?a.vulnCount>0||a.socketIssues.alerts>0||a.outdated.length>0||a.duplicates.length>0:a.vulnCount>0||a.socketIssues.alerts>0)&&(process.exitCode=1)},"execute"),group:"Security & Health",name:"doctor",options:[{description:"Output format: table or json (default: table)",name:"format",type:String},{defaultValue:!1,description:"Exit with code 1 if issues found",name:"exit-code",type:Boolean},{defaultValue:!1,description:"Auto-apply safe fixes (security overrides + codemods)",name:"fix",type:Boolean},{defaultValue:!1,description:"With --exit-code: also fail on outdated and duplicate deps",name:"strict",type:Boolean}]};var Y$=Object.defineProperty,K$=b((e,t)=>Y$(e,"name",{value:t,configurable:!0}),"s$g");const X$={argument:{description:"Command to execute followed by arguments",name:"command",type:String},description:"Execute a local node_modules/.bin command (no remote fallback)",examples:[["vis exec eslint .","Run local eslint"],["vis exec tsc --noEmit","Run local TypeScript check"],["vis exec -r -- eslint .","Run in all workspace packages"],["vis exec -c 'echo $PATH'","Shell mode"]],execute:K$(async({argument:e,logger:t,options:r,workspaceRoot:n})=>{const o=e;if(!o||o.length===0)throw new Error("No command specified. Usage: vis exec <command> [args...]");const[i,...s]=o,a=n??process.cwd(),c=Ne(a),d=Am(c,{args:s,command:i,filter:Yn(r.filter),parallel:r.parallel||!1,recursive:r.recursive||!1,reverse:r.reverse||!1,shellMode:r.shellMode||!1,workspaceRoot:r.workspaceRoot||!1},a,t);d!==0&&(process.exitCode=d)},"execute"),group:"Run & Execute",name:"exec",options:[{alias:"c",defaultValue:!1,description:"Execute within shell environment",name:"shell-mode",type:Boolean},{alias:"r",defaultValue:!1,description:"Run in every workspace package",name:"recursive",type:Boolean},{alias:"w",defaultValue:!1,description:"Run on workspace root only",name:"workspace-root",type:Boolean},{alias:"F",description:"Filter packages by name pattern",multiple:!0,name:"filter",type:String},{defaultValue:!1,description:"Run concurrently without topological ordering",name:"parallel",type:Boolean},{defaultValue:!1,description:"Reverse topological execution order",name:"reverse",type:Boolean}]};var Q$=Object.defineProperty,er=b((e,t)=>Q$(e,"name",{value:t,configurable:!0}),"i$b");const Yd=[".ts",".mts",".cts",".js",".mjs",".cjs"],Z$="template.yml",ex=[".d",".test",".spec",".config",".bench",".stories"],tx=[".d.ts",".d.mts",".d.cts",".js.map",".mjs.map",".cjs.map",".ts.map"],Kd=er(e=>{for(const t of Yd)if(e.endsWith(t))return e.slice(0,-t.length);return e},"stripExtension"),rx=er(e=>{if(tx.some(r=>e.endsWith(r))||!Yd.some(r=>e.endsWith(r)))return!1;const t=Kd(e);return!ex.some(r=>t.endsWith(r))},"isNativeFile"),tc=er((e,t)=>{const r=[];if(!E(e))return r;for(const n of Un(e,{includeDirs:!1,includeSymlinks:!1,maxDepth:1})){if(!rx(n.name))continue;const o=Kd(n.name);r.push({load:er(()=>nx(n.path),"load"),name:o,path:n.path,source:t})}return r},"scanNativeDirectory"),Si=er((e,t)=>{const r=[];if(!E(e))return r;for(const n of Un(e,{includeFiles:!1,includeSymlinks:!1,maxDepth:1})){if(n.path===e)continue;const o=v(n.path,Z$);E(o)&&r.push({load:er(()=>ox(n.path,n.name),"load"),name:n.name,path:n.path,source:t})}return r},"scanMoonDirectory"),Ci=er(e=>{const{extraDirectories:t=[],onWarning:r,workspaceRoot:n}=e,o=[];o.push(...tc(v(n,".vis","templates"),"native")),o.push(...Si(v(n,".vis","templates"),"moon")),o.push(...Si(v(n,".moon","templates"),"moon"));for(const s of t)o.push(...Si(s,"config")),o.push(...tc(s,"config"));const i=new Map;for(const s of o){const a=i.get(s.name);if(!a){i.set(s.name,s);continue}r&&r(`Template "${s.name}" exists in multiple sources — using ${a.source} (${a.path}), ignoring ${s.source} (${s.path}).`)}return[...i.values()].sort((s,a)=>s.name.localeCompare(a.name))},"discoverTemplates"),nx=er(async e=>{const{loadNativeTemplate:t}=await import("./packem_chunks/loader.js");return t(e)},"loadNativeFromPath"),ox=er(async(e,t)=>{const{loadMoonTemplate:r}=await import("./packem_chunks/index.js");return r(e,t)},"loadMoonFromPath");var ix=Object.defineProperty,Vt=b((e,t)=>ix(e,"name",{value:t,configurable:!0}),"c$n");const ti=Vt((e,t)=>new Promise(r=>{e.question(t,n=>{r(n.trim())})}),"ask"),sx=Vt(async(e,t,r)=>{const n=await ti(e,` ${t} ${re(r?"[Y/n]":"[y/N]")} `);return n===""?r:n.toLowerCase()==="y"||n.toLowerCase()==="yes"},"confirm"),ax=Vt(async(e,t,r,n)=>{process.stderr.write(` ${t}
351
- `);for(const[o,i]of r.entries()){const s=ve(Fe(` ${String(o+1)}.`)),a=i===n?re(" (default)"):"";process.stderr.write(`${s} ${i}${a}
352
- `)}for(;;){const o=await ti(e,`
353
- ${re(`Enter choice (1-${String(r.length)}):`)} `);if(o===""&&n!==void 0)return n;const i=Number.parseInt(o,10);if(Number.isInteger(i)&&i>=1&&i<=r.length)return r[i-1];const s=r.find(a=>a===o);if(s)return s;process.stderr.write(` ${re("Invalid choice. Try again.")}
354
- `)}},"selectOne"),cx=Vt(async(e,t,r,n)=>{process.stderr.write(` ${t} ${re("(comma-separated numbers)")}
355
- `);for(const[o,i]of r.entries()){const s=ve(Fe(` ${String(o+1)}.`)),a=n.includes(i)?re(" (default)"):"";process.stderr.write(`${s} ${i}${a}
356
- `)}for(;;){const o=await ti(e,`
357
- ${re("Enter choices:")} `);if(o===""&&n.length>0)return n;const i=o.split(",").map(s=>Number.parseInt(s.trim(),10)).filter(s=>Number.isInteger(s)&&s>=1&&s<=r.length);if(i.length>0)return i.map(s=>r[s-1]);process.stderr.write(` ${re("Invalid choice. Try again.")}
358
- `)}},"selectMany"),lx=Vt(e=>` ${re(`${e}:`)} `,"promptText"),dx=Vt((e,t)=>t.prompt??e,"variableLabel"),ux=Vt(e=>Object.entries(e).sort(([t,r],[n,o])=>{const i=r.order??0,s=o.order??0;return i!==s?i-s:t.localeCompare(n)}),"sortVariables"),rc=Vt((e,t)=>{switch(e.type){case"array":return t.split(",").map(r=>r.trim()).filter(Boolean);case"boolean":return t==="true"||t==="1"||t==="yes"||t==="y";case"enum":return e.multiple?t.split(",").map(r=>r.trim()).filter(Boolean):t;case"number":{const r=Number(t);if(Number.isNaN(r))throw new TypeError(`Expected a number, got "${t}"`);return r}default:return t}},"parseValue"),ji=Vt((e,t,r)=>{if(t.type==="enum"){const n=Array.isArray(r)?r:[r];for(const o of n)if(typeof o!="string"||!t.values.includes(o))throw new Error(`Variable "${e}" must be one of: ${t.values.join(", ")} (got "${String(o)}")`)}},"validateValue"),px=Vt(async e=>{const{defaults:t,interactive:r,overrides:n,variables:o}=e,i={},s=r?gt({input:process.stdin,output:process.stderr}):null;try{for(const[a,c]of ux(o)){if(Object.hasOwn(n,a)){const g=rc(c,n[a]??"");ji(a,c,g),i[a]=g;continue}if(t||!r||c.internal){if(c.default!==void 0){ji(a,c,c.default),i[a]=c.default;continue}if(c.required)throw new Error(`Required variable "${a}" not provided. Pass --${a}=<value> or remove --defaults.`);continue}const d=dx(a,c);let p;if(c.type==="boolean")p=await sx(s,d,!!(c.default??!1));else if(c.type==="enum")if(c.multiple){const g=Array.isArray(c.default)?c.default:[];p=await cx(s,d,c.values,g)}else{const g=typeof c.default=="string"?c.default:void 0;p=await ax(s,d,c.values,g)}else{const g=c.default===void 0?"":` (${String(c.default)})`,h=await ti(s,lx(`${d}${g}`));if(h===""&&c.default!==void 0)p=c.default;else if(h===""){if(c.required)throw new Error(`Variable "${a}" is required`);continue}else p=rc(c,h)}ji(a,c,p),i[a]=p}return i}finally{s?.close()}},"collectOptions");var fx=Object.defineProperty,Li=b((e,t)=>fx(e,"name",{value:t,configurable:!0}),"o$d");const gx=["git://","npm://","https://","github:","gitlab:","bitbucket:","sourcehut:"],mx=Li(e=>gx.some(t=>e.startsWith(t)),"isRemoteSource"),hx=Li(async(e,t={})=>{const r=t.targetDirectory===void 0,n=t.targetDirectory??Ip(v($p(),"vis-generate-")),o=Li(()=>{if(r)try{at(n,{force:!0,recursive:!0})}catch{}},"cleanup");S(`Downloading ${e}…`);try{const i=await pl(e,{auth:t.auth||process.env.GIGET_AUTH||process.env.GITHUB_TOKEN||process.env.GH_TOKEN||void 0,dir:n,force:!0,preferOffline:t.preferOffline});return{cleanup:o,directory:i.dir}}catch(i){o();const s=i instanceof Error?i.message:String(i);throw se(`Failed to download template: ${s}`),i}},"fetchRemoteTemplate");var yx=Object.defineProperty,Ur=b((e,t)=>yx(e,"name",{value:t,configurable:!0}),"a$f");const Xd=Ur((e,t="")=>{const r=[];for(const[n,o]of Object.entries(e)){const i=t?`${t}/${n}`:n;typeof o=="string"||Buffer.isBuffer(o)?r.push({content:o,path:i}):o&&typeof o=="object"&&r.push(...Xd(o,i))}return r},"flattenTree"),vx=Ur(e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,"formatSize"),wx=Ur((e,t)=>{if(st(t))throw new Error(`Refusing to write outside destination: template produced absolute path "${t}".`);const r=v(e,t),n=He(e,r);if(n===".."||n.startsWith(`..${qc}`)||st(n))throw new Error(`Refusing to write outside destination: "${t}" resolves to "${r}" which escapes "${e}".`);return r},"safeJoinDestination"),kx=Ur((e,t)=>{Se(Lt(e)),Z(e,t)},"writeOne"),bx=Ur((e,t,r=!1)=>{const n=typeof e=="string"?[e]:e.commands,o=typeof e=="string"?r:e.silent??r;for(const i of n){o||S(`$ ${i}`);const s=De(i,{cwd:t,shell:!0,stdio:o?"ignore":"inherit"});if(s.status!==0)return se(`Script failed (exit ${String(s.status)}): ${i}`),!1}return!0},"runScript"),$x=Ur(e=>{const t=new Map;for(const r of e){const n=typeof r=="string"?0:r.phase??0,o=t.get(n);o?o.push(r):t.set(n,[r])}return[...t.entries()].sort(([r],[n])=>r-n)},"groupByPhase"),xx=Ur(async(e,t)=>{const r={builtins:{dest_dir:t.destination,dest_rel_dir:He(t.workspaceRoot,t.destination)||".",working_dir:t.cwd,workspace_root:t.workspaceRoot},options:t.options},n=await e.produce(r),o=n.files?Xd(n.files):[],i=n.filesMeta??{},s=[];for(const a of o){const c=wx(t.destination,a.path);s.push({file:a,meta:i[a.path]??{},target:c})}if(t.dryRun){S(`${ve(Fe("Plan"))} ${re("(dry-run, no files written)")}`);for(const a of s){const c=Buffer.isBuffer(a.file.content)?a.file.content.length:Buffer.byteLength(a.file.content,"utf8");process.stderr.write(` ${re("write")} ${a.file.path} ${re(`(${vx(c)})`)}
359
- `)}}else{Se(t.destination);let a=0,c=0;for(const d of s){const{file:p,meta:g,target:h}=d,y=E(h),w=t.force||g.force===!0;if(y&&!w){se(`Skipped existing file: ${p.path} (use --force or set frontmatter force: true to overwrite)`),c+=1;continue}kx(h,p.content),a+=1}ee(`Wrote ${String(a)} file${a===1?"":"s"}${c>0?`, skipped ${String(c)}`:""}`)}if(!t.dryRun&&!t.skipScripts&&n.scripts&&n.scripts.length>0){const a=$x(n.scripts);S(`Running ${String(n.scripts.length)} script${n.scripts.length===1?"":"s"} across ${String(a.length)} phase${a.length===1?"":"s"}…`);for(const[,c]of a)if((await Promise.all(c.map(d=>Promise.resolve(bx(d,t.destination))))).includes(!1))throw new Error("Script failed — aborting.")}if(n.suggestions&&n.suggestions.length>0){process.stderr.write(`
360
- `),ie("Next steps:");for(const a of n.suggestions)process.stderr.write(` ${re("•")} ${a}
361
- `)}},"runTemplate");var Sx=Object.defineProperty,ri=b((e,t)=>Sx(e,"name",{value:t,configurable:!0}),"u$f");const Cx=ri(e=>{if(e.length===0){S("No templates found."),ie("Create one at .vis/templates/<name>.ts (programmatic) or .vis/templates/<name>/ (moon-format with template.yml).");return}S("Available templates:");for(const t of e){const r=re(`(${t.source})`);process.stderr.write(` ${ve(Fe(t.name))} ${r}
362
- `)}},"printList"),jx=ri(e=>{const t={},r=[];for(const n of e){if(!n.startsWith("--")){r.push(n);continue}const o=n.indexOf("=");if(o===-1){const a=n.slice(2);a.startsWith("no-")?t[a.slice(3)]="false":t[a]="true";continue}const i=n.slice(2,o),s=n.slice(o+1);t[i]=s}return{overrides:t,remaining:r}},"parsePassthroughOverrides"),Ex={argument:{description:"Template name (or remote source like git://… or npm://…) — omit for interactive picker",name:"template",type:String},description:"Scaffold files from an in-repo template",examples:[["vis generate","Pick a template interactively"],["vis generate package","Run the 'package' template"],["vis generate component -- --name=Button --style=primary","Pre-fill option values"],["vis generate package --to=./packages/new --force","Custom destination + overwrite"],["vis generate package --dry-run","Print planned writes without touching disk"],["vis generate git://github.com/org/template#main","Fetch and run a remote template"],["vis generate --list","Show discovered templates"]],execute:ri(async({argument:e,options:t,rawUnknown:r,visConfig:n,workspaceRoot:o})=>{const i=t.cwd||o||process.cwd(),s=o??i,a=n?.generator,c=Array.isArray(e)?e:e?[e]:[];if(t.list){const A=Ci({extraDirectories:a?.templates??[],onWarning:se,workspaceRoot:s});Cx(A);return}let d=[...r??[]];if(d.length===0){const A=process.argv.slice(2),V=A.indexOf("--");V!==-1&&(d=A.slice(V+1))}const p=c.indexOf("--"),g=p===-1?[]:c.slice(p+1),h=p===-1?c:c.slice(0,p),{overrides:y}=jx([...g,...d]);let w,k,$;const x=h[0];let T;if(x&&mx(x)){const A=await hx(x,{auth:a?.auth,preferOffline:!!t.preferOffline||a?.preferOffline});T=A.cleanup;try{const V=Ci({extraDirectories:[A.directory],workspaceRoot:s}).find(N=>N.path.startsWith(A.directory));if(!V)throw new Error(`Downloaded template at ${A.directory} contains no template.yml or *.ts entrypoint.`);w=await V.load(),k=V.name,$=w.destination}catch(V){throw T(),T=void 0,V}}else{const A=Ci({extraDirectories:a?.templates??[],onWarning:se,workspaceRoot:s});if(A.length===0)throw new Error("No templates found. Create one at .vis/templates/<name>.ts or .vis/templates/<name>/template.yml.");let V;if(x)V=x;else{if(t.noInteractive||!process.stdin.isTTY)throw new Error("No template specified. Pass a template name (see `vis generate --list`) or run interactively in a terminal.");V=await Tx(A)}const N=A.find(F=>F.name===V);if(!N)throw new Error(`Template "${V}" not found. Run 'vis generate --list' to see available templates.`);w=await N.load(),k=N.name,$=w.destination}const I=t.to,P=!!t.dryRun,R=!!t.force,M=!!t.defaults,L=!!t.skipScripts,U=!t.noInteractive&&!!process.stdin.isTTY&&!M;let D;I?D=I:$?D=$:D=".";const C=st(D)?D:xe(i,D);S(`Template: ${ve(Fe(k))}`),S(`Target: ${re(C)}`),process.stderr.write(`
363
- `);const j=await px({defaults:M,interactive:U,overrides:y,variables:w.options??{}});try{await xx(w,{cwd:i,destination:C,dryRun:P,force:R,options:j,skipScripts:L,workspaceRoot:s}),P||(process.stderr.write(`
364
- `),ee(`Template '${k}' applied.`))}finally{T?.()}},"execute"),group:"Scaffold & Config",name:"generate",options:[{defaultValue:!1,description:"List discovered templates",name:"list",type:Boolean},{description:"Destination directory",name:"to",type:String},{defaultValue:!1,description:"Print planned writes without touching disk",name:"dry-run",type:Boolean},{defaultValue:!1,description:"Overwrite existing files without prompting",name:"force",type:Boolean},{defaultValue:!1,description:"Skip prompts; use template defaults",name:"defaults",type:Boolean},{defaultValue:!1,description:"Skip running post-generation scripts",name:"skip-scripts",type:Boolean},{defaultValue:!1,description:"Skip interactive prompts (errors on missing required values)",name:"no-interactive",type:Boolean},{defaultValue:!1,description:"Prefer locally cached remote templates over re-downloading",name:"prefer-offline",type:Boolean}]},Tx=ri(async e=>{const{createInterface:t}=await import("node:readline"),r=t({input:process.stdin,output:process.stderr});try{process.stderr.write(` ${ve(Fe("vis generate"))} ${re("— pick a template")}
365
-
366
- `);for(const[n,o]of e.entries()){const i=ve(Fe(` ${String(n+1)}.`));process.stderr.write(`${i} ${o.name} ${re(`(${o.source})`)}
367
- `)}return new Promise((n,o)=>{r.question(`
368
- ${re(`Enter choice (1-${String(e.length)}):`)} `,i=>{const s=Number.parseInt(i.trim(),10);Number.isInteger(s)&&s>=1&&s<=e.length?n(e[s-1].name):o(new Error("Invalid choice."))})})}finally{r.close()}},"pickInteractive");var Rx=Object.defineProperty,In=b((e,t)=>Rx(e,"name",{value:t,configurable:!0}),"n$7");const Ax=In(e=>{const t=new Map;for(const[r,n]of Object.entries(e.dependencies))for(const o of n){const i=t.get(o.target)??[];i.push(r),t.set(o.target,i)}return Object.values(e.nodes).map(r=>({deps:e.dependencies[r.name]??[],name:r.name,reverseDeps:t.get(r.name)??[],type:r.type})).sort((r,n)=>r.type!==n.type?r.type==="application"?-1:1:r.name.localeCompare(n.name))},"buildNodes"),Ix=In((e,t,r)=>{let n=e;if(t==="app"?n=n.filter(o=>o.type==="application"):t==="lib"&&(n=n.filter(o=>o.type!=="application")),r){const o=r.toLowerCase();n=n.filter(i=>i.name.toLowerCase().includes(o))}return n},"filterNodes");class Ox{static{b(this,"GraphStore")}static{In(this,"GraphStore")}#e;#t=new Set;#n;constructor(t){this.#n=t;const r=Ax(t);this.#e={allNodes:r,filterActive:!1,filterText:"",filterType:"all",focusedPanel:"list",selectedIndex:0}}getSnapshot=In(()=>this.#e,"getSnapshot");subscribe=In(t=>(this.#t.add(t),()=>{this.#t.delete(t)}),"subscribe");getFilteredNodes(){return Ix(this.#e.allNodes,this.#e.filterType,this.#e.filterText)}getStats(){const t=this.#e.allNodes.filter(o=>o.type==="application").length,r=this.#e.allNodes.length,n=Object.values(this.#n.dependencies).reduce((o,i)=>o+i.length,0);return{apps:t,deps:n,libs:r-t,total:r}}setSelectedIndex(t){const r=this.getFilteredNodes(),n=r.length===0?-1:Math.max(0,Math.min(t,r.length-1));n!==this.#e.selectedIndex&&this.#o({...this.#e,selectedIndex:n})}setFocusedPanel(t){t!==this.#e.focusedPanel&&this.#o({...this.#e,focusedPanel:t})}setFilterType(t){t!==this.#e.filterType&&this.#o({...this.#e,filterType:t,selectedIndex:0})}setFilter(t){this.#o({...this.#e,filterText:t,selectedIndex:0})}setFilterActive(t){t!==this.#e.filterActive&&this.#o({...this.#e,filterActive:t,filterText:t?this.#e.filterText:"",selectedIndex:t?this.#e.selectedIndex:0})}#o(t){this.#e=t;for(const r of this.#t)try{r()}catch{}}}var Px=Object.defineProperty,Nx=b((e,t)=>Px(e,"name",{value:t,configurable:!0}),"p$o");const Mx=Nx(({focused:e,node:t,scrollRef:r})=>{const n=e?"white":"gray";if(!t)return u(m,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:u(l,{dimColor:!0,children:"No project selected"})});const o=t.type==="application",i=o?"yellow":"cyan",s=o?"Application":"Library";return u(m,{borderColor:n,borderStyle:"single",borderTopRightTitle:` ${s} `,borderTopTitle:` ${t.name} `,flexDirection:"column",flexGrow:1,children:f(cn,{flexGrow:1,flexShrink:1,paddingX:2,ref:r,scrollbar:!0,scrollbarColor:"gray",children:[f(m,{flexDirection:"column",marginTop:1,children:[f(m,{children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"DEPENDS ON"}),f(l,{dimColor:!0,children:[" ","(",t.deps.length,")"]})]}),t.deps.length===0?u(m,{marginTop:1,paddingLeft:2,children:u(l,{dimColor:!0,children:"No dependencies"})}):u(m,{flexDirection:"column",marginTop:1,children:t.deps.map(a=>f(m,{gap:1,paddingLeft:2,children:[u(l,{color:"cyan",children:"→"}),u(l,{children:a.target}),a.type!=="static"&&f(l,{dimColor:!0,children:["(",a.type,")"]})]},a.target))})]}),f(m,{flexDirection:"column",marginTop:1,children:[f(m,{children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"REQUIRED BY"}),f(l,{dimColor:!0,children:[" ","(",t.reverseDeps.length,")"]})]}),t.reverseDeps.length===0?u(m,{marginTop:1,paddingLeft:2,children:u(l,{dimColor:!0,children:"No reverse dependencies"})}):u(m,{flexDirection:"column",marginTop:1,children:t.reverseDeps.map(a=>f(m,{gap:1,paddingLeft:2,children:[u(l,{color:"magenta",children:"←"}),u(l,{children:a})]},a))})]}),f(m,{flexDirection:"column",marginTop:1,children:[f(m,{children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"INFO"})]}),f(m,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[f(m,{children:[u(m,{width:16,children:u(l,{dimColor:!0,children:"Type:"})}),u(l,{color:i,children:s})]}),f(m,{children:[u(m,{width:16,children:u(l,{dimColor:!0,children:"Dependencies:"})}),u(l,{children:String(t.deps.length)})]}),f(m,{children:[u(m,{width:16,children:u(l,{dimColor:!0,children:"Required by:"})}),u(l,{children:String(t.reverseDeps.length)})]}),f(m,{children:[u(m,{width:16,children:u(l,{dimColor:!0,children:"Connectivity:"})}),u(l,{children:String(t.deps.length+t.reverseDeps.length)})]})]})]})]})})},"ProjectDetailPanel");var Dx=Object.defineProperty,Os=b((e,t)=>Dx(e,"name",{value:t,configurable:!0}),"g$i");const Bx=[{key:"all",label:"All",shortcut:"1"},{key:"app",label:"Apps",shortcut:"2"},{key:"lib",label:"Libs",shortcut:"3"}],nc=Os(({isSelected:e,node:t})=>{const r=t.type==="application",n=r?"yellow":"cyan",o=r?"app":"lib";return f(m,{flexShrink:0,height:1,children:[f(l,{children:[e?"▶":" "," "]}),u(m,{flexGrow:1,children:u(l,{bold:e,inverse:e,wrap:"truncate",children:t.name})}),f(l,{color:n,children:[" ",o]}),f(l,{dimColor:!0,children:[" ","→",t.deps.length," ","←",t.reverseDeps.length]})]})},"ProjectRow"),oc=Os(({count:e,label:t})=>f(m,{flexShrink:0,height:1,marginTop:1,children:[f(l,{dimColor:!0,children:["▼"," "]}),u(l,{bold:!0,color:"white",children:t.toUpperCase()}),f(l,{dimColor:!0,children:[" ","(",e,")"]})]}),"TypeHeader"),Fx=Os(({filterActive:e,filterText:t,filterType:r,focused:n,nodes:o,scrollOffset:i,selectedIndex:s,stats:a,viewportHeight:c})=>{const d=n?"white":"gray",p=o.filter($=>$.type==="application"),g=o.filter($=>$.type!=="application"),h=[];let y=0;if(p.length>0){h.push(u(oc,{count:p.length,label:"Applications"},"hdr-apps"));for(const $ of p){const x=y;h.push(u(nc,{isSelected:x===s,node:$},$.name)),y++}}if(g.length>0){h.push(u(oc,{count:g.length,label:"Libraries"},"hdr-libs"));for(const $ of g){const x=y;h.push(u(nc,{isSelected:x===s,node:$},$.name)),y++}}let w=0;p.length>0&&(w+=2+p.length),g.length>0&&(w+=2+g.length);const k=w>c&&c>0;return f(m,{borderColor:d,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[f(m,{flexShrink:0,gap:1,paddingX:1,children:[u(l,{bold:!0,inverse:!0,children:" VIS "}),f(l,{wrap:"truncate",children:[a.total," ","packages"]}),f(l,{dimColor:!0,children:["(",a.apps," ","apps,"," ",a.libs," ","libs,"," ",a.deps," ","deps)"]})]}),u(m,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:Bx.map($=>{const x=r===$.key;return f(m,{children:[u(l,{dimColor:!x,children:"["}),u(l,{bold:x,color:x?"cyan":"gray",children:$.shortcut}),u(l,{dimColor:!x,children:"]"}),f(l,{color:x?"white":"gray",children:[" ",$.label]})]},$.key)})}),e&&f(m,{flexShrink:0,paddingX:1,children:[u(l,{bold:!0,color:"white",children:"/ "}),u(l,{children:t}),u(l,{inverse:!0,children:" "})]}),f(m,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[u(m,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:u(m,{flexDirection:"column",marginTop:-i,children:h})}),k&&u(m,{flexShrink:0,marginLeft:1,marginRight:1,children:u(Gn,{contentHeight:w,placement:"inset",scrollOffset:i,style:"block",viewportHeight:c})})]})]})},"ProjectListPanel");var Lx=Object.defineProperty,Vx=b((e,t)=>Lx(e,"name",{value:t,configurable:!0}),"M$c");const _x=100,Ux=40,Wx=10,ic={1:"all",2:"app",3:"lib"},Gx=Vx(({autoExitSeconds:e=0,store:t})=>{const{exit:r}=an(),{columns:n,rows:o}=sn(),i=Hn(t.subscribe,t.getSnapshot),[s,a]=we(!1),c=Ue(null),d=Ue(null),[p,g]=we(0),[h,y]=we(!1),w=Dt(()=>t.getFilteredNodes(),[i.allNodes,i.filterType,i.filterText]),k=Dt(()=>t.getStats(),[i.allNodes]),$=w[i.selectedIndex]??null,x=Nt(C=>{const j=w.filter(F=>F.type==="application"),A=w.filter(F=>F.type!=="application");let V=0,N=0;if(j.length>0){V+=2;for(let F=0;F<j.length;F++){if(N===C)return V;V+=1,N++}}if(A.length>0){V+=2;for(let F=0;F<A.length;F++){if(N===C)return V;V+=1,N++}}return V},[w]),T=Math.max(1,o-8-(i.filterActive?1:0)),I=Nt(C=>{const j=x(C);g(A=>j>A+T-2?Math.max(0,j-T+2):j<A+1?Math.max(0,j-1):A)},[x,T]);if(Pt(()=>{d.current?.scrollToTop()},[$?.name]),kt((C,j)=>{if(C==="c"&&j.ctrl){r();return}if(!h){if(s){j.escape||C==="?"?a(!1):C==="q"?(a(!1),y(!0)):j.downArrow||C==="j"?c.current?.scrollBy(1):(j.upArrow||C==="k")&&c.current?.scrollBy(-1);return}if(C==="?"){a(!0);return}if(C==="q"){y(!0);return}if(j.tab){t.setFocusedPanel(i.focusedPanel==="list"?"detail":"list");return}if(ic[C]){t.setFilterType(ic[C]);return}if(i.filterActive){if(j.escape){t.setFilterActive(!1);return}if(j.return){t.setFilterActive(!1);return}if(j.backspace){t.setFilter(i.filterText.slice(0,-1));return}if(C&&!j.ctrl&&!j.meta){t.setFilter(i.filterText+C);return}return}if(i.focusedPanel==="list"){if(w.length===0){C==="/"&&t.setFilterActive(!0);return}if(j.downArrow||C==="j"){const A=Math.min(i.selectedIndex+1,w.length-1);t.setSelectedIndex(A),I(A);return}if(j.upArrow||C==="k"){const A=Math.max(i.selectedIndex-1,0);t.setSelectedIndex(A),I(A);return}if(j.pageDown){const A=Math.min(i.selectedIndex+10,w.length-1);t.setSelectedIndex(A),I(A);return}if(j.pageUp){const A=Math.max(i.selectedIndex-10,0);t.setSelectedIndex(A),I(A);return}if(j.home){t.setSelectedIndex(0),g(0);return}if(j.end){const A=w.length-1;t.setSelectedIndex(A),I(A);return}if(C==="/"){t.setFilterActive(!0);return}if(j.rightArrow){t.setFocusedPanel("detail");return}return}if(i.focusedPanel==="detail"){if(j.escape||j.leftArrow){t.setFocusedPanel("list");return}if(j.downArrow||C==="j"){d.current?.scrollBy(1);return}if(j.upArrow||C==="k"){d.current?.scrollBy(-1);return}if(j.pageDown){d.current?.scrollBy(10);return}if(j.pageUp){d.current?.scrollBy(-10);return}if(j.home){d.current?.scrollToTop();return}j.end&&d.current?.scrollToBottom()}}},{isActive:!0}),n<Ux||o<Wx)return u(m,{alignItems:"center",height:o,justifyContent:"center",width:n,children:f(l,{color:"yellow",children:["Terminal too small (",n,"x",o,")"]})});const P=n>=_x,R=u(m,{borderBottom:!1,borderColor:"gray",borderLeft:!1,borderRight:!1,borderStyle:"single",flexShrink:0,children:f(m,{flexWrap:"wrap",gap:2,paddingX:1,children:[f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"q"}),u(l,{dimColor:!0,children:"QUIT"})]},"q"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"?"}),u(l,{dimColor:!0,children:"HELP"})]},"?"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"↑↓"}),u(l,{dimColor:!0,children:"NAV"})]},"nav"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"1-3 /"}),u(l,{dimColor:!0,children:"FILTER"})]},"f"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"Tab"}),u(l,{dimColor:!0,children:"PANEL"})]},"t")]})}),M=f(Ar,{footer:f(l,{dimColor:!0,children:[u(l,{bold:!0,color:"white",children:"↑↓"})," ","scroll"," ",u(l,{bold:!0,color:"white",children:"?"}),"/",u(l,{bold:!0,color:"white",children:"Esc"})," ","close"]}),scrollRef:c,title:"KEYBOARD SHORTCUTS",visible:s,width:52,children:[f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"NAVIGATION"})]}),f(m,{children:[u(m,{width:24,children:f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","↑","/k"]}),u(l,{dimColor:!0,children:" Move up"})]})}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","↓","/j"]}),u(l,{dimColor:!0,children:" Move down"})]})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","Tab"]}),u(l,{dimColor:!0,children:" Switch panel"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","→","/","←"]}),u(l,{dimColor:!0,children:" Focus detail/list"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","PgUp/PgDn"]}),u(l,{dimColor:!0,children:" Jump 10 items"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","Home/End"]}),u(l,{dimColor:!0,children:" Jump to start/end"})]})]}),f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"FILTERS"})]}),f(m,{children:[u(m,{width:24,children:f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","1"]}),u(l,{dimColor:!0,children:" All"})]})}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","2"]}),u(l,{dimColor:!0,children:" Apps only"})]})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","3"]}),u(l,{dimColor:!0,children:" Libraries only"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","/"]}),u(l,{dimColor:!0,children:" Text filter"})]})]}),f(m,{flexDirection:"column",children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"ACTIONS"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","q"]}),u(l,{dimColor:!0,children:" Quit"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","?"]}),u(l,{dimColor:!0,children:" Toggle help"})]})]})]}),L=u(Fx,{filterActive:i.filterActive,filterText:i.filterText,filterType:i.filterType,focused:i.focusedPanel==="list",nodes:w,scrollOffset:p,selectedIndex:i.selectedIndex,stats:k,viewportHeight:T}),U=u(Mx,{focused:i.focusedPanel==="detail",node:$,scrollRef:d});if(P){const C=Math.floor(n*.35);return f(m,{flexDirection:"column",height:o,width:n,children:[f(m,{flexDirection:"row",flexGrow:1,children:[u(m,{flexGrow:1,children:L}),u(m,{width:C,children:U})]}),R,u(Nr,{autoExitSeconds:e??3,onCancel:b(()=>{y(!1)},"onCancel"),visible:h}),M]})}const D=Math.floor(o*.55);return f(m,{flexDirection:"column",height:o,width:n,children:[u(m,{height:D,children:L}),u(m,{flexGrow:1,children:U}),R,u(Nr,{autoExitSeconds:e??3,onCancel:b(()=>{y(!1)},"onCancel"),visible:h}),M]})},"VisGraphApp");var sc=Object.freeze,Qd=Object.defineProperty,gn=b((e,t)=>Qd(e,"name",{value:t,configurable:!0}),"y$8"),Hx=b((e,t)=>sc(Qd(e,"raw",{value:sc(t||e.slice())})),"k$d");const Zd=gn((e,t,r,n,o,i,s,a)=>{const c=re(r?"└── ":"├── "),d=o.has(e),p=d?re(" (*)"):"",g=n.get(e),h=g?.type==="application"?ve(e):e;if(i.push(`${t}${c}${h}${p}`),d)return;o.add(e);const y=g?.deps??[],w=r?`${t} `:`${t}${re("│")} `;if(a>=s&&y.length>0){i.push(`${w}${re(`... ${y.length} more`)}`);return}for(let k=0;k<y.length;k++){const $=y[k];$&&Zd($.target,w,k===y.length-1,n,o,i,s,a+1)}},"printDepsTree"),ac=gn((e,t,r,n,o,i)=>{const s=t.get(e),a=s?.type==="application"?ve(e):e;n.push(`${i}${a}`),r.add(e);const c=s?.deps??[];if(c.length===0){n.push(`${i} ${re("(no dependencies)")}`);return}if(o<=0){n.push(`${i} ${re(`... ${c.length} dependencies`)}`);return}for(let d=0;d<c.length;d++){const p=c[d];p&&Zd(p.target,i,d===c.length-1,t,r,n,o,1)}},"printRootProject"),cc=gn((e,t)=>{const r=new Map;for(const[g,h]of Object.entries(e.nodes))r.set(g,{deps:(e.dependencies[g]??[]).map(y=>({target:y.target,type:y.type})),name:g,type:h.type});const n=[],o=[];for(const[g,h]of r)h.type==="application"?n.push(g):o.push(g);n.sort(),o.sort();const i=n.length+o.length,s=Object.values(e.dependencies).reduce((g,h)=>g+h.length,0),a=[];if(a.push(ve("Project Dependency Graph"),""),n.length>0){a.push(` ${ve(Fe(`Applications (${n.length})`))}`,"");for(const g of n)ac(g,r,new Set,a,t," "),a.push("")}if(o.length>0){a.push(` ${ve(Fe(`Libraries (${o.length})`))}`,"");for(const g of o)ac(g,r,new Set,a,t," "),a.push("")}const c=process.stdout.columns||80;a.push(re("─".repeat(Math.min(c,60)))),a.push(`${ve(String(i))} packages ${re("·")} ${ve(String(s))} dependencies ${re("·")} ${ve(String(n.length))} apps${re(",")} ${ve(String(o.length))} libraries`);const d=new Set;let p=!1;for(const g of[...n,...o]){const h=r.get(g)?.deps??[];for(const y of h)d.has(y.target)&&(p=!0),d.add(y.target);d.add(g)}return p&&a.push(re("(*) = already shown above")),a.join(`
369
- `)},"projectGraphToAscii"),zx=gn(e=>{const t=Object.values(e.nodes).map(r=>({name:r.name,type:r.type}));return{edges:Object.values(e.dependencies).flat(),nodes:t}},"projectGraphToJson");var lc;const qx=gn(e=>{const t=Object.values(e.nodes).map(s=>({name:s.name,type:s.type})),r=[];for(const s of Object.values(e.dependencies))for(const a of s)r.push({source:a.source,target:a.target,type:a.type});const n=t.filter(s=>s.type==="application"),o=t.filter(s=>s.type!=="application"),i={apps:n.length,edges:r,libs:o.length,nodes:t};return String.raw(lc||(lc=Hx([`<!DOCTYPE html>
370
- <html lang="en">
371
- <head>
372
- <meta charset="UTF-8">
373
- <title>Project Dependency Graph</title>
374
- <style>
375
- * { margin: 0; padding: 0; box-sizing: border-box; }
376
- body { font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #e2e8f0; overflow: hidden; }
377
- svg { width: 100vw; height: 100vh; }
378
- .edge { fill: none; marker-end: url(#arrow); }
379
- .node rect { rx: 8; ry: 8; cursor: pointer; transition: stroke-width 0.15s; }
380
- .node text { font-size: 12px; font-weight: 600; pointer-events: none; }
381
- .node:hover rect { stroke-width: 2.5; stroke: #fff; }
382
- #info { position: fixed; top: 16px; right: 16px; background: #1e293b; padding: 14px 20px; border-radius: 10px; font-size: 13px; border: 1px solid #334155; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
383
- #info b { font-variant-numeric: tabular-nums; }
384
- .app-count { color: #fbbf24; }
385
- .lib-count { color: #38bdf8; }
386
- .dep-count { color: #a78bfa; }
387
- #legend { position: fixed; bottom: 16px; left: 16px; background: #1e293b; padding: 12px 16px; border-radius: 10px; font-size: 12px; border: 1px solid #334155; display: flex; gap: 16px; align-items: center; }
388
- .legend-dot { width: 12px; height: 12px; border-radius: 3px; display: inline-block; vertical-align: middle; margin-right: 6px; }
389
- #tooltip { position: fixed; display: none; background: #1e293b; border: 1px solid #475569; border-radius: 8px; padding: 12px 16px; font-size: 12px; max-width: 320px; box-shadow: 0 8px 24px rgba(0,0,0,0.4); z-index: 10; pointer-events: none; }
390
- #tooltip h3 { font-size: 14px; margin-bottom: 6px; }
391
- #tooltip .type-badge { display: inline-block; padding: 1px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; margin-left: 8px; }
392
- #tooltip .dep-section { margin-top: 8px; color: #94a3b8; }
393
- #tooltip ul { list-style: none; padding-left: 0; margin-top: 4px; }
394
- #tooltip li { padding: 1px 0; color: #cbd5e1; }
395
- #tooltip li::before { content: "92 "; color: #64748b; }
396
- </style>
397
- </head>
398
- <body>
399
- <div id="info">
400
- <b class="app-count">`,`</b> apps &middot;
401
- <b class="lib-count">`,`</b> libraries &middot;
402
- <b class="dep-count">`,`</b> dependencies
403
- </div>
404
- <div id="legend">
405
- <span><span class="legend-dot" style="background:#fbbf24"></span>Application</span>
406
- <span><span class="legend-dot" style="background:#38bdf8"></span>Library</span>
407
- <span style="color:#64748b">&mdash; solid = static &nbsp; - - - = implicit</span>
408
- </div>
409
- <div id="tooltip"></div>
410
- <svg id="graph">
411
- <defs>
412
- <marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto">
413
- <path d="M 0 0 L 10 5 L 0 10 z" fill="#64748b"/>
414
- </marker>
415
- </defs>
416
- </svg>
417
- <script>
418
- const data = `,`;
419
- const svg = document.getElementById('graph');
420
- const tooltip = document.getElementById('tooltip');
421
- const W = window.innerWidth, H = window.innerHeight;
422
-
423
- // Build adjacency
424
- const depMap = {}, rdepMap = {};
425
- data.nodes.forEach(n => { depMap[n.name] = []; rdepMap[n.name] = []; });
426
- data.edges.forEach(e => { depMap[e.source]?.push(e.target); rdepMap[e.target]?.push(e.source); });
427
-
428
- // Escape text for safe DOM insertion
429
- function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.textContent; }
430
-
431
- // Force-directed layout
432
- const repulsion = 5000 + data.nodes.length * 150;
433
- const nodes = data.nodes.map(n => ({
434
- ...n, x: W/2 + (Math.random()-0.5)*Math.min(W*0.6, 600),
435
- y: H/2 + (Math.random()-0.5)*Math.min(H*0.6, 400), vx: 0, vy: 0
436
- }));
437
- const nodeMap = new Map(nodes.map(n => [n.name, n]));
438
- const edges = data.edges.map(e => ({
439
- source: nodeMap.get(e.source), target: nodeMap.get(e.target), type: e.type
440
- }));
441
-
442
- for (let iter = 0; iter < 400; iter++) {
443
- for (let i = 0; i < nodes.length; i++) {
444
- for (let j = i+1; j < nodes.length; j++) {
445
- let dx = nodes[j].x - nodes[i].x, dy = nodes[j].y - nodes[i].y;
446
- let d = Math.sqrt(dx*dx + dy*dy) || 1;
447
- let f = repulsion / (d * d);
448
- nodes[i].vx -= dx/d * f; nodes[i].vy -= dy/d * f;
449
- nodes[j].vx += dx/d * f; nodes[j].vy += dy/d * f;
450
- }
451
- }
452
- edges.forEach(e => {
453
- if (!e.source || !e.target) {
454
- return;
455
- }
456
- let dx = e.target.x - e.source.x, dy = e.target.y - e.source.y;
457
- let d = Math.sqrt(dx*dx + dy*dy) || 1;
458
- let f = (d - 180) * 0.008;
459
- e.source.vx += dx/d * f; e.source.vy += dy/d * f;
460
- e.target.vx -= dx/d * f; e.target.vy -= dy/d * f;
461
- });
462
- nodes.forEach(n => {
463
- n.vx += (W/2 - n.x) * 0.001; n.vy += (H/2 - n.y) * 0.001;
464
- n.x += n.vx * 0.3; n.y += n.vy * 0.3;
465
- n.vx *= 0.75; n.vy *= 0.75;
466
- n.x = Math.max(80, Math.min(W-80, n.x));
467
- n.y = Math.max(40, Math.min(H-40, n.y));
468
- });
469
- }
470
-
471
- // Measure text widths
472
- const measure = document.createElementNS('http://www.w3.org/2000/svg','text');
473
- measure.setAttribute('font-size','12'); measure.setAttribute('font-weight','600');
474
- measure.setAttribute('font-family','system-ui');
475
- svg.appendChild(measure);
476
- const widths = {};
477
- nodes.forEach(n => { measure.textContent = n.name; widths[n.name] = measure.getComputedTextLength(); });
478
- svg.removeChild(measure);
479
-
480
- // Render edges
481
- edges.forEach(e => {
482
- if (!e.source || !e.target) {
483
- return;
484
- }
485
- const sw = (widths[e.source.name]||80)/2 + 12;
486
- const tw = (widths[e.target.name]||80)/2 + 12;
487
- const dx = e.target.x - e.source.x, dy = e.target.y - e.source.y;
488
- const d = Math.sqrt(dx*dx+dy*dy)||1;
489
- const x1 = e.source.x + dx/d*sw, y1 = e.source.y + dy/d*14;
490
- const x2 = e.target.x - dx/d*tw, y2 = e.target.y - dy/d*14;
491
- const line = document.createElementNS('http://www.w3.org/2000/svg','line');
492
- line.setAttribute('x1',x1); line.setAttribute('y1',y1);
493
- line.setAttribute('x2',x2); line.setAttribute('y2',y2);
494
- line.setAttribute('class','edge');
495
- const edgeColors = { implicit: '#475569', devDependency: '#888888', peerDependency: '#CC8800' };
496
- line.setAttribute('stroke', edgeColors[e.type] || '#64748b');
497
- line.setAttribute('stroke-width', '1.5');
498
- if (e.type === 'implicit' || e.type === 'peerDependency') {
499
- line.setAttribute('stroke-dasharray', '6,4');
500
- }
501
- if (e.type === 'devDependency') {
502
- line.setAttribute('stroke-dasharray', '3,3');
503
- }
504
- svg.appendChild(line);
505
- });
506
-
507
- // Render nodes
508
- nodes.forEach(n => {
509
- const w = (widths[n.name]||80) + 24;
510
- const h = 32;
511
- const isApp = n.type === 'application';
512
- const fill = isApp ? '#fbbf24' : '#38bdf8';
513
- const textFill = '#0f172a';
514
- const stroke = isApp ? '#f59e0b' : '#0284c7';
515
-
516
- const g = document.createElementNS('http://www.w3.org/2000/svg','g');
517
- g.setAttribute('class','node');
518
- g.setAttribute('transform','translate('+(n.x - w/2)+','+(n.y - h/2)+')');
519
- const rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
520
- rect.setAttribute('width', w); rect.setAttribute('height', h);
521
- rect.setAttribute('fill', fill); rect.setAttribute('stroke', stroke); rect.setAttribute('stroke-width','1.5');
522
- g.appendChild(rect);
523
- const text = document.createElementNS('http://www.w3.org/2000/svg','text');
524
- text.setAttribute('x', w/2); text.setAttribute('y', h/2 + 4.5);
525
- text.setAttribute('text-anchor','middle'); text.setAttribute('fill', textFill);
526
- text.textContent = n.name;
527
- g.appendChild(text);
528
-
529
- g.addEventListener('mouseenter', (ev) => {
530
- const deps = depMap[n.name] || [];
531
- const rdeps = rdepMap[n.name] || [];
532
-
533
- // Build tooltip using safe DOM methods
534
- tooltip.textContent = '';
535
-
536
- const heading = document.createElement('h3');
537
- heading.textContent = n.name;
538
- const badge = document.createElement('span');
539
- badge.className = 'type-badge';
540
- badge.style.background = fill;
541
- badge.style.color = '#0f172a';
542
- badge.textContent = n.type;
543
- heading.appendChild(badge);
544
- tooltip.appendChild(heading);
545
-
546
- if (deps.length) {
547
- const label = document.createElement('div');
548
- label.className = 'dep-section';
549
- label.textContent = 'Depends on:';
550
- tooltip.appendChild(label);
551
- const ul = document.createElement('ul');
552
- deps.forEach(d => { const li = document.createElement('li'); li.textContent = d; ul.appendChild(li); });
553
- tooltip.appendChild(ul);
554
- }
555
- if (rdeps.length) {
556
- const label = document.createElement('div');
557
- label.className = 'dep-section';
558
- label.textContent = 'Required by:';
559
- tooltip.appendChild(label);
560
- const ul = document.createElement('ul');
561
- rdeps.forEach(d => { const li = document.createElement('li'); li.textContent = d; ul.appendChild(li); });
562
- tooltip.appendChild(ul);
563
- }
564
- if (!deps.length && !rdeps.length) {
565
- const empty = document.createElement('div');
566
- empty.style.marginTop = '6px';
567
- empty.style.color = '#64748b';
568
- empty.textContent = 'No dependencies';
569
- tooltip.appendChild(empty);
570
- }
571
-
572
- tooltip.style.display = 'block';
573
- const rect = tooltip.getBoundingClientRect();
574
- tooltip.style.left = Math.min(ev.clientX + 12, W - rect.width - 12) + 'px';
575
- tooltip.style.top = Math.min(ev.clientY + 12, H - rect.height - 12) + 'px';
576
- });
577
- g.addEventListener('mouseleave', () => { tooltip.style.display = 'none'; });
578
- svg.appendChild(g);
579
- });
580
- <\/script>
581
- </body>
582
- </html>`],[`<!DOCTYPE html>
583
- <html lang="en">
584
- <head>
585
- <meta charset="UTF-8">
586
- <title>Project Dependency Graph</title>
587
- <style>
588
- * { margin: 0; padding: 0; box-sizing: border-box; }
589
- body { font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #e2e8f0; overflow: hidden; }
590
- svg { width: 100vw; height: 100vh; }
591
- .edge { fill: none; marker-end: url(#arrow); }
592
- .node rect { rx: 8; ry: 8; cursor: pointer; transition: stroke-width 0.15s; }
593
- .node text { font-size: 12px; font-weight: 600; pointer-events: none; }
594
- .node:hover rect { stroke-width: 2.5; stroke: #fff; }
595
- #info { position: fixed; top: 16px; right: 16px; background: #1e293b; padding: 14px 20px; border-radius: 10px; font-size: 13px; border: 1px solid #334155; box-shadow: 0 4px 12px rgba(0,0,0,0.3); }
596
- #info b { font-variant-numeric: tabular-nums; }
597
- .app-count { color: #fbbf24; }
598
- .lib-count { color: #38bdf8; }
599
- .dep-count { color: #a78bfa; }
600
- #legend { position: fixed; bottom: 16px; left: 16px; background: #1e293b; padding: 12px 16px; border-radius: 10px; font-size: 12px; border: 1px solid #334155; display: flex; gap: 16px; align-items: center; }
601
- .legend-dot { width: 12px; height: 12px; border-radius: 3px; display: inline-block; vertical-align: middle; margin-right: 6px; }
602
- #tooltip { position: fixed; display: none; background: #1e293b; border: 1px solid #475569; border-radius: 8px; padding: 12px 16px; font-size: 12px; max-width: 320px; box-shadow: 0 8px 24px rgba(0,0,0,0.4); z-index: 10; pointer-events: none; }
603
- #tooltip h3 { font-size: 14px; margin-bottom: 6px; }
604
- #tooltip .type-badge { display: inline-block; padding: 1px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; margin-left: 8px; }
605
- #tooltip .dep-section { margin-top: 8px; color: #94a3b8; }
606
- #tooltip ul { list-style: none; padding-left: 0; margin-top: 4px; }
607
- #tooltip li { padding: 1px 0; color: #cbd5e1; }
608
- #tooltip li::before { content: "\\2192 "; color: #64748b; }
609
- </style>
610
- </head>
611
- <body>
612
- <div id="info">
613
- <b class="app-count">`,`</b> apps &middot;
614
- <b class="lib-count">`,`</b> libraries &middot;
615
- <b class="dep-count">`,`</b> dependencies
616
- </div>
617
- <div id="legend">
618
- <span><span class="legend-dot" style="background:#fbbf24"></span>Application</span>
619
- <span><span class="legend-dot" style="background:#38bdf8"></span>Library</span>
620
- <span style="color:#64748b">&mdash; solid = static &nbsp; - - - = implicit</span>
621
- </div>
622
- <div id="tooltip"></div>
623
- <svg id="graph">
624
- <defs>
625
- <marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto">
626
- <path d="M 0 0 L 10 5 L 0 10 z" fill="#64748b"/>
627
- </marker>
628
- </defs>
629
- </svg>
630
- <script>
631
- const data = `,`;
632
- const svg = document.getElementById('graph');
633
- const tooltip = document.getElementById('tooltip');
634
- const W = window.innerWidth, H = window.innerHeight;
635
-
636
- // Build adjacency
637
- const depMap = {}, rdepMap = {};
638
- data.nodes.forEach(n => { depMap[n.name] = []; rdepMap[n.name] = []; });
639
- data.edges.forEach(e => { depMap[e.source]?.push(e.target); rdepMap[e.target]?.push(e.source); });
640
-
641
- // Escape text for safe DOM insertion
642
- function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.textContent; }
643
-
644
- // Force-directed layout
645
- const repulsion = 5000 + data.nodes.length * 150;
646
- const nodes = data.nodes.map(n => ({
647
- ...n, x: W/2 + (Math.random()-0.5)*Math.min(W*0.6, 600),
648
- y: H/2 + (Math.random()-0.5)*Math.min(H*0.6, 400), vx: 0, vy: 0
649
- }));
650
- const nodeMap = new Map(nodes.map(n => [n.name, n]));
651
- const edges = data.edges.map(e => ({
652
- source: nodeMap.get(e.source), target: nodeMap.get(e.target), type: e.type
653
- }));
654
-
655
- for (let iter = 0; iter < 400; iter++) {
656
- for (let i = 0; i < nodes.length; i++) {
657
- for (let j = i+1; j < nodes.length; j++) {
658
- let dx = nodes[j].x - nodes[i].x, dy = nodes[j].y - nodes[i].y;
659
- let d = Math.sqrt(dx*dx + dy*dy) || 1;
660
- let f = repulsion / (d * d);
661
- nodes[i].vx -= dx/d * f; nodes[i].vy -= dy/d * f;
662
- nodes[j].vx += dx/d * f; nodes[j].vy += dy/d * f;
663
- }
664
- }
665
- edges.forEach(e => {
666
- if (!e.source || !e.target) {
667
- return;
668
- }
669
- let dx = e.target.x - e.source.x, dy = e.target.y - e.source.y;
670
- let d = Math.sqrt(dx*dx + dy*dy) || 1;
671
- let f = (d - 180) * 0.008;
672
- e.source.vx += dx/d * f; e.source.vy += dy/d * f;
673
- e.target.vx -= dx/d * f; e.target.vy -= dy/d * f;
674
- });
675
- nodes.forEach(n => {
676
- n.vx += (W/2 - n.x) * 0.001; n.vy += (H/2 - n.y) * 0.001;
677
- n.x += n.vx * 0.3; n.y += n.vy * 0.3;
678
- n.vx *= 0.75; n.vy *= 0.75;
679
- n.x = Math.max(80, Math.min(W-80, n.x));
680
- n.y = Math.max(40, Math.min(H-40, n.y));
681
- });
682
- }
683
-
684
- // Measure text widths
685
- const measure = document.createElementNS('http://www.w3.org/2000/svg','text');
686
- measure.setAttribute('font-size','12'); measure.setAttribute('font-weight','600');
687
- measure.setAttribute('font-family','system-ui');
688
- svg.appendChild(measure);
689
- const widths = {};
690
- nodes.forEach(n => { measure.textContent = n.name; widths[n.name] = measure.getComputedTextLength(); });
691
- svg.removeChild(measure);
692
-
693
- // Render edges
694
- edges.forEach(e => {
695
- if (!e.source || !e.target) {
696
- return;
697
- }
698
- const sw = (widths[e.source.name]||80)/2 + 12;
699
- const tw = (widths[e.target.name]||80)/2 + 12;
700
- const dx = e.target.x - e.source.x, dy = e.target.y - e.source.y;
701
- const d = Math.sqrt(dx*dx+dy*dy)||1;
702
- const x1 = e.source.x + dx/d*sw, y1 = e.source.y + dy/d*14;
703
- const x2 = e.target.x - dx/d*tw, y2 = e.target.y - dy/d*14;
704
- const line = document.createElementNS('http://www.w3.org/2000/svg','line');
705
- line.setAttribute('x1',x1); line.setAttribute('y1',y1);
706
- line.setAttribute('x2',x2); line.setAttribute('y2',y2);
707
- line.setAttribute('class','edge');
708
- const edgeColors = { implicit: '#475569', devDependency: '#888888', peerDependency: '#CC8800' };
709
- line.setAttribute('stroke', edgeColors[e.type] || '#64748b');
710
- line.setAttribute('stroke-width', '1.5');
711
- if (e.type === 'implicit' || e.type === 'peerDependency') {
712
- line.setAttribute('stroke-dasharray', '6,4');
713
- }
714
- if (e.type === 'devDependency') {
715
- line.setAttribute('stroke-dasharray', '3,3');
716
- }
717
- svg.appendChild(line);
718
- });
719
-
720
- // Render nodes
721
- nodes.forEach(n => {
722
- const w = (widths[n.name]||80) + 24;
723
- const h = 32;
724
- const isApp = n.type === 'application';
725
- const fill = isApp ? '#fbbf24' : '#38bdf8';
726
- const textFill = '#0f172a';
727
- const stroke = isApp ? '#f59e0b' : '#0284c7';
728
-
729
- const g = document.createElementNS('http://www.w3.org/2000/svg','g');
730
- g.setAttribute('class','node');
731
- g.setAttribute('transform','translate('+(n.x - w/2)+','+(n.y - h/2)+')');
732
- const rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
733
- rect.setAttribute('width', w); rect.setAttribute('height', h);
734
- rect.setAttribute('fill', fill); rect.setAttribute('stroke', stroke); rect.setAttribute('stroke-width','1.5');
735
- g.appendChild(rect);
736
- const text = document.createElementNS('http://www.w3.org/2000/svg','text');
737
- text.setAttribute('x', w/2); text.setAttribute('y', h/2 + 4.5);
738
- text.setAttribute('text-anchor','middle'); text.setAttribute('fill', textFill);
739
- text.textContent = n.name;
740
- g.appendChild(text);
741
-
742
- g.addEventListener('mouseenter', (ev) => {
743
- const deps = depMap[n.name] || [];
744
- const rdeps = rdepMap[n.name] || [];
745
-
746
- // Build tooltip using safe DOM methods
747
- tooltip.textContent = '';
748
-
749
- const heading = document.createElement('h3');
750
- heading.textContent = n.name;
751
- const badge = document.createElement('span');
752
- badge.className = 'type-badge';
753
- badge.style.background = fill;
754
- badge.style.color = '#0f172a';
755
- badge.textContent = n.type;
756
- heading.appendChild(badge);
757
- tooltip.appendChild(heading);
758
-
759
- if (deps.length) {
760
- const label = document.createElement('div');
761
- label.className = 'dep-section';
762
- label.textContent = 'Depends on:';
763
- tooltip.appendChild(label);
764
- const ul = document.createElement('ul');
765
- deps.forEach(d => { const li = document.createElement('li'); li.textContent = d; ul.appendChild(li); });
766
- tooltip.appendChild(ul);
767
- }
768
- if (rdeps.length) {
769
- const label = document.createElement('div');
770
- label.className = 'dep-section';
771
- label.textContent = 'Required by:';
772
- tooltip.appendChild(label);
773
- const ul = document.createElement('ul');
774
- rdeps.forEach(d => { const li = document.createElement('li'); li.textContent = d; ul.appendChild(li); });
775
- tooltip.appendChild(ul);
776
- }
777
- if (!deps.length && !rdeps.length) {
778
- const empty = document.createElement('div');
779
- empty.style.marginTop = '6px';
780
- empty.style.color = '#64748b';
781
- empty.textContent = 'No dependencies';
782
- tooltip.appendChild(empty);
783
- }
784
-
785
- tooltip.style.display = 'block';
786
- const rect = tooltip.getBoundingClientRect();
787
- tooltip.style.left = Math.min(ev.clientX + 12, W - rect.width - 12) + 'px';
788
- tooltip.style.top = Math.min(ev.clientY + 12, H - rect.height - 12) + 'px';
789
- });
790
- g.addEventListener('mouseleave', () => { tooltip.style.display = 'none'; });
791
- svg.appendChild(g);
792
- });
793
- <\/script>
794
- </body>
795
- </html>`])),i.apps,i.libs,i.edges.length,JSON.stringify(i).replaceAll("</",String.raw`<\/`))},"projectGraphToHtml"),Jx={description:"Visualize the project dependency graph",examples:[["vis graph","Show colored dependency graph (TUI in TTY, ASCII otherwise)"],["vis graph --format=ascii","Force ASCII tree output"],["vis graph --format=dot","Output in Graphviz DOT format"],["vis graph --format=html --output=graph.html","Generate interactive HTML graph"],["vis graph --format=json --output=graph.json","Save JSON graph to file"]],execute:gn(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!n)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const o=n,{packageJsons:i,workspace:s}=mt(o,r),a=nr(o,s,i),c=!!process.stdout.isTTY&&!ft,d=t.format??(c?"tui":"ascii"),p=t.output,g=t.depth??1/0;let h;switch(d){case"dot":{h=mp(a);break}case"html":{h=qx(a);break}case"json":{h=JSON.stringify(zx(a),void 0,2);break}case"tui":{if(!c){h=cc(a,g);break}const y=r?.tui?.autoExit===!0?3:typeof r?.tui?.autoExit=="number"?r.tui.autoExit:0;process.stdin.isTTY&&typeof process.stdin.setRawMode=="function"&&(process.stdin.setRawMode(!0),process.stdin.ref(),process.stdin.resume());const w=setInterval(()=>{},1e3),k=new Ox(a);await Xt(Q.createElement(Gx,{autoExitSeconds:y,store:k}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit(),clearInterval(w);return}default:h=cc(a,g)}p?(me(p,h,"utf8"),e.info(`Graph written to ${p}`)):e.info(h)},"execute"),group:"Workspace",name:"graph",options:[{alias:"f",defaultValue:void 0,description:"Output format: tui, ascii, dot, json, html (default: tui in TTY, ascii otherwise)",name:"format",type:String},{alias:"o",description:"Write output to file instead of stdout",name:"output",type:String},{alias:"d",description:"Maximum dependency tree depth for ASCII output (default: unlimited)",name:"depth",type:Number}]},ni=["pre-commit","pre-merge-commit","prepare-commit-msg","commit-msg","post-commit","applypatch-msg","pre-applypatch","post-applypatch","pre-rebase","post-rewrite","post-checkout","post-merge","pre-push","pre-auto-gc"],oi=".vis-hooks",Yx=[".pre-commit-config.yaml",".pre-commit-config.yml","prek.toml"],Kx={commit:"pre-commit","merge-commit":"pre-merge-commit",push:"pre-push"},Xx=new Set(["commit-msg","post-checkout","post-commit","post-merge","post-rewrite","pre-commit","pre-merge-commit","pre-push","pre-rebase","prepare-commit-msg"]),Qx=new Set(["commit-msg","post-checkout","post-merge","post-rewrite","pre-rebase","prepare-commit-msg"]),Zx=new Set(["fail","script","system"]);var e0=Object.defineProperty,Io=b((e,t)=>e0(e,"name",{value:t,configurable:!0}),"o$a");const t0=/\/$/,r0=Io(e=>{let t='"$0"';for(let r=0;r<e;r+=1)t=`"$(dirname ${t})"`;return t},"nestedDirname"),n0=Io(e=>{const t=e.split("/").filter(r=>r!==""&&r!==".").length+2;return`#!/usr/bin/env sh
796
- { [ "$VIS_GIT_HOOKS" = "2" ]; } && set -x
797
- n=$(basename "$0")
798
- s=$(dirname "$(dirname "$0")")/$n
799
-
800
- [ ! -f "$s" ] && exit 0
801
-
802
- { [ "\${VIS_GIT_HOOKS-}" = "0" ]; } && exit 0
803
-
804
- d=${r0(t)}
805
- export PATH="$d/node_modules/.bin:$PATH"
806
- sh -e "$s" "$@"
807
- c=$?
808
-
809
- [ $c != 0 ] && echo "vis - $n script failed (code $c)"
810
- [ $c = 127 ] && echo "vis - command not found in PATH=$PATH"
811
- exit $c`},"hookScript"),Ps=Io((e=oi)=>{if(process.env.VIS_GIT_HOOKS==="0")return{isError:!1,message:"skip install (git hooks disabled via VIS_GIT_HOOKS=0)"};if(e.includes(".."))return{isError:!0,message:'".." is not allowed in hooks directory path'};const t=De("git",["rev-parse","--show-prefix"]);if(t.status===void 0||t.status===null)return{isError:!0,message:"git command not found"};if(t.status!==0)return{isError:!1,message:".git directory not found (not a git repository)"};const r=Io((d="")=>v(e,"_",d),"internal"),n=t.stdout.toString().trim().replace(t0,""),o=n?`${n}/${e}/_`:`${e}/_`,i=De("git",["config","--local","core.hooksPath"]),s=i.status===0?i.stdout?.toString().trim():"";if(s&&s!==o)return{isError:!1,message:`core.hooksPath is already set to "${s}", skipping`};const{status:a,stderr:c}=De("git",["config","core.hooksPath",o]);if(a==null)return{isError:!0,message:"git command not found"};if(a)return{isError:!0,message:String(c)};Se(r()),me(r(".gitignore"),"*"),me(r("h"),n0(e),{mode:493});for(const d of ni)me(r(d),`#!/usr/bin/env sh
812
- . "$(dirname "$0")/h"`,{mode:493});return{isError:!1,message:""}},"installHooks");var o0=Object.defineProperty,ii=b((e,t)=>o0(e,"name",{value:t,configurable:!0}),"c$m");const i0=/^# ([^:\s]\S*)(?::\s+(.+))?$/,s0=ii(e=>{const t=[],r=e.split(`
813
- `);let n;for(const o of r){if(o.startsWith("#!")||o.startsWith("# Generated by")||o.startsWith("# NOTE:")||o==="set -e"||o==="")continue;const i=i0.exec(o);if(i){n&&t.push(n),n={command:"",id:i[1]??"",...i[2]?{name:i[2]}:{}};continue}n?n.command=n.command.length>0?`${n.command}
814
- ${o}`:o:n={command:o,id:"(custom)"}}return n&&t.push(n),t},"parseStageScript"),a0=ii((e,t)=>{const r=v(e,t),n=[],o=new Set(ni);if(E(r))for(const i of Ve(r)){if(i.startsWith(".")||i==="_"||!o.has(i))continue;const s=v(r,i);if(!Mt(s).isFile())continue;const a=q(s),c=s0(a);n.push({blocks:c,rawLineCount:a.split(`
815
- `).length,stage:i})}return n.sort((i,s)=>i.stage.localeCompare(s.stage)),{hooksDirectory:t,stages:n}},"listHooks"),c0=ii(e=>{const t=[];if(e.stages.length===0)return t.push(`No hooks installed in ${e.hooksDirectory}/.`),t;t.push(`Hooks in ${e.hooksDirectory}/:`);for(const r of e.stages)if(t.push("",`${r.stage} (${r.rawLineCount} lines)`),r.blocks.length===0)t.push(" (empty)");else for(const n of r.blocks){const o=n.name?`${n.id} — ${n.name}`:n.id;t.push(` - ${o}`);const i=n.command.split(`
816
- `).find(s=>s.trim()!=="");if(i){const s=i.length>120?`${i.slice(0,117)}...`:i;t.push(` ${s}`)}}return t},"formatListResult"),l0=ii((e,t)=>{const r=a0(on(),e);for(const n of c0(r))t.info(n)},"runList");var d0=Object.defineProperty,u0=b((e,t)=>d0(e,"name",{value:t,configurable:!0}),"t$d");const eu=[".lintstagedrc.json",".lintstagedrc"],tu=[".lintstagedrc.yaml",".lintstagedrc.yml",".lintstagedrc.mjs","lint-staged.config.mjs",".lintstagedrc.cjs","lint-staged.config.cjs",".lintstagedrc.js","lint-staged.config.js",".lintstagedrc.ts","lint-staged.config.ts",".lintstagedrc.mts","lint-staged.config.mts",".lintstagedrc.cts","lint-staged.config.cts"],Ns=[...eu,...tu],p0=[/^((?:[A-Z_][A-Z0-9_]*(?:=\S*)?\s+)*)(pnpm|pnpm exec|npx|yarn|yarn run|npm exec|npm run|bunx|bun run|bun x)\s+lint-staged\b/,/^((?:[A-Z_][A-Z0-9_]*(?:=\S*)?\s+)*)lint-staged\b/],ru=[".nano-staged.json",".nanostagedrc"],nu=[".nano-staged.mjs",".nano-staged.cjs",".nano-staged.js","nano-staged.config.mjs","nano-staged.config.cjs","nano-staged.config.js","nano-staged.config.mts","nano-staged.config.cts","nano-staged.config.ts"],Ms=[...ru,...nu],f0=[/^((?:[A-Z_][A-Z0-9_]*(?:=\S*)?\s+)*)(pnpm|pnpm exec|npx|yarn|yarn run|npm exec|npm run|bunx|bun run|bun x)\s+nano-staged\b/,/^((?:[A-Z_][A-Z0-9_]*(?:=\S*)?\s+)*)nano-staged\b/],g0=["husky","lint-staged","nano-staged"],m0=/\(is-ci \|\| husky \|\| exit 0\)\s*&&\s*/g,h0=/\bhusky(?:\s+install)?\s*&&\s*/g,y0=/\s*&&\s*husky(?:\s+install)?/g,v0=/\s*\|\|\s*husky(?:\s+install)?/g,w0=[m0,h0,y0,v0],ou=u0(e=>{if(e==="husky"||e==="husky install")return;let t=e;for(const r of w0)t=t.replace(r,"");return t=t.trim(),t===e?e:t||void 0},"cleanHuskyFromScript");var k0=Object.defineProperty,wr=b((e,t)=>k0(e,"name",{value:t,configurable:!0}),"u$e");const b0=[".husky",".config/husky"],$0=/^\. "\$\(dirname "\$0"\)\/common\.sh"\s*/m,Ds=wr(e=>{for(const t of b0)if(E(v(e,t))&&Mt(v(e,t)).isDirectory())return t},"detectHuskyDirectory"),x0=wr((e,t)=>{const r=new Map,n=v(e,t),o=new Set(ni);for(const i of Ve(n)){if(i==="_"||i===".gitignore"||i.startsWith("."))continue;const s=v(n,i);Mt(s).isFile()&&(!o.has(i)&&i!=="common.sh"||r.set(i,q(s)))}return r},"readHuskyHooks"),S0=wr(e=>e.replace($0,""),"transformHookScript"),iu=wr(e=>E(v(e,"pnpm-lock.yaml"))||E(v(e,"pnpm-workspace.yaml"))?"pnpm":E(v(e,"yarn.lock"))?"yarn":E(v(e,"bun.lockb"))||E(v(e,"bun.lock"))?"bun":"npm","detectPackageManager"),C0=wr((e,t)=>{const r=iu(e),n={bun:["bun","remove","husky"],npm:["npm","uninstall","husky"],pnpm:["pnpm","remove","husky"],yarn:["yarn","remove","husky"]},[o,...i]=n[r];t.info(`Removing husky package via ${r}...`);const s=De(o,i,{cwd:e,encoding:"utf8",stdio:"pipe"});return s.status!==0?(t.info(`Warning: failed to remove husky via ${r} (${s.stderr?.trim()??"unknown error"})`),!1):!0},"uninstallHuskyPackage"),j0=wr((e,t,r)=>{const n=ou(r);if(n!==r)return n?(e[t]=n,`updated "${t}" script`):(delete e[t],`removed "${t}" script (was: "${r}")`)},"processScript"),E0=wr(e=>{const t=v(e,"package.json");if(!E(t))return{modified:!1,removedScriptReferences:[]};const r=q(t),n=JSON.parse(r),o=[],i=n.scripts;if(i)for(const[s,a]of Object.entries(i)){if(typeof a!="string")continue;const c=j0(i,s,a);c&&o.push(c)}return o.length>0&&me(t,`${JSON.stringify(n,void 0,4)}
817
- `,"utf8"),{modified:o.length>0,removedScriptReferences:o}},"cleanPackageJsonScripts"),su=wr((e,t,r,n={})=>{const o=Ds(e),i=n.dryRun===!0;if(!o)return{isError:!0,message:"No husky installation found (.husky/ or .config/husky/)"};r.info(`Found husky at ${o}/`);const s=x0(e,o);if(s.size===0&&r.info("No user-defined hooks found in husky directory."),!i){const d=De("git",["config","--local","core.hooksPath"]),p=d.status===0?d.stdout?.toString().trim():"";p&&(p===".husky/_"||p.startsWith(".husky"))&&De("git",["config","--local","--unset","core.hooksPath"]);const g=Ps(t);if(g.isError)return g;g.message&&r.info(g.message)}const a=v(e,t);i||Se(a);let c=0;for(const[d,p]of s){if(d==="common.sh"){i?r.info(" (would copy) common.sh"):(me(v(a,d),p,{mode:493}),r.info(" Copied common.sh"));continue}if(i)r.info(` (would migrate) ${d}`);else{const g=S0(p);me(v(a,d),g,{mode:493}),r.info(` Migrated ${d}`)}c+=1}if(i)r.info(" (would remove) husky npm package and clean package.json scripts"),r.info(` (would remove) ${o}/ directory`);else{C0(e,r);const d=E0(e);if(d.modified){r.info("Updated package.json scripts:");for(const g of d.removedScriptReferences)r.info(` ${g}`)}const p=v(e,o);at(p,{force:!0,recursive:!0}),r.info(`Removed ${o}/`)}return{isError:!1,message:`${i?"would migrate":"Migration complete:"} ${c} hook${c===1?"":"s"} ${i?"from":"migrated from"} ${o}/ to ${t}/`}},"migrateFromHusky"),cr="prek-runner.mjs",T0={css:["css","scss","sass","less"],dockerfile:["dockerfile"],html:["htm","html"],javascript:["cjs","js","jsx","mjs"],json:["json"],jsx:["jsx","tsx"],makefile:["mk","makefile"],markdown:["markdown","md","mdown","mdx"],python:["py","pyi","pyw"],python3:["py","pyi","pyw"],ruby:["rb"],rust:["rs"],shell:["bash","sh","zsh"],sql:["sql"],svg:["svg"],systemd:["service","socket","timer"],toml:["toml"],tsx:["tsx"],typescript:["cts","mts","ts","tsx"],xml:["xml"],yaml:["yaml","yml"]},R0=["binary","directory","executable","non-executable","symlink","text"],A0={bash:["bash","shell"],node:["javascript"],nodejs:["javascript"],perl:["perl"],python:["python"],python3:["python","python3"],ruby:["ruby"],sh:["shell"],zsh:["shell","zsh"]},I0=["check-json","check-merge-conflict","end-of-file-fixer","mixed-line-ending","trailing-whitespace"],O0=[...Object.keys(T0),...Object.values(A0).flat(),...R0],P0=["#!/usr/bin/env node","// Auto-generated by `vis hook migrate`. Do not edit by hand.","// Replicates the subset of prek / pre-commit framework semantics that a vis","// hook script needs: staged-file discovery, regex + type filters, chunked","// argv dispatch, and a handful of built-in hook implementations.","","import { spawnSync } from 'node:child_process';","import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';","import { basename, extname, join } from 'node:path';","import process from 'node:process';","","const TYPES_EXTENSION_MAP = {"," css: ['css', 'scss', 'sass', 'less'],"," dockerfile: ['dockerfile'],"," html: ['htm', 'html'],"," javascript: ['cjs', 'js', 'jsx', 'mjs'],"," json: ['json'],"," jsx: ['jsx', 'tsx'],"," makefile: ['mk', 'makefile'],"," markdown: ['markdown', 'md', 'mdown', 'mdx'],"," python: ['py', 'pyi', 'pyw'],"," python3: ['py', 'pyi', 'pyw'],"," ruby: ['rb'],"," rust: ['rs'],"," shell: ['bash', 'sh', 'zsh'],"," sql: ['sql'],"," svg: ['svg'],"," systemd: ['service', 'socket', 'timer'],"," toml: ['toml'],"," tsx: ['tsx'],"," typescript: ['cts', 'mts', 'ts', 'tsx'],"," xml: ['xml'],"," yaml: ['yaml', 'yml'],","};","","const FILENAME_TYPE_MAP = {"," dockerfile: 'dockerfile',"," makefile: 'makefile',"," 'gnumakefile': 'makefile',","};","","const SHEBANG_INTERPRETER_MAP = {"," bash: ['bash', 'shell'],"," node: ['javascript'],"," nodejs: ['javascript'],"," perl: ['perl'],"," python: ['python'],"," python3: ['python', 'python3'],"," ruby: ['ruby'],"," sh: ['shell'],"," zsh: ['shell', 'zsh'],","};","","const BUILTINS = {"," 'check-json': runCheckJson,"," 'check-merge-conflict': runCheckMergeConflict,"," 'end-of-file-fixer': runEndOfFileFixer,"," 'mixed-line-ending': runMixedLineEnding,"," 'trailing-whitespace': runTrailingWhitespace,","};","","const parseArgs = (argv) => {"," const flags = {"," allFiles: process.env.VIS_HOOK_ALL_FILES === '1',"," alwaysRun: false,"," builtin: null,"," exclude: null,"," excludeTypes: [],"," files: null,"," fromRef: process.env.VIS_HOOK_FROM_REF || null,"," passFilenames: true,"," toRef: process.env.VIS_HOOK_TO_REF || null,"," types: [],"," typesOr: [],"," };"," const rest = [];"," let seenDoubleDash = false;",""," for (let i = 0; i < argv.length; i += 1) {"," const arg = argv[i];",""," if (seenDoubleDash) {"," rest.push(arg);"," continue;"," }",""," switch (arg) {"," case '--':"," seenDoubleDash = true;"," break;"," case '--all-files':"," flags.allFiles = true;"," break;"," case '--always-run':"," flags.alwaysRun = true;"," break;"," case '--builtin':"," i += 1;"," flags.builtin = argv[i];"," break;"," case '--exclude':"," i += 1;"," flags.exclude = argv[i];"," break;"," case '--from-ref':"," i += 1;"," flags.fromRef = argv[i];"," break;"," case '--to-ref':"," i += 1;"," flags.toRef = argv[i];"," break;"," case '--exclude-types':"," i += 1;"," flags.excludeTypes = (argv[i] || '').split(',').filter(Boolean);"," break;"," case '--files':"," i += 1;"," flags.files = argv[i];"," break;"," case '--no-pass-filenames':"," flags.passFilenames = false;"," break;"," case '--types':"," i += 1;"," flags.types = (argv[i] || '').split(',').filter(Boolean);"," break;"," case '--types-or':"," i += 1;"," flags.typesOr = (argv[i] || '').split(',').filter(Boolean);"," break;"," default:"," process.stderr.write('prek-runner: unknown flag ' + arg + '\\n');"," process.exit(2);"," }"," }",""," return { flags, rest };","};","","const gitListFiles = (args, errorHint) => {"," const result = spawnSync('git', args, { encoding: 'buffer' });"," if (result.status !== 0) {"," process.stderr.write('prek-runner: git ' + errorHint + ' failed\\n');"," process.stderr.write(result.stderr ? result.stderr.toString() : '');"," process.exit(result.status === null ? 1 : result.status);"," }"," const raw = result.stdout.toString('utf8');"," if (raw.length === 0) { return []; }"," return raw.split('\\0').filter(function (f) { return f.length > 0; });","};","","const discoverFiles = (flags) => {"," if (flags.allFiles) {"," return gitListFiles(['ls-files', '-z'], 'ls-files');"," }"," if (flags.fromRef && flags.toRef) {"," return gitListFiles("," ['diff', '--name-only', '--diff-filter=ACM', '-z', flags.fromRef, flags.toRef],"," 'diff --from-ref/--to-ref'"," );"," }"," return gitListFiles(['diff', '--cached', '--name-only', '--diff-filter=ACM', '-z'], 'diff --cached');","};","","const buildRegex = (pattern) => {"," try {"," return new RegExp(pattern);"," } catch (error) {"," process.stderr.write('prek-runner: invalid regex ' + JSON.stringify(pattern) + ': ' + error.message + '\\n');"," process.exit(2);"," }","};","","const readShebang = (file) => {"," try {"," const fd = readFileSync(file, { encoding: null });"," if (fd.length < 2 || fd[0] !== 0x23 || fd[1] !== 0x21) { return null; }"," const nl = fd.indexOf(0x0a);"," const end = nl === -1 ? Math.min(fd.length, 256) : Math.min(nl, 256);"," return fd.slice(2, end).toString('utf8').trim();"," } catch (error) {"," return null;"," }","};","","const interpreterFromShebang = (shebang) => {"," if (!shebang) { return null; }"," const parts = shebang.split(/\\s+/).filter(Boolean);"," if (parts.length === 0) { return null; }"," const first = parts[0];"," let candidate = basename(first);"," if (candidate === 'env' && parts.length > 1) {"," candidate = basename(parts[1].split('=')[0] || parts[1]);"," }"," return candidate.toLowerCase();","};","","const fileMetadataTags = (file) => {"," const tags = new Set();"," let info;"," try { info = statSync(file, { throwIfNoEntry: false }); } catch (error) { info = null; }"," if (!info) { return tags; }"," if (info.isSymbolicLink()) { tags.add('symlink'); }"," if (info.isDirectory()) { tags.add('directory'); }"," if (info.isFile()) {"," if ((info.mode & 0o111) !== 0) { tags.add('executable'); } else { tags.add('non-executable'); }"," }"," return tags;","};","","const isBinaryFile = (file) => {"," try {"," const buf = readFileSync(file);"," const slice = buf.subarray(0, Math.min(buf.length, 8192));"," for (let i = 0; i < slice.length; i += 1) {"," if (slice[i] === 0) { return true; }"," }"," return false;"," } catch (error) {"," return false;"," }","};","","const typesForFile = (file) => {"," const tags = new Set();"," const baseName = basename(file).toLowerCase();"," const ext = extname(file).slice(1).toLowerCase();",""," if (baseName in FILENAME_TYPE_MAP) {"," tags.add(FILENAME_TYPE_MAP[baseName]);"," }",""," for (const [type, extensions] of Object.entries(TYPES_EXTENSION_MAP)) {"," if (extensions.includes(ext) || extensions.includes(baseName)) {"," tags.add(type);"," }"," }",""," const metaTags = fileMetadataTags(file);"," for (const tag of metaTags) { tags.add(tag); }",""," if (tags.size === 0 || tags.has('executable') || tags.has('shell')) {"," const interpreter = interpreterFromShebang(readShebang(file));"," if (interpreter) {"," const interpreterTags = SHEBANG_INTERPRETER_MAP[interpreter];"," if (interpreterTags) {"," for (const tag of interpreterTags) { tags.add(tag); }"," }"," }"," }",""," if (!tags.has('symlink') && !tags.has('directory')) {"," tags.add(isBinaryFile(file) ? 'binary' : 'text');"," }",""," return tags;","};","","const applyFilters = (files, flags) => {"," let filtered = files;",""," if (flags.files) {"," const rx = buildRegex(flags.files);"," filtered = filtered.filter(function (f) { return rx.test(f); });"," }",""," if (flags.exclude) {"," const rx = buildRegex(flags.exclude);"," filtered = filtered.filter(function (f) { return !rx.test(f); });"," }",""," if (flags.types.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return flags.types.every(function (t) { return tags.has(t); });"," });"," }",""," if (flags.typesOr.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return flags.typesOr.some(function (t) { return tags.has(t); });"," });"," }",""," if (flags.excludeTypes.length > 0) {"," filtered = filtered.filter(function (f) {"," const tags = typesForFile(f);"," return !flags.excludeTypes.some(function (t) { return tags.has(t); });"," });"," }",""," return filtered;","};","","// Conservative per-call argv budget. POSIX guarantees 4 KiB, Linux gives ~2 MiB","// in practice. 32 KiB keeps us well clear of Windows' 32767-char limit too.","const ARG_BUDGET = 32 * 1024;","","const chunkFiles = (files) => {"," const chunks = [];"," let current = [];"," let size = 0;",""," for (const file of files) {"," const cost = Buffer.byteLength(file, 'utf8') + 8;",""," if (size + cost > ARG_BUDGET && current.length > 0) {"," chunks.push(current);"," current = [];"," size = 0;"," }",""," current.push(file);"," size += cost;"," }",""," if (current.length > 0) {"," chunks.push(current);"," }",""," return chunks;","};","","const runCommand = (cmd, files, passFilenames) => {"," if (!cmd || cmd.length === 0) {"," process.stderr.write('prek-runner: no command specified after --\\n');"," return 2;"," }",""," const bin = cmd[0];"," const baseArgs = cmd.slice(1);",""," if (!passFilenames) {"," const result = spawnSync(bin, baseArgs, { stdio: 'inherit' });"," return result.status === null ? 1 : result.status;"," }",""," let rc = 0;"," const chunks = files.length === 0 ? [[]] : chunkFiles(files);",""," for (const chunk of chunks) {"," const result = spawnSync(bin, baseArgs.concat(chunk), { stdio: 'inherit' });"," rc = rc | (result.status === null ? 1 : result.status);"," }",""," return rc;","};","","// ─── Built-in hook implementations ──────────────────────────────────","// Each receives the already-filtered file list and returns an exit code.","","function runTrailingWhitespace(files) {"," // Mirrors pre-commit/pre-commit-hooks/trailing_whitespace_fixer.py:"," // strip trailing whitespace from each line, preserve original endings,"," // preserve markdown hard-break trailing two-spaces on non-blank lines."," const WS = new Set([0x20, 0x09, 0x0b, 0x0c, 0x0d]); // SP, TAB, VT, FF, CR"," const MD_RE = /\\.(md|markdown|mdown|mdx)$/i;"," let rc = 0;",""," for (const file of files) {"," const isMarkdown = MD_RE.test(file);"," const buf = readFileSync(file);"," const out = [];"," let i = 0;",""," while (i <= buf.length) {"," let end = i;",""," while (end < buf.length && buf[end] !== 0x0a) {"," end += 1;"," }",""," const hadLf = end < buf.length && buf[end] === 0x0a;"," let contentEnd = end;"," let hadCr = false;",""," if (hadLf && end > i && buf[end - 1] === 0x0d) {"," hadCr = true;"," contentEnd = end - 1;"," }",""," const content = buf.subarray(i, contentEnd);"," let stripEnd = content.length;",""," while (stripEnd > 0 && WS.has(content[stripEnd - 1])) {"," stripEnd -= 1;"," }",""," const nonWhitespace = content.some(function (b) { return !WS.has(b); });",""," if (isMarkdown && content.length >= 2 && content[content.length - 1] === 0x20 && content[content.length - 2] === 0x20 && nonWhitespace) {"," stripEnd = Math.min(stripEnd + 2, content.length);"," }",""," out.push(content.subarray(0, stripEnd));",""," if (hadCr) {"," out.push(Buffer.from([0x0d]));"," }",""," if (hadLf) {"," out.push(Buffer.from([0x0a]));"," }",""," if (!hadLf) {"," break;"," }",""," i = end + 1;"," }",""," const next = Buffer.concat(out);",""," if (!next.equals(buf)) {"," writeFileSync(file, next);"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," }"," }",""," return rc;","}","","function runEndOfFileFixer(files) {"," // Mirrors pre-commit/pre-commit-hooks/end_of_file_fixer.py: collapse"," // trailing \\n / \\r\\n / \\r runs to a single newline; add a newline if"," // missing; leave empty files alone."," let rc = 0;",""," for (const file of files) {"," const buf = readFileSync(file);",""," if (buf.length === 0) {"," continue;"," }",""," let end = buf.length;"," const last = buf[end - 1];",""," if (last !== 0x0a && last !== 0x0d) {"," writeFileSync(file, Buffer.concat([buf, Buffer.from([0x0a])]));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," continue;"," }",""," while (end > 0 && (buf[end - 1] === 0x0a || buf[end - 1] === 0x0d)) {"," end -= 1;"," }",""," if (end === 0) {"," writeFileSync(file, Buffer.alloc(0));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," continue;"," }",""," const trailing = buf.subarray(end);"," let keep;",""," if (trailing[0] === 0x0d && trailing[1] === 0x0a) {"," keep = Buffer.from([0x0d, 0x0a]);"," } else if (trailing[0] === 0x0d) {"," keep = Buffer.from([0x0d]);"," } else {"," keep = Buffer.from([0x0a]);"," }",""," if (trailing.equals(keep)) {"," continue;"," }",""," writeFileSync(file, Buffer.concat([buf.subarray(0, end), keep]));"," process.stdout.write('Fixing ' + file + '\\n');"," rc = 1;"," }",""," return rc;","}","","function isInMerge() {"," // Mirrors pre-commit/pre-commit-hooks/check_merge_conflict.py:is_in_merge."," const gitDirResult = spawnSync('git', ['rev-parse', '--git-dir'], { encoding: 'utf8' });"," if (gitDirResult.status !== 0) { return false; }"," const gitDir = gitDirResult.stdout.trim();"," if (!existsSync(join(gitDir, 'MERGE_MSG'))) { return false; }"," return existsSync(join(gitDir, 'MERGE_HEAD'))"," || existsSync(join(gitDir, 'rebase-apply'))"," || existsSync(join(gitDir, 'rebase-merge'));","}","","function runCheckMergeConflict(files, args) {"," // Mirrors pre-commit/pre-commit-hooks/check_merge_conflict.py: only"," // scans for conflict markers when git is mid-merge/rebase, unless the"," // caller passes --assume-in-merge. Skipping the guard means every"," // legit `<<<<<<<` in docs would fail the hook."," const assumeInMerge = Array.isArray(args) && args.includes('--assume-in-merge');"," if (!assumeInMerge && !isInMerge()) { return 0; }",""," const PATTERNS = ['<<<<<<< ', '======= ', '=======\\r\\n', '=======\\n', '>>>>>>> '];"," let rc = 0;",""," for (const file of files) {"," const content = readFileSync(file, 'utf8');"," const lines = content.split('\\n');",""," for (let i = 0; i < lines.length; i += 1) {"," const line = lines[i] + (i < lines.length - 1 ? '\\n' : '');",""," for (const pattern of PATTERNS) {"," if (line.startsWith(pattern)) {"," process.stdout.write(file + ':' + (i + 1) + ': Merge conflict string ' + JSON.stringify(pattern.trim()) + ' found\\n');"," rc = 1;"," }"," }"," }"," }",""," return rc;","}","","function runCheckJson(files) {"," // Mirrors pre-commit/pre-commit-hooks/check_json.py: parse each file"," // and additionally reject duplicate keys."," let rc = 0;",""," for (const file of files) {"," const content = readFileSync(file, 'utf8');",""," try {"," JSON.parse(content);"," detectDuplicateJsonKeys(content, file);"," } catch (error) {"," process.stdout.write(file + ': Failed to json decode (' + error.message + ')\\n');"," rc = 1;"," }"," }",""," return rc;","}","","function detectDuplicateJsonKeys(source, file) {"," // Minimal tokeniser that walks the already-valid JSON source and throws"," // with a message compatible with the Python hook when a duplicate key"," // appears at any object level."," let i = 0;"," const length = source.length;",""," const skipWs = function () {"," while (i < length && /\\s/.test(source[i])) {"," i += 1;"," }"," };",""," const parseString = function () {",` if (source[i] !== '"') {`," throw new Error('expected string at ' + i);"," }"," i += 1;"," let start = i;",` while (i < length && source[i] !== '"') {`," if (source[i] === '\\\\') {"," i += 2;"," } else {"," i += 1;"," }"," }"," const raw = source.slice(start, i);"," i += 1;",` return JSON.parse('"' + raw + '"');`," };",""," const parseValue = function () {"," skipWs();"," const ch = source[i];"," if (ch === '{') { parseObject(); }"," else if (ch === '[') { parseArray(); }",` else if (ch === '"') { parseString(); }`," else {"," while (i < length && ',}]'.indexOf(source[i]) === -1 && !/\\s/.test(source[i])) {"," i += 1;"," }"," }"," };",""," const parseArray = function () {"," i += 1;"," skipWs();"," if (source[i] === ']') { i += 1; return; }"," while (i < length) {"," parseValue();"," skipWs();"," if (source[i] === ',') { i += 1; skipWs(); }"," else if (source[i] === ']') { i += 1; return; }"," }"," };",""," const parseObject = function () {"," i += 1;"," skipWs();"," const seen = new Set();"," if (source[i] === '}') { i += 1; return; }"," while (i < length) {"," skipWs();"," const key = parseString();"," if (seen.has(key)) {"," throw new Error('Duplicate key: ' + key);"," }"," seen.add(key);"," skipWs();"," if (source[i] !== ':') {"," throw new Error('expected colon at ' + i);"," }"," i += 1;"," parseValue();"," skipWs();"," if (source[i] === ',') { i += 1; skipWs(); }"," else if (source[i] === '}') { i += 1; return; }"," }"," };",""," skipWs();"," parseValue();","}","","function runMixedLineEnding(files, args) {"," // Mirrors pre-commit/pre-commit-hooks/mixed_line_ending.py."," const ENDING = { cr: Buffer.from([0x0d]), crlf: Buffer.from([0x0d, 0x0a]), lf: Buffer.from([0x0a]) };"," let fixArg = 'auto';",""," for (let idx = 0; idx < args.length; idx += 1) {"," const a = args[idx];"," if (a === '-f' || a === '--fix') {"," idx += 1;"," fixArg = args[idx];"," } else if (a.indexOf('--fix=') === 0) {"," fixArg = a.slice('--fix='.length);"," }"," }",""," let rc = 0;",""," for (const file of files) {"," const buf = readFileSync(file);"," const counts = { cr: 0, crlf: 0, lf: 0 };"," const lines = [];"," let start = 0;",""," for (let i = 0; i < buf.length; i += 1) {"," const b = buf[i];",""," if (b === 0x0d && buf[i + 1] === 0x0a) {"," lines.push({ content: buf.subarray(start, i), ending: 'crlf' });"," counts.crlf += 1;"," i += 1;"," start = i + 1;"," } else if (b === 0x0d) {"," lines.push({ content: buf.subarray(start, i), ending: 'cr' });"," counts.cr += 1;"," start = i + 1;"," } else if (b === 0x0a) {"," lines.push({ content: buf.subarray(start, i), ending: 'lf' });"," counts.lf += 1;"," start = i + 1;"," }"," }",""," if (start < buf.length) {"," lines.push({ content: buf.subarray(start), ending: null });"," }",""," const distinct = Object.values(counts).filter(function (c) { return c > 0; }).length;"," const mixed = distinct > 1;",""," if (fixArg === 'no') {"," if (mixed) {"," process.stdout.write(file + ': mixed line endings\\n');"," rc = 1;"," }"," continue;"," }",""," let target;",""," if (fixArg === 'auto') {"," if (!mixed) { continue; }"," let max = -1;"," for (const key of ['cr', 'crlf', 'lf']) {"," if (counts[key] >= max) {"," max = counts[key];"," target = key;"," }"," }"," } else if (!(fixArg in ENDING)) {"," process.stderr.write('prek-runner: invalid --fix value ' + fixArg + '\\n');"," return 2;"," } else {"," target = fixArg;"," const other = Object.entries(counts).some(function (entry) { return entry[0] !== target && entry[1] > 0; });"," if (!other) { continue; }"," }",""," const ending = ENDING[target];"," const chunks = [];",""," for (const line of lines) {"," chunks.push(line.content);"," if (line.ending !== null) {"," chunks.push(ending);"," }"," }",""," writeFileSync(file, Buffer.concat(chunks));"," process.stdout.write(file + ': fixed mixed line endings\\n');"," rc = 1;"," }",""," return rc;","}","","// ─── Entry point ────────────────────────────────────────────────────","","const parsed = parseArgs(process.argv.slice(2));","const candidateFiles = discoverFiles(parsed.flags);","const filtered = applyFilters(candidateFiles, parsed.flags);","","if (filtered.length === 0 && !parsed.flags.alwaysRun) {"," process.exit(0);","}","","let code;","","if (parsed.flags.builtin) {"," const impl = BUILTINS[parsed.flags.builtin];"," if (!impl) {"," process.stderr.write('prek-runner: unknown builtin ' + parsed.flags.builtin + '\\n');"," process.exit(2);"," }"," code = impl(filtered, parsed.rest);","} else {"," code = runCommand(parsed.rest, filtered, parsed.flags.passFilenames);","}","","process.exit(code);",""],N0=P0.join(`
818
- `);var M0=Object.defineProperty,We=b((e,t)=>M0(e,"name",{value:t,configurable:!0}),"a$b");const D0=new Map([["pre-commit/pre-commit-hooks#check-json","check-json"],["pre-commit/pre-commit-hooks#check-merge-conflict","check-merge-conflict"],["pre-commit/pre-commit-hooks#end-of-file-fixer","end-of-file-fixer"],["pre-commit/pre-commit-hooks#mixed-line-ending","mixed-line-ending"],["pre-commit/pre-commit-hooks#trailing-whitespace","trailing-whitespace"]]),B0=/[<>=!~]=/,F0=/github\.com[/:]([^/\s]+\/[^/\s.]+)/i,au=`node "$(dirname "$0")/.builtins/${cr}"`,L0="# Generated by `vis hook migrate` from prek",Kt=We(e=>`'${e.replaceAll("'",String.raw`'\''`)}'`,"shellQuote"),Bs=We(e=>{for(const t of Yx)if(E(v(e,t)))return t},"detectPrekConfig"),V0=We(e=>Kx[e]??e,"mapPrekStage"),_0=We(e=>F0.exec(e)?.[1]??e,"normalizeRepoKey"),U0=We(e=>{if(B0.test(e))return;if(e.startsWith("@")){const n=e.indexOf("@",1);if(n===-1)return{name:e,version:"latest"};const o=e.slice(n+1).trim();return{name:e.slice(0,n),version:o||"latest"}}const t=e.indexOf("@");if(t===-1)return{name:e,version:"latest"};const r=e.slice(t+1).trim();return{name:e.slice(0,t),version:r||"latest"}},"parseAdditionalDep"),W0=new Set(O0),G0=We(e=>{const t=[];for(const r of[e.types,e.types_or,e.exclude_types])for(const n of r??[])W0.has(n)||t.push(n);return t},"unknownTypes"),H0=We((e,t)=>(e.stages&&e.stages.length>0?e.stages:t??["pre-commit"]).map(r=>V0(r)),"resolveStages"),z0=We(e=>{const t=[];return e.files&&t.push("--files",Kt(e.files)),e.exclude&&t.push("--exclude",Kt(e.exclude)),e.types&&e.types.length>0&&t.push("--types",Kt(e.types.join(","))),e.types_or&&e.types_or.length>0&&t.push("--types-or",Kt(e.types_or.join(","))),e.exclude_types&&e.exclude_types.length>0&&t.push("--exclude-types",Kt(e.exclude_types.join(","))),e.always_run&&t.push("--always-run"),e.pass_filenames===!1&&t.push("--no-pass-filenames"),t},"buildRunnerFilterFlags"),dc=We((e,t)=>{const r=[au,...z0(e)];if(t)return r.push("--builtin",t),Array.isArray(e.args)&&e.args.length>0&&r.push("--",...e.args.map(n=>Kt(n))),r.join(" ");if(r.push("--",e.entry??""),Array.isArray(e.args))for(const n of e.args)r.push(Kt(n));return r.join(" ")},"buildRunnerInvocation"),q0=We((e,t,r)=>{if(e.language==="fail"){const n=e.entry??e.name??e.id??"hook failed";return`echo ${Kt(n)}; exit 1`}if(r)return dc(e,r);if(Qx.has(t)){const n=[];if(e.entry&&n.push(e.entry),Array.isArray(e.args))for(const o of e.args)n.push(Kt(o));return(e.pass_filenames??!0)&&!e.always_run&&n.push('"$@"'),n.join(" ")}return dc(e)},"buildHookCommand"),J0=We((e,t,r,n)=>{if(Array.isArray(e.additional_dependencies))for(const o of e.additional_dependencies){const i=U0(o);if(!i){n.push(`"${t}": additional_dependency "${o}" uses a pip-style pin and cannot be added to package.json — install manually.`);continue}r.push({hookId:t,name:i.name,raw:o,version:i.version})}},"collectAdditionalDeps"),Y0=We(e=>{const t=new Map,r=[],n=[],o=[],i=[];let s=!1;(e.files||e.exclude)&&n.push("top-level files/exclude filter dropped — apply it per hook if needed");for(const c of e.repos??[]){const d=c.repo??"<unknown>",p=d==="local",g=p?void 0:_0(d);for(const h of c.hooks??[]){const y=h.id??"<unknown>";let w;if(p){const x=h.language??"system";if(!Zx.has(x)){r.push({hookId:y,reason:`language "${x}" needs an isolated toolchain — run via prek or reimplement as a system command`,repo:d});continue}if(x!=="fail"&&!h.entry){r.push({hookId:y,reason:"missing `entry`",repo:d});continue}}else if(g&&(w=D0.get(`${g}#${y}`)),!w){r.push({hookId:y,reason:`remote repo "${d}"@${c.rev??"?"} has no bundled equivalent — run via prek or replace with a system command`,repo:d});continue}J0(h,y,i,o);const k=G0(h);k.length>0&&n.push(`hook "${y}": unsupported types ${k.join(", ")} — those entries are ignored by the runner`);const $=H0(h,e.default_stages);for(const x of $){if(x==="manual")continue;if(!Xx.has(x)){r.push({hookId:y,reason:`unsupported stage "${x}"`,repo:d});continue}let T=q0(h,x,w);T.startsWith(au)&&(s=!0),h.verbose&&(T=`(set -x; ${T})`);const I=`${`# ${y}${h.name?`: ${h.name}`:""}`}
819
- ${T}`,P=t.get(x);P?P.push(I):t.set(x,[I])}}}const a=new Map;for(const[c,d]of t){const p=["#!/usr/bin/env sh",L0];e.fail_fast&&p.push("set -e"),p.push("",d.join(`
820
-
821
- `),""),a.set(c,p.join(`
822
- `))}return{additionalDeps:i,droppedFilters:n,manualSteps:o,scripts:a,skippedHooks:r,usesRunner:s}},"convertPrekConfig"),K0=We(e=>{const t=Kp(e);if(t&&typeof t=="object")return t},"parsePrekConfig"),X0=We(e=>{if(e.endsWith(".toml")){const r=Yp(e);return r&&typeof r=="object"?r:void 0}const t=q(e);return K0(t)},"loadPrekConfig"),Q0=We((e,t)=>{const r=v(e,"package.json"),n=[],o=[];if(!E(r)||t.length===0)return{added:n,skipped:o};const i=q(r),s=JSON.parse(i),a=s.devDependencies??{},c=s.dependencies??{};for(const g of t){if(g.name in a||g.name in c){o.push(g.name);continue}a[g.name]=g.version,n.push(g.name)}if(n.length===0)return{added:n,skipped:o};s.devDependencies=a;const d=/^(\s+)"/m.exec(i),p=d?d[1]:" ";return me(r,`${JSON.stringify(s,void 0,p)}
823
- `,"utf8"),{added:n,skipped:o}},"mergeAdditionalDependencies"),Z0=We((e,t)=>{const r=v(e,t,".builtins");Se(r),me(v(r,cr),N0,{mode:493}),me(v(r,"README.md"),["# Vis prek runner","","Auto-generated by `vis hook migrate` from a prek/pre-commit config.","This directory is owned by the migrator — do not edit by hand.","",`Supported built-in hooks: ${I0.join(", ")}`,""].join(`
824
- `),"utf8")},"writeRunnerAssets"),eS=We((e,t)=>{De("prek",["--version"],{cwd:e,encoding:"utf8"}).status===0?De("prek",["uninstall"],{cwd:e,encoding:"utf8"}).status===0?t.info("Detached prek via `prek uninstall`."):t.info("`prek uninstall` did not exit cleanly — continuing. You may need to run it manually."):t.info("prek binary not found on PATH — skipping `prek uninstall`. Run it manually if prek is installed elsewhere.")},"detachPrek"),cu=We((e,t,r,n={})=>{const o=Bs(e),i=n.dryRun===!0;if(!o)return{isError:!0,message:"No prek configuration found (.pre-commit-config.yaml, .pre-commit-config.yml, or prek.toml)"};r.info(`Found prek config at ${o}`);const s=v(e,o),a=q(s),c=X0(s);if(!c)return{isError:!0,message:`Could not parse ${o}`};const{additionalDeps:d,droppedFilters:p,manualSteps:g,scripts:h,skippedHooks:y,usesRunner:w}=Y0(c);if(h.size===0&&y.length===0)return{isError:!0,message:`${o} has no hooks to migrate`};if(!i){const P=De("git",["config","--local","core.hooksPath"],{cwd:e,encoding:"utf8"});if(P.status===0){const M=P.stdout?.toString().trim();M&&(M.includes(".prek")||M.includes("prek-hooks"))&&De("git",["config","--local","--unset","core.hooksPath"],{cwd:e})}const R=Ps(t);if(R.isError)return R;R.message&&r.info(R.message)}const k=v(e,t);i||Se(k),w&&(i?r.info(` (would write) ${t}/.builtins/${cr}`):(Z0(e,t),r.info(` Wrote ${t}/.builtins/${cr}`)));let $=0;for(const[P,R]of h)i?r.info(` (would write) ${t}/${P} (${R.split(`
825
- `).length} lines)`):(me(v(k,P),R,{mode:493}),r.info(` Wrote ${t}/${P}`)),$+=1;const{added:x,skipped:T}=i?{added:d.map(P=>P.name),skipped:[]}:Q0(e,d);if(x.length>0){const P=i?"would add":"Added";r.info(`${P} ${x.length} package${x.length===1?"":"s"} to devDependencies: ${x.join(", ")}`),i||r.info("Run your package manager's install (e.g. `pnpm install`) to pick up the new devDependencies.")}T.length>0&&r.info(`Skipped ${T.length} already-declared package${T.length===1?"":"s"}: ${T.join(", ")}`),i||eS(e,r);const I=`${s}.bak`;if(i?r.info(` (would remove) ${o} and back it up to ${o}.bak`):(E(I)||me(I,a,"utf8"),Dr(s),r.info(`Removed ${o} (backup at ${o}.bak)`)),y.length>0){r.warn(`Skipped ${y.length} hook${y.length===1?"":"s"} that cannot run without prek:`);for(const P of y)r.warn(` - ${P.repo}::${P.hookId} — ${P.reason}`)}if(p.length>0){r.warn("Partial filter translations:");for(const P of p)r.warn(` - ${P}`)}if(g.length>0){r.warn("Manual follow-up required:");for(const P of g)r.warn(` - ${P}`)}return{isError:!1,message:`${i?"would migrate":"Migration complete:"} ${$} stage script${$===1?"":"s"} ${i?"into":"written to"} ${t}/`}},"migrateFromPrek");var tS=Object.defineProperty,lu=b((e,t)=>tS(e,"name",{value:t,configurable:!0}),"a$a");const rS="pre-commit",nS=lu((e,t,r,n)=>{const o=r.stage??rS,i=v(e,t,o);if(!E(i))throw new Error(`No script found at ${t}/${o}. Install or migrate hooks first.`);if(r.lastCommit&&(r.fromRef||r.toRef))throw new Error("--last-commit cannot be combined with --from-ref or --to-ref");const s=r.lastCommit?"HEAD~1":r.fromRef,a=r.lastCommit?"HEAD":r.toRef;if(s&&!a)throw new Error("--from-ref requires --to-ref");if(a&&!s)throw new Error("--to-ref requires --from-ref");const c={...process.env};r.allFiles&&(c.VIS_HOOK_ALL_FILES="1"),s&&(c.VIS_HOOK_FROM_REF=s),a&&(c.VIS_HOOK_TO_REF=a),n.info(`Running ${t}/${o}${r.allFiles?" (--all-files)":""}${s?` (${s}..${a})`:""}`);const d=De("sh",["-e",i],{cwd:e,env:c,stdio:"inherit"});if(d.error)throw d.error;return d.status??1},"runHookStage"),oS=lu((e,t,r)=>{const n=nS(on(),e,t,r);if(n!==0)throw new Error(`Hook stage exited with code ${n}`)},"runRun");var iS=Object.defineProperty,sS=b((e,t)=>iS(e,"name",{value:t,configurable:!0}),"e$2");const aS=sS((e=oi)=>{if(De("git",["config","--local","core.hooksPath"]).status!==0)return{isError:!1,message:"No custom hooks path configured"};const{status:t,stderr:r}=De("git",["config","--local","--unset","core.hooksPath"]);if(t==null)return{isError:!0,message:"git command not found"};if(t&&t!==5)return{isError:!0,message:String(r)};const n=v(e,"_");return E(n)&&at(n,{force:!0,recursive:!0}),{isError:!1,message:""}},"uninstallHooks");var cS=Object.defineProperty,to=b((e,t)=>cS(e,"name",{value:t,configurable:!0}),"u$d");const lS=new Set(ni),dS=to(e=>{const t=De("sh",["-n",e],{encoding:"utf8"});if(t.status===null)return`failed to run "sh -n" (${t.error?.message??"unknown error"})`;if(t.status!==0)return t.stderr.trim()||`sh -n exited with ${t.status}`},"runSyntaxCheck"),uS=to(e=>{const t=De("node",["--check",e],{encoding:"utf8"});if(t.status===null)return`failed to run "node --check" (${t.error?.message??"unknown error"})`;if(t.status!==0)return t.stderr.trim()||`node --check exited with ${t.status}`},"runNodeCheck"),pS=to((e,t)=>{const r=[],n=v(e,t),o=De("git",["config","--local","core.hooksPath"],{cwd:e,encoding:"utf8"});if(o.status===0){const s=o.stdout.trim(),a=`${t}/_`;s&&s!==a&&r.push({kind:"warning",message:`core.hooksPath is "${s}" — expected "${a}". Re-run \`vis hook install\` to fix.`})}else r.push({kind:"warning",message:"core.hooksPath is not set — run `vis hook install`."});if(E(v(n,"_"))||r.push({kind:"error",message:`Dispatcher directory ${t}/_ is missing. Run \`vis hook install\`.`}),!E(n))return r.push({kind:"error",message:`Hooks directory ${t}/ is missing.`}),{issues:r,ok:!1};let i=!1;for(const s of Ve(n)){if(s.startsWith(".")||s==="_")continue;if(!lS.has(s)){r.push({kind:"warning",message:`Unknown hook "${s}" — not a standard git hook.`,path:v(t,s)});continue}const a=v(n,s);if(!Mt(a).isFile())continue;const c=Mt(a).mode&511;(c&64)===0&&r.push({kind:"warning",message:`Script is not owner-executable (mode ${c.toString(8)}).`,path:v(t,s)});const d=dS(a);d&&r.push({kind:"error",message:`Shell syntax error: ${d}`,path:v(t,s)}),q(a).includes(`/.builtins/${cr}`)&&(i=!0)}if(i){const s=v(n,".builtins",cr);if(E(s)){const a=uS(s);a&&r.push({kind:"error",message:`prek-runner.mjs has a syntax error: ${a}`,path:v(t,".builtins",cr)})}else r.push({kind:"error",message:`Hook scripts reference ${t}/.builtins/${cr} but the file is missing. Re-run \`vis hook migrate\`.`})}return{issues:r,ok:!r.some(s=>s.kind==="error")}},"validateHooks"),fS=to((e,t)=>{if(e.issues.length===0)return[`Hook directory ${t}/ looks good.`];const r=[];for(const n of e.issues){const o=n.kind==="error"?"ERROR":"WARN ",i=n.path?` (${n.path})`:"";r.push(`${o} ${n.message}${i}`)}return r.push("",e.ok?"No errors — warnings only.":`${e.issues.filter(n=>n.kind==="error").length} error(s).`),r},"formatValidationResult"),gS=to((e,t)=>{const r=pS(on(),e),n=fS(r,e);for(const o of n)o.startsWith("ERROR")||o.startsWith("WARN")?t.warn(o):t.info(o);if(!r.ok)throw new Error("Hook validation failed")},"runValidate");var mS=Object.defineProperty,dt=b((e,t)=>mS(e,"name",{value:t,configurable:!0}),"s$c");const Wr={defaultValue:oi,description:"Custom hooks directory",name:"hooks-dir",type:String},Gr=dt(e=>e.hooksDir??oi,"resolveHooksDirectory"),uc=dt(e=>new Promise(t=>{const r=gt({input:process.stdin,output:process.stdout});r.question(`${e} (y/N) `,n=>{r.close();const o=n.trim().toLowerCase();t(o==="y"||o==="yes")})}),"confirmPrompt"),hS=dt(async(e,t)=>{const r=on(),n=Ds(r),o=Bs(r);if(n&&o)throw new Error(`Found both husky (${n}/) and prek (${o}). Remove or migrate one before running \`vis hook install\`.`);if(n){if(t.info(`Existing husky installation found at ${n}/`),await uc("Would you like to migrate your husky hooks to vis?")){const s=su(r,e,t);if(s.isError)throw new Error(s.message);s.message&&t.info(s.message);return}t.info("Aborting install. Remove husky first or run 'vis hook migrate' to migrate.");return}if(o){if(t.info(`Existing prek configuration found at ${o}`),await uc("Would you like to migrate your prek hooks to vis?")){const s=cu(r,e,t);if(s.isError)throw new Error(s.message);s.message&&t.info(s.message);return}t.info("Aborting install. Remove the prek config first or run 'vis hook migrate' to migrate.");return}t.info(`Installing git hooks in ${e}/...`);const i=Ps(e);if(i.message){if(i.isError)throw new Error(i.message);t.info(i.message);return}E(v(r,e,"pre-commit"))||me(v(r,e,"pre-commit"),`#!/usr/bin/env sh
826
- `,{mode:493}),t.info("Git hooks installed successfully.")},"executeInstall"),yS=dt((e,t,r)=>{const n=on(),o=Ds(n),i=Bs(n);if(o&&i)throw new Error(`Found both husky (${o}/) and prek (${i}). Migrate one at a time — rename or remove one before retrying.`);if(!o&&!i)throw new Error("No husky (.husky/) or prek (.pre-commit-config.yaml / prek.toml) configuration found to migrate.");t&&r.info("(dry-run) no files will be written");const s=o?su(n,e,r,{dryRun:t}):cu(n,e,r,{dryRun:t});if(s.isError)throw new Error(s.message);s.message&&r.info(s.message)},"executeMigrate"),Vi="# vis:secrets-hook",vS=`#!/usr/bin/env sh
827
- ${Vi}
828
- # Scan staged files for secrets before each commit. Remove this block or the whole file to disable.
829
- pnpm exec vis secrets --staged --quiet || exit 1
830
- `,wS=dt((e,t,r)=>{if(e!=="secrets")throw new Error(`Unknown hook add target "${String(e)}". Currently supported: "secrets".`);const n=on(),o=v(n,t,"pre-commit");if(!E(v(n,t)))throw new Error(`Hooks directory ${t}/ does not exist. Run \`vis hook install\` first.`);if(E(o)){const i=q(o);if(i.includes(Vi)){r.info(`Secrets hook already present in ${o}.`);return}if(/\bvis secrets\b/.test(i)){r.warn(`Found a \`vis secrets\` invocation in ${o} without the managed marker — leaving it untouched.`);return}const s=`${i.trimEnd()}
831
-
832
- ${Vi}
833
- pnpm exec vis secrets --staged --quiet || exit 1
834
- `;me(o,s),rl(o,493),r.info(`Appended secrets scan to ${o}.`);return}me(o,vS,{mode:493}),r.info(`Created ${o} with a secrets-scan pre-commit check.`)},"executeAdd"),kS=dt((e,t)=>{t.info("Removing git hooks...");const r=aS(e);if(r.message){if(r.isError)throw new Error(r.message);t.info(r.message);return}t.info("Git hooks removed successfully.")},"executeUninstall"),Hr=[{defaultValue:void 0,description:"Set to 0 to disable git hooks, set to 2 for debug output",name:"VIS_GIT_HOOKS",type:String}],bS={commandPath:["hook"],description:"Install git hooks for the workspace (migrates husky / prek on prompt)",env:[...Hr],examples:[["vis hook install","Install git hooks in .vis-hooks/"],["vis hook install --hooks-dir=.githooks","Install hooks in a custom directory"]],execute:dt(async({logger:e,options:t})=>{await hS(Gr(t),e)},"execute"),group:"Scaffold & Config",name:"install",options:[Wr]},$S={commandPath:["hook"],description:"Remove git hooks and reset core.hooksPath",env:[...Hr],examples:[["vis hook uninstall","Remove git hooks and reset core.hooksPath"]],execute:dt(({logger:e,options:t})=>{kS(Gr(t),e)},"execute"),group:"Scaffold & Config",name:"uninstall",options:[Wr]},xS={commandPath:["hook"],description:"Migrate from husky or prek to vis hooks (auto-detected)",env:[...Hr],examples:[["vis hook migrate","Migrate from husky or prek to vis hooks (auto-detected)"],["vis hook migrate --dry-run","Preview what a migration would write without touching disk"]],execute:dt(({logger:e,options:t})=>{yS(Gr(t),!!t.dryRun,e)},"execute"),group:"Scaffold & Config",name:"migrate",options:[Wr,{defaultValue:!1,description:"Preview migrate without writing files",name:"dry-run",type:Boolean}]},SS={commandPath:["hook"],description:"Show configured hooks grouped by stage",env:[...Hr],examples:[["vis hook list","Show configured hooks grouped by stage"]],execute:dt(({logger:e,options:t})=>{l0(Gr(t),e)},"execute"),group:"Scaffold & Config",name:"list",options:[Wr]},CS={commandPath:["hook"],description:"Sanity-check installed hooks and the bundled runner",env:[...Hr],examples:[["vis hook validate","Sanity-check installed hooks and the bundled runner"]],execute:dt(({logger:e,options:t})=>{gS(Gr(t),e)},"execute"),group:"Scaffold & Config",name:"validate",options:[Wr]},jS={argument:{description:"Hook stage to run (e.g. pre-commit, commit-msg). Defaults to pre-commit.",name:"stage",type:String},commandPath:["hook"],description:"Run a specific hook stage against tracked files",env:[...Hr],examples:[["vis hook run pre-commit --all-files","Run the pre-commit hooks against every tracked file"],["vis hook run pre-commit --from-ref=main --to-ref=HEAD","Run pre-commit hooks on files changed between two refs"],["vis hook run pre-commit --last-commit","Shortcut for --from-ref HEAD~1 --to-ref HEAD"]],execute:dt(({argument:e,logger:t,options:r})=>{oS(Gr(r),{allFiles:!!r.allFiles,fromRef:r.fromRef,lastCommit:!!r.lastCommit,stage:e[0],toRef:r.toRef},t)},"execute"),group:"Scaffold & Config",name:"run",options:[Wr,{defaultValue:!1,description:"Run against every tracked file",name:"all-files",type:Boolean},{defaultValue:void 0,description:"Include files changed since this ref",name:"from-ref",type:String},{defaultValue:void 0,description:"Include files changed up to this ref",name:"to-ref",type:String},{defaultValue:!1,description:"Shortcut for --from-ref HEAD~1 --to-ref HEAD",name:"last-commit",type:Boolean}]},ES={argument:{description:"Target to add (currently: `secrets`)",name:"target",type:String},commandPath:["hook"],description:"Add a managed hook snippet (e.g. `vis secrets --staged`)",env:[...Hr],examples:[["vis hook add secrets","Add a pre-commit hook that runs `vis secrets --staged`"]],execute:dt(({argument:e,logger:t,options:r})=>{wS(e[0],Gr(r),t)},"execute"),group:"Scaffold & Config",name:"add",options:[Wr]},TS=[bS,$S,xS,SS,CS,jS,ES];var RS=Object.defineProperty,Et=b((e,t)=>RS(e,"name",{value:t,configurable:!0}),"t$b");const du=Xp(_p),AS=["[skip ci]","[ci skip]","[no ci]","[vis skip]","[nx skip]"],IS=["[vis deploy]","[nx deploy]"],OS=["vis","nx"],PS=["CACHED_COMMIT_REF","VERCEL_GIT_PREVIOUS_SHA","GITHUB_BASE_REF","CI_COMMIT_BEFORE_SHA"],NS=/^[\w./~^@{}][\w.\-/~^@{}]*$/,MS=Et((e=process.env)=>{for(const t of PS){const r=e[t];if(r&&r.trim().length>0)return r.trim()}},"resolveCiBaseSha"),pc=Et(e=>{if(!NS.test(e))throw new Error(`Invalid git ref: "${e}". Refs must start with an alphanumeric character or one of _ . / ~ ^ @ { } and may only contain letters, digits, dots, dashes, underscores, slashes, tildes, carets, @, and braces.`)},"validateGitRef"),DS=Et(async(e,t)=>{try{return await du("git",["rev-parse","--verify",`${t}^{commit}`],{cwd:e}),!0}catch{return!1}},"isRefReachable"),BS=Et(async e=>{try{const{stdout:t}=await du("git",["log","-1","--pretty=%B"],{cwd:e});return t}catch{return""}},"readLastCommitMessage"),uu=Et((e,t,r)=>OS.some(n=>e.includes(`[${n} ${t} ${r}]`)),"matchesPerProjectToken"),FS=Et((e,t)=>AS.some(r=>e.includes(r))||uu(e,"skip",t),"commitHasSkipMessage"),LS=Et((e,t)=>IS.some(r=>e.includes(r))||uu(e,"deploy",t),"commitHasForceDeployMessage"),jr=Et((e,t,r,n)=>({action:"build",message:r,project:e,reason:t,...n}),"decideBuild"),Ei=Et((e,t,r,n)=>({action:"skip",message:r,project:e,reason:t,...n}),"decideSkip"),VS=Et(e=>`${e.action==="skip"?"🛑":"✅"} ${e.message}`,"formatDecisionLine"),_S=Et((e,t)=>e.action==="skip"||t?0:1,"exitCodeFor");var US=Object.defineProperty,Ti=b((e,t)=>US(e,"name",{value:t,configurable:!0}),"u$b");const fc=new Set(["deep","direct","none"]),WS={argument:{description:"Project name to check (required)",name:"project",type:String},description:'Exit with inverted codes for CI "Ignored Build Step" gating (Vercel/Netlify)',examples:[["vis ignore my-app","Check if my-app is affected and decide whether to build"],["vis ignore my-app --base $VERCEL_GIT_PREVIOUS_SHA","Explicit base ref"],["vis ignore my-app --json","Emit the decision as JSON instead of text"],["vis ignore my-app --verbose","Print debug info about the decision path"],["vis ignore my-app --exit-zero-on-build","Normal exit semantics (0=build, 0=skip)"]],execute:Ti(async({argument:e,logger:t,options:r,visConfig:n,workspaceRoot:o})=>{const i=e[0]??"",s=!!r.json,a=!!r.verbose,c=!!r["exit-zero-on-build"],d=Ti(k=>{a&&!s&&t.info(`❱ ${k}`)},"debug"),p=Ti(k=>{s?process.stdout.write(`${JSON.stringify(k)}
835
- `):t.info(VS(k)),process.exit(_S(k,c))},"emit");if(!i)return p(jr("","missing-project-argument","Missing project argument. Usage: vis ignore <project>"));if(!o)return p(jr(i,"workspace-error","Could not determine workspace root — building defensively"));const g=await BS(o),h=g.trim().split(`
836
- `)[0]??"";if(d(`commit: ${h}`),g&&LS(g,i))return p(jr(i,"commit-force-deploy",`Force-deploy keyword in commit: "${h}"`));if(g&&FS(g,i))return p(Ei(i,"commit-skip",`Skip keyword in commit: "${h}"`));let y,w;try{({packageJsons:w,workspace:y}=mt(o,n))}catch(k){const $=k instanceof Error?k.message:String(k);return p(jr(i,"workspace-error",`Workspace discovery failed (${$}) — building defensively`))}if(!Object.hasOwn(y.projects,i))return p(jr(i,"project-unknown",`Project "${i}" not found in workspace — building defensively`));try{const k=r.base?.trim(),$=MS();let x=k||$||"HEAD~1";const T=r.head?.trim()||"HEAD";pc(x),pc(T),d(`resolved base ref: ${x} (source: ${k?"flag":$?"ci-env":"default"})`);const I=DS(o,x),P=nr(o,y,w);await I||(d(`base ref ${x} not reachable — falling back to HEAD~1`),x="HEAD~1"),d(`comparing ${x}...${T}`);const R=r.downstream??"deep",M=r.upstream??"none";if(!fc.has(R))throw new Error(`Invalid --downstream value: "${R}". Must be "none", "direct", or "deep".`);if(!fc.has(M))throw new Error(`Invalid --upstream value: "${M}". Must be "none", "direct", or "deep".`);const L={base:x,downstream:R,head:T,projectGraph:P,projects:y.projects,upstream:M,workspaceRoot:o},U=await Jc(L);d(`changed files: ${U.changedFiles.length}`),d(`affected projects: ${U.affectedProjects.join(", ")||"(none)"}`);const D={base:x,head:T};return U.changedFiles.length===0?p(Ei(i,"no-changes",`No files changed between ${x}...${T}`,{...D,affectedProjects:[]})):U.affectedProjects.includes(i)?p(jr(i,"project-affected",`Build ${i}: affected by ${U.changedFiles.length} changed file(s)`,{...D,affectedProjects:U.affectedProjects})):p(Ei(i,"project-not-affected",`Skip ${i}: not affected by changes between ${x}...${T}`,{...D,affectedProjects:U.affectedProjects}))}catch(k){const $=k instanceof Error?k.message:String(k);return t.error(`Affected detection failed: ${$}`),p(jr(i,"workspace-error",`Affected detection failed (${$}) — building defensively`))}},"execute"),group:"Run & Execute",name:"ignore",options:[{description:"Git base ref for comparison. Defaults to CI provider env vars, then HEAD~1.",name:"base",type:String},{defaultValue:"HEAD",description:"Git head ref for comparison",name:"head",type:String},{defaultValue:"deep",description:'Downstream scope: "none", "direct", or "deep"',name:"downstream",type:String},{defaultValue:"none",description:'Upstream scope: "none", "direct", or "deep"',name:"upstream",type:String},{defaultValue:!1,description:"Emit the decision as JSON on stdout instead of human text",name:"json",type:Boolean},{defaultValue:!1,description:"Exit 0 on build (normal semantics) instead of 1 (inverted Vercel/Netlify semantics)",name:"exit-zero-on-build",type:Boolean},{defaultValue:!1,description:"Enable verbose debug output",name:"verbose",type:Boolean}]};var GS=Object.defineProperty,pu=b((e,t)=>GS(e,"name",{value:t,configurable:!0}),"f$c");const bn=v(Qe(),".vis"),fu=[v(Qe(),".zshrc"),v(Qe(),".zshenv"),v(Qe(),".bashrc"),v(Qe(),".bash_profile"),v(Qe(),".profile"),v(Qe(),".config","fish","config.fish")],HS=pu(e=>{const t=[];for(const r of fu)if(E(r))try{const n=q(r).split(`
837
- `),o=n.filter(i=>!i.includes(".vis/bin")&&!i.includes("VIS_HOME")&&!i.includes("# vis "));o.length!==n.length&&(Z(r,o.join(`
838
- `)),t.push(r))}catch{e.warn(`warning: could not clean ${r}`)}return t},"cleanShellProfiles"),zS={description:"Remove vis from the system (self-uninstall)",examples:[["vis implode","Interactive uninstall"],["vis implode --yes","Non-interactive uninstall (CI)"]],execute:pu(async({logger:e,options:t})=>{if(!E(bn)){e.info("vis is not installed (no ~/.vis directory found).");return}e.info("This will remove:"),e.info(` ${bn}/`);const r=fu.filter(o=>E(o)&&q(o).includes(".vis"));for(const o of r)e.info(` Lines in ${o}`);if(!t.yes){if(!process.stdin.isTTY)throw new Error("Non-interactive terminal. Use --yes to confirm.");const o=gt({input:process.stdin,output:process.stdout}),i=await new Promise(s=>{o.question(`
839
- Type "uninstall" to confirm: `,s)});if(o.close(),i.trim()!=="uninstall"){e.info("Aborted.");return}}const n=HS(e);for(const o of n)e.info(`Cleaned ${o}`);try{at(bn,{force:!0,recursive:!0}),e.info(`
840
- ✓ Removed ${bn}`)}catch(o){throw new Error(`Failed to remove ${bn}: ${o instanceof Error?o.message:String(o)}`)}e.info("✓ vis has been uninstalled.")},"execute"),group:"System",name:"implode",options:[{alias:"y",defaultValue:!1,description:"Skip confirmation prompt",name:"yes",type:Boolean}]};var qS=Object.defineProperty,JS=b((e,t)=>qS(e,"name",{value:t,configurable:!0}),"n$5");const YS={alias:"view",argument:{description:"Package name followed by optional metadata fields (e.g. 'react version dependencies')",name:"args",type:String},description:"Show npm registry metadata for a package (alias of `npm view` / `pnpm view` / `yarn info` / `bun pm view`)",examples:[["vis info react","Full registry metadata for react"],["vis info react version","Latest version only"],["vis info react versions","All published versions"],["vis info react@18 dependencies","Dependencies of react@18"],["vis info react --json","Emit JSON"],["vis view react","Alias matching npm/pnpm"]],execute:JS(async({argument:e,logger:t,options:r,workspaceRoot:n})=>{if(!e||e.length===0)throw new Error("No package specified. Usage: vis info <package> [field...]");const[o,...i]=e,s=n??process.cwd(),a=Ne(s),c=Em(a,{fields:i,json:r.json||!1,package:o},s,t);c!==0&&c!==1&&(process.exitCode=c)},"execute"),group:"Dependencies",name:"info",options:[{defaultValue:!1,description:"Output as JSON",name:"json",type:Boolean}]};var KS=Object.defineProperty,zr=b((e,t)=>KS(e,"name",{value:t,configurable:!0}),"l$b");const XS=zr(e=>{const t=[];return E(v(e,"turbo.json"))&&t.push("turborepo"),E(v(e,"nx.json"))&&t.push("nx"),E(v(e,".moon"))&&t.push("moon"),t},"detectExistingTools"),QS=zr((e,t)=>new Promise(r=>{e.question(t,n=>{r(n.trim())})}),"ask"),qr=zr(async(e,t,r=!0)=>{const n=await QS(e,`${t} ${r?"[Y/n]":"[y/N]"} `);return n===""?r:n.toLowerCase()==="y"||n.toLowerCase()==="yes"},"confirm"),_i=zr((e,t)=>{const r=[],n=Object.entries(t.allowBuilds).filter(([,i])=>i).map(([i])=>` "${i}": true,`).join(`
841
- `);let o=` allowBuilds: ${n?`{
842
- ${n}
843
- }`:"{}"},`;return t.enableSocket&&(o+=`
844
- socket: { enabled: true },`),r.push(` security: {
845
- ${o}
846
- },`),t.staged&&r.push(` staged: {
847
- "*.{ts,tsx}": "eslint --fix",
848
- "*.{ts,tsx,js,jsx,json,md}": "prettier --write",
849
- },`),`import { defineConfig } from "@visulima/vis/config";
850
-
851
- export default defineConfig({
852
- ${r.join(`
853
-
854
- `)}
855
- });
856
- `},"generateConfigContent"),ZS=zr(async(e,t,r)=>{const n=gt({input:process.stdin,output:process.stdout});S(`
857
- vis init — interactive setup
858
- `);const o=await qr(n," Enable Socket.dev security scanning?");o&&(ee(" Socket.dev enabled — scores, alerts, and supply chain data active."),process.env.VIS_SOCKET_TOKEN||ie(" Set VIS_SOCKET_TOKEN for a custom API token (optional).")),S("");const i=await qr(n," Scan for packages with build scripts?"),s={};if(i){S(" Scanning node_modules...");const g=hd(e,{});if(g.length>0){S(` Found ${String(g.length)} package${g.length===1?"":"s"} with build scripts:
859
- `);for(const h of g){const y=await qr(n,` Allow ${h}?`,!1),w=h.split(" (")[0]??h;s[w]=y,y&&ee(` ✓ ${w} approved`)}}else S(" No packages with build scripts found.")}S("");const a=await qr(n," Set up pre-commit hooks (lint-staged)?",!1);let c=!1;(t.name==="pnpm"||t.name==="yarn"||t.name==="npm"||t.name==="bun")&&(S(""),c=await qr(n,` Sync security settings to ${t.name} config?`));const d=XS(e);if(d.length>0&&(S(""),S(` Detected existing tools: ${d.join(", ")}`),await qr(n,` Run \`vis migrate\` for ${d.join(", ")}?`,!1))){n.close();const g=t.name==="pnpm"?"pnpm exec":t.name==="yarn"?"yarn exec":t.name==="bun"?"bunx":"npx";for(const h of d){S(` Migrating from ${h}...`);try{zn(`${g} vis migrate ${h}`,{cwd:e,stdio:"inherit"})}catch{se(` Migration from ${h} had issues — run \`vis migrate ${h}\` manually.`)}}if(E(r))ee(`Migrated config written to ${r}`);else{const h=_i(t.name,{allowBuilds:s,enableSocket:o,staged:a});Z(r,h),ee(`Created ${r}`)}ie(" Run 'vis doctor' to see your project's full health status.");return}n.close(),S("");const p=_i(t.name,{allowBuilds:s,enableSocket:o,staged:a});if(Z(r,p),ee(`Created ${r}`),c){const g=Object.fromEntries(Object.entries(s).filter(([,y])=>y)),h=Cs(t.name,e,g);for(const y of h)ee(` ${y}`)}S(""),S(" Setup complete. Your config:"),S(` Security: ${o?"Socket.dev enabled":"defaults only"}`),S(` Build scripts: ${Object.values(s).filter(Boolean).length} approved`),S(` Git hooks: ${a?"lint-staged configured":"not configured"}`),S(` PM sync: ${c?"done":"skipped"}`),S(""),ie(" Run 'vis doctor' to see your project's full health status."),S("")},"runInteractiveInit"),eC=zr((e,t,r,n)=>{const o=_i(t.name,{allowBuilds:{},enableSocket:!1,staged:!1});if(Z(n,o),ee(`Created ${n}`),S(" Secure defaults applied automatically by defineConfig()."),r.syncNative){const i=Cs(t.name,e,{});for(const s of i)ee(` ${s}`)}S(""),ie("Run 'vis doctor' for a full health check, or 'vis init' in a terminal for guided setup.")},"runStaticInit"),tC={description:"Initialize vis.config.ts with best-practice security defaults",examples:[["vis init","Interactive setup wizard"],["vis init --no-interactive","Create minimal config without prompts"],["vis init --force","Overwrite existing config"],["vis init --sync-native","Also sync to native PM config files"]],execute:zr(async({options:e,workspaceRoot:t})=>{const r=t??process.cwd(),n=Ne(r),o=dn(r);if(o&&!e.force){se(`Config already exists: ${o}`),ie("Use --force to overwrite, or edit the existing file.");return}const i=o??v(r,"vis.config.ts");process.stdin.isTTY&&e.interactive!==!1&&!e.noInteractive?await ZS(r,n,i):eC(r,n,e,i)},"execute"),group:"Scaffold & Config",name:"init",options:[{defaultValue:!1,description:"Overwrite existing config file",name:"force",type:Boolean},{defaultValue:!1,description:"Skip interactive prompts",name:"no-interactive",type:Boolean},{defaultValue:!1,description:"Sync settings to native PM config files",name:"sync-native",type:Boolean}]};var rC=Object.defineProperty,nC=b((e,t)=>rC(e,"name",{value:t,configurable:!0}),"i$7");const oC={alias:"i",description:"Install dependencies using the detected package manager",examples:[["vis install","Install all dependencies"],["vis i --frozen-lockfile","Install with frozen lockfile (CI mode)"],["vis install --ci","Clean install: wipe node_modules + frozen lockfile (mirrors npm ci / pnpm ci)"],["vis install --prod","Install production dependencies only"],["vis install --filter app","Install for specific workspace package"],["vis install --ignore-scripts","Install without running lifecycle scripts"],["vis install --no-typosquat-check","Skip typosquat name check"]],execute:nC(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{const o=n??process.cwd();if(!t.noTyposquatCheck&&!await Vl(o,r?.security?.typosquatAllowlist)){process.exitCode=1;return}const i=Ne(o),s=Yn(t.filter),a=t.ci||!1;if(a){S("Clean install: removing node_modules...");try{at(v(o,"node_modules"),{force:!0,recursive:!0})}catch(d){ur(`Failed to remove node_modules: ${d instanceof Error?d.message:String(d)}`),process.exitCode=1;return}}const c=Ho(i,{dev:t.dev||!1,filter:s,force:t.force||!1,frozenLockfile:a||t.frozenLockfile||!1,ignoreScripts:t.ignoreScripts||!1,lockfileOnly:t.lockfileOnly||!1,noOptional:t.noOptional||!1,offline:t.offline||!1,prod:t.prod||!1,recursive:t.recursive||!1,silent:t.silent||!1,workspaceRoot:t.workspaceRoot||!1},o,e);c!==0&&(process.exitCode=c)},"execute"),group:"Dependencies",name:"install",options:[{alias:"P",defaultValue:!1,description:"Skip devDependencies",name:"prod",type:Boolean},{alias:"D",defaultValue:!1,description:"Install devDependencies only",name:"dev",type:Boolean},{defaultValue:!1,description:"Use frozen lockfile (CI mode, maps to npm ci)",name:"frozen-lockfile",type:Boolean},{defaultValue:!1,description:"Clean install: wipe node_modules then install with frozen lockfile",name:"ci",type:Boolean},{alias:"f",defaultValue:!1,description:"Force reinstall all dependencies",name:"force",type:Boolean},{defaultValue:!1,description:"Skip lifecycle scripts",name:"ignore-scripts",type:Boolean},{defaultValue:!1,description:"Update lockfile without installing",name:"lockfile-only",type:Boolean},{defaultValue:!1,description:"Skip optional dependencies",name:"no-optional",type:Boolean},{defaultValue:!1,description:"Use only cached packages",name:"offline",type:Boolean},{alias:"s",defaultValue:!1,description:"Suppress output",name:"silent",type:Boolean},{alias:"r",defaultValue:!1,description:"Install in all workspace packages",name:"recursive",type:Boolean},{alias:"w",defaultValue:!1,description:"Target workspace root",name:"workspace-root",type:Boolean},{alias:"F",description:"Filter by workspace package name",multiple:!0,name:"filter",type:String},{defaultValue:!1,description:"Skip typosquat name check",name:"no-typosquat-check",type:Boolean}]};var iC=Object.defineProperty,sC=b((e,t)=>iC(e,"name",{value:t,configurable:!0}),"o$8");const aC={alias:"ln",argument:{description:"Package name or directory path to link (omit to register current package)",name:"target",type:String},description:"Link a local package for development",examples:[["vis link ./packages/utils","Link local directory package (works on all PMs)"],["vis link","Register current package globally (pnpm <=10, yarn, npm, bun)"],["vis link react","Link global package into current project (pnpm <=10, yarn, npm, bun)"]],execute:sC(async({argument:e,logger:t,workspaceRoot:r})=>{const n=e?.[0]??null,o=r??process.cwd(),i=Ne(o),s=Tm(i,n,o,t);s!==0&&(process.exitCode=s)},"execute"),group:"Dependencies",name:"link"};var cC=Object.defineProperty,gc=b((e,t)=>cC(e,"name",{value:t,configurable:!0}),"m$8");const lC={description:"List all workspace projects with metadata",examples:[["vis list","Show all projects"],["vis list --json","Machine-readable output"],['vis list --query "tag=frontend"',"Filter by query"]],execute:gc(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!n)throw new Error("Could not determine workspace root.");const{projectOptions:o,workspace:i}=mt(n,r);let s=Object.keys(i.projects).sort();if(t.query&&(s=Bo(s,i,t.query)),s.length===0){e.info("No projects found.");return}if(t.json){const g=s.map(h=>{const y=i.projects[h],w=o.get(h)??{},k=Object.entries(y.targets??{}).map(([$])=>{const x=w[$];return{aliases:x?.aliases??[],command:x?.command,description:x?.description,name:$,type:x?.type}});return{language:y.language,layer:y.layer,name:h,root:y.root,stack:y.stack,tags:y.tags??[],targets:k,type:y.projectType??"library"}});e.info(JSON.stringify(g,null,2));return}const a=["Project","Type","Layer","Tags","Targets"],c=s.map(g=>{const h=i.projects[g],y=Object.keys(h.targets??{});return[g,h.projectType??"library",h.layer??"—",(h.tags??[]).join(", ")||"—",y.length>4?`${y.slice(0,4).join(", ")}… (${String(y.length)})`:y.join(", ")||"—"]}),d=a.map((g,h)=>{const y=c.reduce((w,k)=>Math.max(w,(k[h]??"").length),0);return Math.max(g.length,y)}),p=gc((g,h)=>g.padEnd(h),"pad");e.info(a.map((g,h)=>p(g,d[h])).join(" ")),e.info(d.map(g=>"─".repeat(g)).join("──"));for(const g of c)e.info(g.map((h,y)=>p(h,d[y])).join(" "));e.info(""),e.info(`${String(s.length)} project(s)`)},"execute"),group:"Workspace",name:"list",options:[{defaultValue:!1,description:"Emit JSON instead of a table",name:"json",type:Boolean},{description:"Filter projects by query",name:"query",type:String}]};var dC=Object.defineProperty,uC=b((e,t)=>dC(e,"name",{value:t,configurable:!0}),"t$a");const Pe=uC((e,t)=>{if(!E(e))return;const r=`${e}.bak`;E(r)||(t?.backupsCreated.includes(r)??!1)||(Op(e,r),t&&t.backupsCreated.push(r))},"backupFile");var pC=Object.defineProperty,si=b((e,t)=>pC(e,"name",{value:t,configurable:!0}),"e$1");const yt=si(e=>{try{const t=q(e);return JSON.parse(t)}catch{return}},"readJsonFile"),ai=si(e=>{if(!E(e))return!1;try{return JSON.parse(q(e)),!0}catch{return!1}},"isJsonFile"),fC=/\n([ \t]+)"/,Fs=si(e=>fC.exec(e)?.[1]?.length??4,"detectJsonIndent"),gC=si((e,t,r)=>{if(!E(e))return!1;const n=q(e);let o;try{o=JSON.parse(n)}catch{return!1}const i=t(o);if(i===void 0)return!1;const s=Fs(n);return r&&Pe(e,r),me(e,`${JSON.stringify(i,void 0,s)}
860
- `,"utf8"),!0},"editJsonFile");var mC=Object.defineProperty,kr=b((e,t)=>mC(e,"name",{value:t,configurable:!0}),"f$9");const hC=/\blint-staged\b/g,yC=kr((e,t)=>{let r=!1;const n={...e};for(const[o,i]of Object.entries(n)){if(typeof i!="string")continue;let s=ou(i);s&&(s=s.replaceAll(hC,"vis staged").trim()||void 0),s!==i&&(s?n[o]=s:delete n[o],r=!0,t.rewrittenScriptCount+=1)}return{modified:r,scripts:n}},"rewriteScripts"),gu=kr((e,t,r,n)=>{const o=v(e,"package.json");E(o)&&gC(o,i=>{let s=!1;for(const c of g0){const d=i.dependencies,p=i.devDependencies;d?.[c]&&(delete d[c],s=!0,n.removedPackageCount+=1),p?.[c]&&(delete p[c],s=!0,n.removedPackageCount+=1)}if(Object.keys(r).length>0)switch(t){case"bun":{const c=i.workspaces,d=c&&!Array.isArray(c)?c:void 0,p={...d?.catalog??i.catalog};for(const[h,y]of Object.entries(r))p[h]=y;d?.catalog==null?i.catalog=p:d.catalog=p;const g=i.overrides??{};for(const h of Object.keys(r))g[h]="catalog:";i.overrides=g,s=!0;break}case"npm":{const c=i.overrides??{};i.overrides={...c,...r},s=!0;break}case"pnpm":{const c=i.pnpm??{},d=c.overrides??{};c.overrides={...d,...r},i.pnpm=c,s=!0;break}case"yarn":{const c=i.resolutions??{};i.resolutions={...c,...r},s=!0;break}}const a=i.scripts;if(a){const c=yC(a,n);c.modified&&(i.scripts=c.scripts,s=!0)}return s?i:void 0})},"rewritePackageJson"),vC=kr((e,t,r,n)=>{try{const{workspace:o}=mt(e);for(const i of Object.values(o.projects)){const s=v(e,i.root);gu(s,t,r,n)}}catch{}},"migrateMonorepoPackages"),wC=kr(e=>e.startsWith("- ")||e!==""&&!e.includes(":")&&!e.startsWith("#"),"isCatalogSectionEnd"),kC=kr(e=>{let t=!1,r="";const n=new Set;for(const o of e){const i=o.trim();if(i==="catalog:"){t=!0;continue}if(!t)continue;if(wC(i))break;const s=i.includes(":")?i.split(":")[0]?.trim():void 0;s&&(n.add(s),r=r||o.slice(0,o.indexOf(i)))}return{entries:n,indent:r||" "}},"parseCatalogEntries"),bC=kr((e,t,r)=>{const n=[];let o=!1,i=!1;for(let s=0;s<e.length;s+=1){const a=e[s],c=a.trim();if(n.push(a),c==="catalog:"){i=!0;continue}if(i&&!o){const d=e[s+1]?.trim()??"";(!d.includes(":")||d.startsWith("- ")||!d||d==="catalog:")&&(n.push(...t),o=!0,i=!1)}}return o||(r.includes("catalog:")||n.push("catalog:"),n.push(...t)),n},"insertCatalogEntries"),$C=kr((e,t)=>{const r=v(e,"pnpm-workspace.yaml");if(!E(r)||Object.keys(t).length===0)return;const n=q(r),o=n.split(`
861
- `),{entries:i,indent:s}=kC(o),a=[];for(const[d,p]of Object.entries(t))i.has(d)||a.push(`${s}${d}: "${p}"`);if(a.length===0)return;const c=bC(o,a,n);Pe(r),me(r,c.join(`
862
- `),"utf8")},"updatePnpmWorkspaceCatalog"),mu=kr((e,t,r,n,o,i)=>{const s=r.overrides??{};if(n.dryRun){o.info("[dry-run] Would rewrite package.json files (remove husky/lint-staged, rewrite scripts)"),Object.keys(s).length>0&&o.info(`[dry-run] Would add overrides: ${JSON.stringify(s)}`);return}gu(e,t,s,i),o.info("Rewritten root package.json"),vC(e,t,s,i),t==="pnpm"&&$C(e,s)},"migrateDeps");var xC=Object.defineProperty,ci=b((e,t)=>xC(e,"name",{value:t,configurable:!0}),"t$9");const SC=ci(()=>({backupsCreated:[],gitHooksConfigured:!1,inlinedLintStagedConfigCount:0,manualSteps:[],mergedStagedConfigCount:0,perMigration:{},removedConfigCount:0,removedPackageCount:0,rewrittenScriptCount:0,warnings:[]}),"createMigrationReport"),qe=ci((e,t)=>{!e||e.warnings.includes(t)||e.warnings.push(t)},"addMigrationWarning"),rt=ci((e,t)=>{!e||e.manualSteps.includes(t)||e.manualSteps.push(t)},"addManualStep"),Ft=ci((e,t,r,n=1)=>{const o=e.perMigration[t]??{removedConfigCount:0,removedPackageCount:0,rewrittenScriptCount:0};o[r]+=n,e.perMigration[t]=o,e[r]+=n},"bumpPerMigration");var CC=Object.defineProperty,_t=b((e,t)=>CC(e,"name",{value:t,configurable:!0}),"d$e");const jC=["gitleaks.toml",".gitleaks.toml"],EC=["gitleaks-report.json",".gitleaks-report.json","baseline.json"],Ls=_t(e=>jC.find(t=>E(v(e,t))),"detectGitleaksConfig"),hu=_t(e=>{const t=v(e,".gitleaksignore");return E(t)?t:void 0},"detectGitleaksIgnore"),yu=_t(e=>{for(const t of EC){const r=v(e,t);if(E(r))try{const n=JSON.parse(q(r));if(Array.isArray(n)&&n.length>0&&typeof n[0]=="object"&&n[0]!==null&&"RuleID"in n[0])return r}catch{}}},"detectGitleaksBaseline"),TC=_t(e=>e.map(t=>({description:t.Description??"",endColumn:t.EndColumn??0,endLine:t.EndLine??t.StartLine??0,entropy:t.Entropy??0,file:t.File??"",match:t.Match??"",ruleId:t.RuleID??"",secret:t.Secret??"",startColumn:t.StartColumn??0,startLine:t.StartLine??0,tags:t.Tags??[]})),"convertBaseline"),RC=_t((e,t,r,n)=>{const o=yu(e);if(!o)return;const i=v(e,".secrets-baseline.json");if(E(i)&&o!==i){qe(n,`.secrets-baseline.json already exists — leaving ${o} in place`);return}const s=yt(o);if(!Array.isArray(s)){qe(n,`Could not parse ${o} as a gitleaks baseline`);return}const a=TC(s);if(t){r.info(`[dry-run] Would convert ${o} -> ${i} (${String(a.length)} findings)`);return}Pe(o,n),Z(i,`${JSON.stringify(a,null,4)}
863
- `),r.info(`Converted ${o} -> ${i} (${String(a.length)} findings)`),Ft(n,"gitleaks","rewrittenScriptCount")},"migrateBaseline"),AC=_t((e,t,r,n)=>{const o=v(e,"package.json");if(!E(o))return;const i=yt(o);if(!i)return;const s=Ls(e),a=s?`vis secrets --config ${s}`:"vis secrets";let c=!1;if(i.scripts){for(const[d,p]of Object.entries(i.scripts))if(typeof p=="string"&&/\bgitleaks\b/.test(p)){const g=p.replaceAll(/\bgitleaks(?:\s+(?:detect|protect))?\b[^\n&|;]*/g,a).trim();g!==p&&(i.scripts[d]=g,c=!0,r.info(` scripts.${d}: "${p}" -> "${g}"`),Ft(n,"gitleaks","rewrittenScriptCount"))}}if(i.devDependencies){const d=i.devDependencies;for(const p of["gitleaks","@gitleaks/cli"])p in d&&(delete d[p],c=!0,Ft(n,"gitleaks","removedPackageCount"),r.info(` removed devDependency: ${p}`))}if(c){if(t){r.info(`[dry-run] Would update ${o}`);return}Pe(o,n),Z(o,`${JSON.stringify(i,null,4)}
864
- `)}},"rewriteScripts"),IC=_t((e,t,r,n)=>{const o=[".husky/pre-commit",".vis-hooks/pre-commit",".git/hooks/pre-commit"],i=Ls(e),s=i?`vis secrets --staged --config ${i}`:"vis secrets --staged";for(const a of o){const c=v(e,a);if(!E(c))continue;const d=q(c);if(!/\bgitleaks\b/.test(d))continue;const p=d.replaceAll(/\bgitleaks(?:\s+(?:detect|protect))?\b[^\n&|;]*/g,s);if(t){r.info(`[dry-run] Would rewrite ${c}`);continue}Pe(c,n),Z(c,p),n.gitHooksConfigured=!0,r.info(`Rewrote gitleaks invocation in ${a}`)}},"rewriteHooks"),OC=/^([^:#][^:]*):([^:]+):(\d+)$/,PC=_t(e=>{const t=OC.exec(e.trim());if(!t)return;const[,r,n,o]=t,i=Number.parseInt(o??"0",10);return{description:"",endColumn:0,endLine:i,entropy:0,file:r??"",match:"",ruleId:n??"",secret:"",startColumn:0,startLine:i,tags:[]}},"fingerprintToBaselineEntry"),NC=_t((e,t,r,n)=>{const o=hu(e);if(!o)return;const i=q(o).split(/\r?\n/).map(p=>p.trim()).filter(p=>p.length>0&&!p.startsWith("#")).map(p=>PC(p)).filter(p=>p!==void 0);i.length===0&&qe(n,`${o} contained no recognisable fingerprint lines — deleting it.`);const s=v(e,".secrets-baseline.json"),a=E(s)?yt(s)??[]:[],c=new Set(a.map(p=>`${p.file}:${p.ruleId}:${String(p.startLine)}`)),d=[...a];for(const p of i){const g=`${p.file}:${p.ruleId}:${String(p.startLine)}`;c.has(g)||(c.add(g),d.push(p))}if(t){r.info(`[dry-run] Would merge ${String(i.length)} .gitleaksignore fingerprint(s) into ${s}, then delete ${o}.`);return}Pe(o,n),E(s)&&Pe(s,n),Z(s,`${JSON.stringify(d,null,4)}
865
- `),Dr(o),r.info(`Merged ${String(i.length)} fingerprint(s) from ${o} into ${s}; removed .gitleaksignore.`),Ft(n,"gitleaks","rewrittenScriptCount",i.length)},"migrateIgnoreFile"),MC=_t((e,t,r,n)=>{const o=Ls(e),i=hu(e);return o??i??yu(e)?(o&&(r.info(`Keeping ${o} as-is (compatible with vis secrets --config).`),rt(n,`Run \`vis secrets --config ${o}\` or rename to .gitleaksignore-compatible defaults.`)),i&&NC(e,t.dryRun,r,n),RC(e,t.dryRun,r,n),AC(e,t.dryRun,r,n),IC(e,t.dryRun,r,n),rt(n,"Review CI workflows (.github/workflows/*.yml) for gitleaks-action calls — replace with `vis secrets`."),!0):(t.silent||r.info("No gitleaks artifacts found — nothing to migrate."),!1)},"migrateGitleaks");var DC=Object.defineProperty,or=b((e,t)=>DC(e,"name",{value:t,configurable:!0}),"g$8");const BC=["kingfisher-baseline.yaml",".kingfisher-baseline.yaml","kingfisher-baseline.yml",".kingfisher-baseline.yml"],FC=["kingfisher-rules.yml","kingfisher-rules.yaml",".kingfisher-rules.yml",".kingfisher-rules.yaml"],vu=or(e=>BC.find(t=>E(v(e,t))),"detectKingfisherBaseline"),Vs=or(e=>FC.find(t=>E(v(e,t))),"detectKingfisherRules"),LC=or(e=>{const t=[];let r={};for(const n of e.split(/\r?\n/)){const o=n.replace(/#.*$/,"");(/^\s*-\s*filepath\s*:/.test(o)||/^\s*-\s*$/.test(o))&&(r.filepath&&typeof r.linenum=="number"&&r.fingerprint&&t.push(r),r={});const i=/filepath\s*:\s*(.+?)\s*$/.exec(o);if(i?.[1]){r.filepath=i[1].replaceAll(/^["']|["']$/g,"");continue}const s=/fingerprint\s*:\s*(.+?)\s*$/.exec(o);if(s?.[1]){r.fingerprint=s[1].replaceAll(/^["']|["']$/g,"");continue}const a=/linenum\s*:\s*(\d+)/.exec(o);a?.[1]&&(r.linenum=Number.parseInt(a[1],10))}return r.filepath&&typeof r.linenum=="number"&&r.fingerprint&&t.push(r),t},"parseKingfisherBaseline"),VC=or(e=>({_kingfisherMigration:{legacyFingerprint:e.fingerprint,note:"Kingfisher xxhash — regenerate by running `vis secrets --update-baseline`."},description:"",endColumn:0,endLine:e.linenum,entropy:0,file:e.filepath,match:"",ruleId:"",secret:"",startColumn:0,startLine:e.linenum,tags:[]}),"toPlaceholderEntry"),_C=or((e,t,r,n)=>{const o=vu(e);if(!o)return;const i=v(e,o);let s;try{s=LC(q(i))}catch(d){const p=d instanceof Error?d.message:String(d);qe(n,`Could not parse ${o} as a Kingfisher baseline: ${p}`);return}if(s.length===0){qe(n,`${o} contained no recognisable records — leaving it in place for manual review.`);return}const a=v(e,".secrets-baseline.json");if(E(a)){qe(n,`.secrets-baseline.json already exists — leaving Kingfisher baseline at ${o} for manual merge.`);return}const c=s.map(d=>VC(d));if(t){r.info(`[dry-run] Would convert ${o} -> .secrets-baseline.json (${String(c.length)} placeholder finding(s))`),rt(n,"Run `vis secrets --update-baseline` after migration — Kingfisher xxhash fingerprints aren't interchangeable with our content-hash.");return}Pe(i,n),Z(a,`${JSON.stringify(c,null,4)}
866
- `),r.info(`Converted ${o} -> .secrets-baseline.json (${String(c.length)} placeholder finding(s))`),rt(n,"Run `vis secrets --update-baseline` — the converted entries are placeholders until the scanner computes real fingerprints."),Ft(n,"kingfisher","rewrittenScriptCount")},"migrateBaseline"),wu=/\bkingfisher(?:\s+(?:scan|validate|rules|update|manage-baseline|report|github|gitlab|bitbucket))?\b[^\n&|;]*/g,UC=or((e,t,r,n)=>{const o=v(e,"package.json");if(!E(o))return;const i=yt(o);if(!i)return;const s=Vs(e),a=s?`vis secrets --config ${s}`:"vis secrets";let c=!1;if(i.scripts)for(const[d,p]of Object.entries(i.scripts)){if(typeof p!="string"||!/\bkingfisher\b/.test(p))continue;const g=p.replaceAll(wu,h=>h.includes("validate")?`${a} --validate`:a).trim();g!==p&&(i.scripts[d]=g,c=!0,r.info(` scripts.${d}: "${p}" -> "${g}"`),Ft(n,"kingfisher","rewrittenScriptCount"))}if(i.devDependencies){const d=i.devDependencies;for(const p of["kingfisher","@mongodb/kingfisher","kingfisher-scanner"])p in d&&(delete d[p],c=!0,Ft(n,"kingfisher","removedPackageCount"),r.info(` removed devDependency: ${p}`))}if(c){if(t){r.info(`[dry-run] Would update ${o}`);return}Pe(o,n),Z(o,`${JSON.stringify(i,null,4)}
867
- `)}},"rewriteScripts"),WC=or((e,t,r,n)=>{const o=Vs(e),i=o?`vis secrets --staged --config ${o}`:"vis secrets --staged";for(const s of ku){const a=v(e,s);if(!E(a))continue;const c=q(a);if(!/\bkingfisher\b/.test(c))continue;const d=c.replaceAll(wu,i);if(t){r.info(`[dry-run] Would rewrite ${a}`);continue}Pe(a,n),Z(a,d),n.gitHooksConfigured=!0,r.info(`Rewrote kingfisher invocation in ${s}`)}},"rewriteHooks"),ku=[".husky/pre-commit",".vis-hooks/pre-commit",".git/hooks/pre-commit"],mc=or(e=>{if(!E(e))return!1;try{return/\bkingfisher\b/.test(q(e))}catch{return!1}},"hasKingfisherRef"),GC=or((e,t,r,n)=>{const o=vu(e),i=Vs(e),s=mc(v(e,"package.json")),a=ku.some(c=>mc(v(e,c)));return(o??i)||s||a?(i&&(r.info(`Found custom Kingfisher ruleset at ${i} — keeping it for now.`),rt(n,`Convert ${i} to gitleaks-shaped JSON using \`packages/tooling/secret-scanner/scripts/kingfisher-converter.mjs\`, then point \`vis secrets --config\` at the result.`)),o&&_C(e,t.dryRun,r,n),UC(e,t.dryRun,r,n),WC(e,t.dryRun,r,n),rt(n,"Replace `# kingfisher:ignore` markers with `# secret-scanner:allow` (or keep `# gitleaks:allow` — the scanner accepts both)."),rt(n,"Review CI workflows (.github/workflows/*.yml) for Kingfisher action/docker invocations — replace with `vis secrets`."),!0):(t.silent||r.info("No Kingfisher artifacts found — nothing to migrate."),!1)},"migrateKingfisher");var HC=Object.defineProperty,Ye=b((e,t)=>HC(e,"name",{value:t,configurable:!0}),"r$9");const zC=/\bstaged\s*:/,hc=/(defineConfig\(\{)/,yc=/(export\s+default\s+\{)/;Ye(e=>Ns.some(t=>E(v(e,t))),"hasStandaloneLintStagedConfig");const qC=Ye(e=>{for(const r of tu)if(E(v(e,r)))return!0;const t=v(e,".lintstagedrc");return E(t)&&!ai(t)},"hasUnsupportedLintStagedConfig"),JC=Ye(e=>{const t=dn(e);if(!t)return!1;const r=q(t);return zC.test(r)},"hasStagedConfigInVisConfig"),YC=Ye(e=>{const t=v(e,"package.json");if(E(t)&&yt(t)?.["lint-staged"])return"package.json";for(const r of Ns)if(E(v(e,r)))return r},"detectLintStagedConfig"),KC=Ye(e=>yt(v(e,"package.json"))?.["lint-staged"],"extractLintStagedFromPackageJson"),XC=Ye(e=>yt(e),"parseLintStagedJsonFile"),Ui=Ye(e=>` staged: {
868
- ${Object.entries(e).map(([t,r])=>{const n=Array.isArray(r)?`[${r.map(o=>JSON.stringify(o)).join(", ")}]`:JSON.stringify(r);return` ${JSON.stringify(t)}: ${n}`}).join(`,
869
- `)},
870
- }`,"generateStagedConfigSnippet"),QC=Ye((e,t,r)=>{const n=dn(e);if(n){const s=q(n),a=Ui(t);let c;return hc.test(s)?c=s.replace(hc,`$1
871
- ${a},`):yc.test(s)&&(c=s.replace(yc,`$1
872
- ${a},`)),c?(Pe(n),me(n,c,"utf8"),r.info(`Merged staged config into ${n}`),!0):(r.warn(`Could not auto-insert staged config into ${n} — please add manually`),!1)}const o=v(e,"vis.config.ts"),i=`import { defineConfig } from "@visulima/vis/config";
873
-
874
- export default defineConfig({
875
- ${Ui(t)},
876
- });
877
- `;return me(o,i,"utf8"),r.info(`Created ${o} with staged config`),!0},"insertStagedIntoVisConfig"),ZC=Ye(e=>{const t=v(e,"package.json"),r={configRemoved:!1,dependencyRemoved:!1};if(!E(t))return r;const n=q(t),o=JSON.parse(n);let i=!1;o["lint-staged"]&&(delete o["lint-staged"],i=!0,r.configRemoved=!0);const s=o.devDependencies,a=o.dependencies;if(s?.["lint-staged"]&&(delete s["lint-staged"],i=!0,r.dependencyRemoved=!0),a?.["lint-staged"]&&(delete a["lint-staged"],i=!0,r.dependencyRemoved=!0),i){const c=Fs(n);Pe(t),me(t,`${JSON.stringify(o,void 0,c)}
878
- `,"utf8")}return r},"removeLintStagedFromPackageJson"),e1=Ye((e,t)=>{for(const r of Ns){const n=v(e,r);E(n)&&(Pe(n,t),Dr(n),t.removedConfigCount+=1)}},"removeLintStagedConfigFiles"),t1=Ye((e,t)=>{const r=v(e,t,"pre-commit");if(!E(r))return!1;const n=q(r);if(n.includes("vis staged"))return!1;const o=n.split(`
879
- `);let i=!1;const s=[];for(const a of o){const c=a.trim();if(!i){let d=!1;for(const p of p0){const g=p.exec(c);if(g){const h=a.slice(0,a.length-a.trimStart().length),y=g[1]?.trim()??"",w=c.slice(g[0].length).trim(),k=[y,"vis staged",w].filter(Boolean);s.push(`${h}${k.join(" ")}`),i=!0,d=!0;break}}if(d)continue}s.push(a)}return i?(Pe(r),me(r,s.join(`
880
- `)),!0):!1},"rewritePreCommitHook"),r1=Ye((e,t,r)=>{if(t==="package.json")return KC(e);const n=v(e,t);if(!eu.includes(t)){qe(r,`${t} cannot be auto-migrated — please add "staged" config to vis.config.ts manually`),rt(r,`Manually convert ${t} to staged config in vis.config.ts`);return}if(t===".lintstagedrc"&&!ai(n)){qe(r,".lintstagedrc is not JSON format — please migrate manually");return}return XC(n)},"extractConfig"),bu=Ye((e,t)=>{const{configRemoved:r,dependencyRemoved:n}=ZC(e);r&&(t.inlinedLintStagedConfigCount+=1),n&&(t.removedPackageCount+=1),e1(e,t)},"cleanupLintStagedArtifacts"),n1=Ye((e,t,r,n)=>{const o=[".vis-hooks",".husky"];for(const i of o)E(v(e,i))&&t1(e,i)&&(n.gitHooksConfigured=!0,t.silent||r.info(`Rewrote pre-commit hook in ${i}/ to use "vis staged"`))},"rewriteHooks"),o1=Ye((e,t,r,n,o)=>{QC(e,t,n)&&(o.mergedStagedConfigCount+=1),bu(e,o),n1(e,r,n,o)},"applyMigration"),$u=Ye((e,t,r,n)=>{const o=YC(e);if(!o)return t.silent||r.info("No lint-staged configuration found — nothing to migrate."),!1;if(qC(e)&&(qe(n,'Non-JSON lint-staged config found — please migrate to "staged" in vis.config.ts manually'),rt(n,"Convert your lint-staged config file to JSON format or add staged config to vis.config.ts manually")),JC(e))return qe(n,'vis.config.ts already has a "staged" config — skipping lint-staged merge'),t.silent||r.warn('vis.config.ts already has a "staged" config — skipping'),t.dryRun||bu(e,n),!0;const i=r1(e,o,n);return!i||Object.keys(i).length===0?(t.silent||r.warn("lint-staged config is empty — skipping"),!1):t.dryRun?(t.silent||(r.info("[dry-run] Would insert staged config into vis.config.ts:"),r.info(Ui(i))),!0):(o1(e,i,t,r,n),!0)},"migrateLintStaged");var i1=Object.defineProperty,_s=b((e,t)=>i1(e,"name",{value:t,configurable:!0}),"t$8");const Us=_s(e=>JSON.stringify(e,null,4).replaceAll(/"(\w+)":/g,"$1:"),"serializeConfigObject"),Ws=_s((e,t,r,n,o)=>{const i=v(e,"vis.config.ts");return E(i)&&!r.dryRun?(n.warn("vis.config.ts already exists — refusing to overwrite. Remove it first or run with --dry-run."),o.warnings.push("vis.config.ts already exists; migration skipped writing the file."),!1):(r.dryRun?(n.info("── vis.config.ts (preview) ──"),n.info(t),n.info("── end preview ──")):(Z(i,t),n.info(`Wrote ${i}`)),!0)},"writeVisConfig"),xu=_s((e,t)=>{const r=v(e,t);if(E(r))try{return JSON.parse(q(r))}catch(n){throw new Error(`Failed to parse ${r}: ${n.message}`)}},"readJsonConfig");var s1=Object.defineProperty,mn=b((e,t)=>s1(e,"name",{value:t,configurable:!0}),"l$a");const a1=mn(e=>{const t={};return e.command&&(t.command=Array.isArray(e.args)?`${e.command} ${e.args.join(" ")}`:e.args?`${e.command} ${e.args}`:e.command),e.deps&&e.deps.length>0&&(t.dependsOn=e.deps),e.inputs&&e.inputs.length>0&&(t.inputs=e.inputs),e.outputs&&e.outputs.length>0&&(t.outputs=e.outputs),e.type&&(t.type=e.type),e.preset&&(t.preset=e.preset),e.options&&(t.options=e.options),t},"taskToVisTarget"),c1=mn(e=>{const t={};e.fileGroups&&(t.fileGroups=e.fileGroups);const r={};for(const[n,o]of Object.entries(e.tasks??{}))r[n]=a1(o);return Object.keys(r).length>0&&(t.targetDefaults=r),e.implicitInputs&&e.implicitInputs.length>0&&(t.namedInputs={default:e.implicitInputs}),["// Migrated from moon's .moon/tasks.yml by `vis migrate moon`.","// Per-project moon.yml files can be converted to project.json —","// review the generated file and move project-specific tasks there.","",'import { defineConfig } from "@visulima/vis/config";',"",`export default defineConfig(${Us(t)});`,""].join(`
881
- `)},"renderVisConfig"),l1=mn(e=>{const t=v(e,".moon");if(!E(t))return;for(const n of["tasks.yml","tasks.yaml"]){const o=v(t,n);if(E(o))return o}const r=v(t,"tasks");if(E(r)){const n=Ve(r).filter(o=>o.endsWith(".yml")||o.endsWith(".yaml")).sort();if(n.length>0)return v(r,n[0])}},"findMoonTasksFile"),d1=mn(e=>{const t=v(e,".moon","templates");if(!E(t))return[];const r=[];try{for(const n of Ve(t,{withFileTypes:!0}))n.isDirectory()&&E(v(t,n.name,"template.yml"))&&r.push(n.name)}catch{}return r.sort()},"findMoonTemplates"),u1=mn((e,t,r,n,o)=>{const i=v(e,".moon","templates"),s=v(e,".vis","templates");r||Pp(s,{recursive:!0});for(const a of t){const c=v(i,a),d=v(s,a);if(E(d)){o.warnings.push(`Template "${a}" already exists at .vis/templates/${a} — left untouched. Remove or rename either copy to resolve.`);continue}if(r){n.info(`Would copy .moon/templates/${a} → .vis/templates/${a}`);continue}try{rs(c,d,{recursive:!0}),n.info(`Copied .moon/templates/${a} → .vis/templates/${a}`)}catch(p){const g=p instanceof Error?p.message:String(p);o.warnings.push(`Failed to copy template "${a}": ${g}`)}}!r&&t.length>0&&o.manualSteps.push(`Copied ${String(t.length)} template${t.length===1?"":"s"} from .moon/templates/ to .vis/templates/. Remove the .moon/templates/ directory when ready.`)},"copyMoonTemplatesToVis"),p1=mn((e,t,r,n)=>{const o=l1(e);if(!o){r.warn("No .moon/tasks.yml (or .moon/tasks/<scope>.yml) found — nothing to migrate."),n.warnings.push("No moon tasks file at workspace root.");return}let i;try{i=ln(o)}catch(d){throw new Error(`Failed to parse ${o}: ${d.message}`)}for(const[d,p]of Object.entries(i.tasks??{}))p.env&&Object.keys(p.env).length>0&&n.warnings.push(`Task "${d}" has an \`env\` block which vis does not support — set environment variables in the command or a wrapper script.`),p.platform&&n.warnings.push(`Task "${d}" has a \`platform\` field ("${p.platform}") which vis does not support — review and remove.`),p.toolchain&&n.warnings.push(`Task "${d}" has a \`toolchain\` field ("${p.toolchain}") which vis does not support — review and remove.`),Array.isArray(p.args)&&p.args.some(g=>g.includes(" "))&&n.warnings.push(`Task "${d}" has \`args\` entries containing spaces — vis flattens args into the command string so quoting may need manual adjustment.`);i.extends&&i.extends.length>0&&n.warnings.push("`extends` was found in the moon config but has no direct vis equivalent — inline the referenced files or use vis's `taskDefaults` blocks."),i.implicitDeps&&i.implicitDeps.length>0&&n.warnings.push("`implicitDeps` was found in the moon config but has no direct vis equivalent — add explicit `dependsOn` entries in project.json instead."),i.taskOptions&&Object.keys(i.taskOptions).length>0&&n.warnings.push("`taskOptions` was found in the moon config but has no direct vis equivalent — review and apply settings per-target in vis.config.ts.");const s=c1(i);if(!Ws(e,s,t,r,n))return;n.manualSteps.push("moon's per-project `moon.yml` files should be converted to `project.json`. vis reads targets, tags, layer, stack, language, and owners from project.json — the field names match."),n.manualSteps.push("Scoped `.moon/tasks/<scope>.yml` files map to vis's `taskDefaults` with a `scope` block. Only the first scope file was parsed — review the generated file.");const a=d1(e);if(a.length===0)return;const c=a.map(d=>`"${d}"`).join(", ");t.copyTemplates?u1(e,a,!!t.dryRun,r,n):n.manualSteps.push(`Detected ${String(a.length)} template${a.length===1?"":"s"} under .moon/templates/ (${c}). They are already usable via \`vis generate <name>\` — vis auto-discovers moon-format template directories at runtime. To decouple from moon entirely, re-run \`vis migrate moon --copy-templates\` to physically move them to .vis/templates/.`)},"migrateMoon");var f1=Object.defineProperty,Ke=b((e,t)=>f1(e,"name",{value:t,configurable:!0}),"r$8");const g1=/\bstaged\s*:/,vc=/(defineConfig\(\{)/,wc=/(export\s+default\s+\{)/;Ke(e=>Ms.some(t=>E(v(e,t))),"hasStandaloneNanoStagedConfig");const m1=Ke(e=>{for(const r of nu)if(E(v(e,r)))return!0;const t=v(e,".nanostagedrc");return E(t)&&!ai(t)},"hasUnsupportedNanoStagedConfig"),h1=Ke(e=>{const t=dn(e);return t?g1.test(q(t)):!1},"hasStagedConfigInVisConfig"),y1=Ke(e=>{const t=v(e,"package.json");if(E(t)&&yt(t)?.["nano-staged"])return"package.json";for(const r of Ms)if(E(v(e,r)))return r},"detectNanoStagedConfig"),v1=Ke(e=>yt(v(e,"package.json"))?.["nano-staged"],"extractNanoStagedFromPackageJson"),w1=Ke(e=>yt(e),"parseNanoStagedJsonFile"),Wi=Ke(e=>` staged: {
882
- ${Object.entries(e).map(([t,r])=>{const n=Array.isArray(r)?`[${r.map(o=>JSON.stringify(o)).join(", ")}]`:JSON.stringify(r);return` ${JSON.stringify(t)}: ${n}`}).join(`,
883
- `)},
884
- }`,"generateStagedConfigSnippet"),k1=Ke((e,t,r)=>{const n=dn(e);if(n){const s=q(n),a=Wi(t);let c;return vc.test(s)?c=s.replace(vc,`$1
885
- ${a},`):wc.test(s)&&(c=s.replace(wc,`$1
886
- ${a},`)),c?(Pe(n),me(n,c,"utf8"),r.info(`Merged staged config into ${n}`),!0):(r.warn(`Could not auto-insert staged config into ${n} — please add manually`),!1)}const o=v(e,"vis.config.ts"),i=`import { defineConfig } from "@visulima/vis/config";
887
-
888
- export default defineConfig({
889
- ${Wi(t)},
890
- });
891
- `;return me(o,i,"utf8"),r.info(`Created ${o} with staged config`),!0},"insertStagedIntoVisConfig"),b1=Ke(e=>{const t=v(e,"package.json"),r={configRemoved:!1,dependencyRemoved:!1};if(!E(t))return r;const n=q(t),o=JSON.parse(n);let i=!1;o["nano-staged"]&&(delete o["nano-staged"],i=!0,r.configRemoved=!0);const s=o.devDependencies,a=o.dependencies;if(s?.["nano-staged"]&&(delete s["nano-staged"],i=!0,r.dependencyRemoved=!0),a?.["nano-staged"]&&(delete a["nano-staged"],i=!0,r.dependencyRemoved=!0),i){const c=Fs(n);Pe(t),me(t,`${JSON.stringify(o,void 0,c)}
892
- `,"utf8")}return r},"removeNanoStagedFromPackageJson"),$1=Ke((e,t)=>{for(const r of Ms){const n=v(e,r);E(n)&&(Pe(n,t),Dr(n),t.removedConfigCount+=1)}},"removeNanoStagedConfigFiles"),x1=Ke((e,t)=>{const r=v(e,t,"pre-commit");if(!E(r))return!1;const n=q(r);if(n.includes("vis staged"))return!1;const o=n.split(`
893
- `);let i=!1;const s=[];for(const a of o){const c=a.trim();if(!i){let d=!1;for(const p of f0){const g=p.exec(c);if(g){const h=a.slice(0,a.length-a.trimStart().length),y=g[1]?.trim()??"",w=c.slice(g[0].length).trim(),k=[y,"vis staged",w].filter(Boolean);s.push(`${h}${k.join(" ")}`),i=!0,d=!0;break}}if(d)continue}s.push(a)}return i?(Pe(r),me(r,s.join(`
894
- `)),!0):!1},"rewritePreCommitHook"),S1=Ke((e,t,r)=>{if(t==="package.json")return v1(e);const n=v(e,t);if(!ru.includes(t)){qe(r,`${t} cannot be auto-migrated — please add "staged" config to vis.config.ts manually`),rt(r,`Manually convert ${t} to staged config in vis.config.ts`);return}if(t===".nanostagedrc"&&!ai(n)){qe(r,".nanostagedrc is not JSON format — please migrate manually");return}return w1(n)},"extractConfig"),Su=Ke((e,t)=>{const{configRemoved:r,dependencyRemoved:n}=b1(e);r&&(t.inlinedLintStagedConfigCount+=1),n&&(t.removedPackageCount+=1),$1(e,t)},"cleanupNanoStagedArtifacts"),C1=Ke((e,t,r,n)=>{const o=[".vis-hooks",".husky"];for(const i of o)E(v(e,i))&&x1(e,i)&&(n.gitHooksConfigured=!0,t.silent||r.info(`Rewrote pre-commit hook in ${i}/ to use "vis staged"`))},"rewriteHooks"),j1=Ke((e,t,r,n,o)=>{k1(e,t,n)&&(o.mergedStagedConfigCount+=1),Su(e,o),C1(e,r,n,o)},"applyMigration"),Cu=Ke((e,t,r,n)=>{const o=y1(e);if(!o)return t.silent||r.info("No nano-staged configuration found — nothing to migrate."),!1;if(m1(e)&&(qe(n,'Non-JSON nano-staged config found — please migrate to "staged" in vis.config.ts manually'),rt(n,"Convert your nano-staged config file to JSON format or add staged config to vis.config.ts manually")),h1(e))return qe(n,'vis.config.ts already has a "staged" config — skipping nano-staged merge'),t.silent||r.warn('vis.config.ts already has a "staged" config — skipping'),t.dryRun||Su(e,n),!0;const i=S1(e,o,n);return!i||Object.keys(i).length===0?(t.silent||r.warn("nano-staged config is empty — skipping"),!1):t.dryRun?(t.silent||(r.info("[dry-run] Would insert staged config into vis.config.ts:"),r.info(Wi(i))),!0):(j1(e,i,t,r,n),!0)},"migrateNanoStaged");var E1=Object.defineProperty,ju=b((e,t)=>E1(e,"name",{value:t,configurable:!0}),"o$7");const T1=ju(e=>{const t={};return e.namedInputs&&Object.keys(e.namedInputs).length>0&&(t.namedInputs=e.namedInputs),e.targetDefaults&&Object.keys(e.targetDefaults).length>0&&(t.targetDefaults=e.targetDefaults),["// Migrated from nx.json by `vis migrate nx`.","// Per-project project.json files are compatible with vis and do not need to be rewritten —","// vis already reads targets, tags, implicitDependencies, and sourceRoot.","",'import { defineConfig } from "@visulima/vis/config";',"",`export default defineConfig(${Us(t)});`,""].join(`
895
- `)},"renderVisConfig"),R1=ju((e,t,r,n)=>{const o=xu(e,"nx.json");if(!o){r.warn("No nx.json found in workspace root — nothing to migrate."),n.warnings.push("No nx.json at workspace root.");return}const i=T1(o);Ws(e,i,t,r,n)&&(n.manualSteps.push("Existing project.json files are vis-compatible and have been left untouched. Rename `sourceRoot` -> `sourceRoot` is identical; `tags`, `implicitDependencies`, and `targets` translate directly."),(o.affected?.defaultBase||o.defaultBase)&&n.manualSteps.push(`nx's default base branch (${o.affected?.defaultBase??o.defaultBase}) is honoured by vis via the --base flag; no vis config change needed.`))},"migrateNx");var A1=Object.defineProperty,I1=b((e,t)=>A1(e,"name",{value:t,configurable:!0}),"o$6");const O1=I1(async e=>{if(!na.isTTY)return!0;const t=Qp({input:na,output:Ap});try{const r=(await t.question(`${e} [Y/n] `)).trim().toLowerCase();return r===""||r==="y"||r==="yes"}finally{t.close()}},"confirm");var P1=Object.defineProperty,tr=b((e,t)=>P1(e,"name",{value:t,configurable:!0}),"a$7");const Eu=[".secretlintrc",".secretlintrc.json",".secretlintrc.js",".secretlintrc.mjs",".secretlintrc.cjs",".secretlintrc.yml",".secretlintrc.yaml"],Tu=[".secretlintignore"],N1=tr(e=>Eu.find(t=>E(v(e,t))),"detectSecretlintConfig"),M1=tr(e=>Tu.find(t=>E(v(e,t))),"detectSecretlintIgnore"),D1=tr((e,t,r)=>{if(t.endsWith(".js")||t.endsWith(".mjs")||t.endsWith(".cjs"))return qe(r,`${t} is a JS config — cannot auto-extract rule IDs. Review manually to confirm coverage.`),[];if(t.endsWith(".yml")||t.endsWith(".yaml"))return qe(r,`${t} is YAML — cannot auto-extract rule IDs without a YAML parser. Review manually.`),[];const n=yt(v(e,t));if(!n)return[];const o=new Set,i=tr(s=>{if(s)for(const a of s)a.id&&o.add(a.id),a.rules&&i(a.rules)},"walk");return i(n.rules),[...o]},"extractRuleIds"),B1=tr((e,t,r,n)=>{for(const o of[...Eu,...Tu]){const i=v(e,o);if(E(i)){if(t){r.info(`[dry-run] Would remove ${i}`);continue}Pe(i,n),Dr(i),Ft(n,"secretlint","removedConfigCount"),r.info(`Removed ${i}`)}}},"removeSecretlintConfigFiles"),F1=tr((e,t,r,n)=>{const o=v(e,".secretlintignore");if(!E(o))return;const i=q(o).split(/\r?\n/).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));i.length!==0&&(rt(n,`.secretlintignore contained ${String(i.length)} path pattern(s). vis secrets uses .gitignore + --exclude / --exclude-from; add these globs to your .gitignore or pass --exclude: ${i.slice(0,5).join(", ")}${i.length>5?", ...":""}`),t&&r.info(`[dry-run] Would consume ${o} (${String(i.length)} patterns) and surface as manual step.`))},"convertIgnoreFile"),L1=tr((e,t,r,n)=>{const o=v(e,"package.json");if(!E(o))return;const i=yt(o);if(!i)return;let s=!1;if(i.scripts){for(const[a,c]of Object.entries(i.scripts))if(typeof c=="string"&&/\bsecretlint\b/.test(c)){const d=c.replaceAll(/\bsecretlint\b[^\n&|;]*/g,"vis secrets").trim();d!==c&&(i.scripts[a]=d,s=!0,Ft(n,"secretlint","rewrittenScriptCount"),r.info(` scripts.${a}: "${c}" -> "${d}"`))}}if(i.devDependencies){const a=i.devDependencies,c=[];for(const d of Object.keys(a))(d==="secretlint"||d.startsWith("@secretlint/"))&&(delete a[d],c.push(d),s=!0,Ft(n,"secretlint","removedPackageCount"));c.length>0&&r.info(` removed ${String(c.length)} secretlint devDependencies: ${c.join(", ")}`)}if(s){if(t){r.info(`[dry-run] Would update ${o}`);return}Pe(o,n),Z(o,`${JSON.stringify(i,null,4)}
896
- `)}},"rewriteScripts"),V1=tr((e,t,r,n)=>{const o=[".husky/pre-commit",".vis-hooks/pre-commit",".git/hooks/pre-commit"];for(const i of o){const s=v(e,i);if(!E(s))continue;const a=q(s);if(!/\bsecretlint\b/.test(a))continue;const c=a.replaceAll(/\bsecretlint\b[^\n&|;]*/g,"vis secrets --staged");if(t){r.info(`[dry-run] Would rewrite ${s}`);continue}Pe(s,n),Z(s,c),n.gitHooksConfigured=!0,r.info(`Rewrote secretlint invocation in ${i}`)}},"rewriteHooks"),_1=tr((e,t,r,n)=>{const o=N1(e),i=M1(e);if(!(o??i))return t.silent||r.info("No secretlint artifacts found — nothing to migrate."),!1;if(o){const s=D1(e,o,n);r.info(`Found ${o}`),s.length>0?(r.info(` active rules/presets: ${s.join(", ")}`),rt(n,`secretlint used these rules: ${s.join(", ")}. vis secrets ships the gitleaks ruleset (177 rules covering AWS/GCP/Azure/GitHub/Slack/Stripe and more). Verify parity before removing secretlint.`)):rt(n,`Rule IDs could not be auto-extracted from ${o}. Verify that the bundled gitleaks ruleset covers your secretlint rule set.`)}return F1(e,t.dryRun,r,n),L1(e,t.dryRun,r,n),V1(e,t.dryRun,r,n),B1(e,t.dryRun,r,n),!0},"migrateSecretlint");var U1=Object.defineProperty,Gs=b((e,t)=>U1(e,"name",{value:t,configurable:!0}),"u$8");const W1=Gs(e=>e.map(t=>{if(t.startsWith("^"))return{dependencies:!0,target:t.slice(1)};if(t.includes("#")){const[r,n]=t.split("#");return{projects:r,target:n}}return t}),"convertDependsOn"),G1=Gs(e=>{const t=e.tasks??e.pipeline??{},r={};for(const[i,s]of Object.entries(t)){if(i.includes("#"))continue;const a={};s.persistent&&(a.persistent=!0),s.interactive&&(a.interactive=!0);const c={};s.cache===!1&&(c.cache=!1),s.dependsOn&&s.dependsOn.length>0&&(c.dependsOn=W1(s.dependsOn)),s.inputs&&s.inputs.length>0&&(c.inputs=s.inputs),s.outputs&&s.outputs.length>0&&(c.outputs=s.outputs),s.env&&s.env.length>0&&(c.env=s.env),s.passThroughEnv&&s.passThroughEnv.length>0&&(c.passThroughEnv=s.passThroughEnv),Object.keys(a).length>0&&(c.options=a),r[i]=c}const n={};Object.keys(r).length>0&&(n.targetDefaults=r);const o={};return e.globalDependencies&&e.globalDependencies.length>0&&(o.globalInputs=e.globalDependencies),e.globalEnv&&e.globalEnv.length>0&&(o.globalEnv=e.globalEnv),e.globalPassThroughEnv&&e.globalPassThroughEnv.length>0&&(o.globalPassThroughEnv=e.globalPassThroughEnv),Object.keys(o).length>0&&(n.taskRunnerOptions=o),["// Migrated from turbo.json by `vis migrate turborepo`.","// Review the generated targetDefaults and move project-specific tasks","// into each project's project.json.","",'import { defineConfig } from "@visulima/vis/config";',"",`export default defineConfig(${Us(n)});`,""].join(`
897
- `)},"renderVisConfig"),H1=Gs((e,t,r,n)=>{const o=xu(e,"turbo.json");if(!o){r.warn("No turbo.json found in workspace root — nothing to migrate."),n.warnings.push("No turbo.json at workspace root.");return}const i=G1(o);if(!Ws(e,i,t,r,n))return;n.manualSteps.push("Review targetDefaults in vis.config.ts — project-specific tasks (turbo's project#task syntax) were skipped and should be moved into each project's project.json.");const s=o.tasks??o.pipeline??{};Object.values(s).some(a=>a.outputLogs!==void 0)&&n.warnings.push("`outputLogs` was found on one or more tasks but vis has no equivalent setting — review and remove."),o.remoteCache?.enabled&&n.manualSteps.push("turbo remote cache detected. vis speaks the same HTTP protocol — set taskRunnerOptions.remoteCache { url, token, teamId } in vis.config.ts.")},"migrateTurborepo");var z1=Object.defineProperty,li=b((e,t)=>z1(e,"name",{value:t,configurable:!0}),"c$e");const q1=[".husky/pre-commit",".vis-hooks/pre-commit",".git/hooks/pre-commit"],J1=[".secretlintrc",".secretlintrc.json",".secretlintrc.js",".secretlintrc.mjs",".secretlintrc.cjs",".secretlintrc.yml",".secretlintrc.yaml"],Y1=li(e=>{const t=v(e,"package.json");if(!E(t))return[];let r;try{r=JSON.parse(q(t))}catch{return[]}const n=[];if(r.scripts)for(const[o,i]of Object.entries(r.scripts))typeof i=="string"&&(/\bgitleaks\b/.test(i)&&n.push({detail:`Script "${o}" still invokes gitleaks: ${i}`,kind:"script",location:"package.json"}),/\bsecretlint\b/.test(i)&&n.push({detail:`Script "${o}" still invokes secretlint: ${i}`,kind:"script",location:"package.json"}));if(r.devDependencies)for(const o of Object.keys(r.devDependencies))(o==="gitleaks"||o==="@gitleaks/cli")&&n.push({detail:`devDependency \`${o}\` is still installed`,kind:"devDep",location:"package.json"}),(o==="secretlint"||o.startsWith("@secretlint/"))&&n.push({detail:`devDependency \`${o}\` is still installed`,kind:"devDep",location:"package.json"});return n},"scanPackageJson"),K1=li(e=>{const t=[];for(const r of q1){const n=v(e,r);if(!E(n))continue;const o=q(n);/\bgitleaks\b/.test(o)&&t.push({detail:"gitleaks invocation still present in hook",kind:"hook",location:r}),/\bsecretlint\b/.test(o)&&t.push({detail:"secretlint invocation still present in hook",kind:"hook",location:r})}return t},"scanHooks"),X1=li(e=>{const t=[];for(const r of J1)E(v(e,r))&&t.push({detail:"secretlint config should be removed after migration",kind:"config",location:r});return t},"scanConfigs"),Q1=li((e,t)=>{const r=[...Y1(e),...K1(e),...X1(e)];if(r.length===0)return t.info("✓ No unmigrated gitleaks/secretlint references found."),[];t.warn(`Found ${String(r.length)} unmigrated reference(s):`);for(const n of r)t.warn(` [${n.kind}] ${n.location} — ${n.detail}`);return r},"verifyMigration");var Z1=Object.defineProperty,tt=b((e,t)=>Z1(e,"name",{value:t,configurable:!0}),"r$6");const Ut=tt((e,t)=>{t.info("── Migration Summary ──");const r=[["Staged configs merged into vis.config.ts",e.mergedStagedConfigCount],["Lint-staged configs inlined",e.inlinedLintStagedConfigCount],["Config files removed",e.removedConfigCount],["Packages removed",e.removedPackageCount],["Scripts rewritten",e.rewrittenScriptCount]];for(const[o,i]of r)i>0&&t.info(` ${o}: ${String(i)}`);e.gitHooksConfigured&&t.info(" Pre-commit hook updated to use vis staged");const n=Object.entries(e.perMigration);if(n.length>0){t.info(""),t.info("By migration:");for(const[o,i]of n){const s=[];i.removedConfigCount>0&&s.push(`${String(i.removedConfigCount)} config(s) removed`),i.removedPackageCount>0&&s.push(`${String(i.removedPackageCount)} package(s) removed`),i.rewrittenScriptCount>0&&s.push(`${String(i.rewrittenScriptCount)} script(s) rewritten`),t.info(` ${o}: ${s.join(", ")||"no changes"}`)}}if(e.backupsCreated.length>0&&(t.info(""),t.info(`Created ${String(e.backupsCreated.length)} .bak file(s) for rollback. Remove them once you're happy.`)),e.warnings.length>0){t.info(""),t.warn("Warnings:");for(const o of e.warnings)t.warn(` - ${o}`)}if(e.manualSteps.length>0){t.info(""),t.info("Manual steps required:");for(const o of e.manualSteps)t.info(` - ${o}`)}},"printSummary"),Wt=tt(e=>{const t=e.workspaceRoot??process.cwd();return{config:e.visConfig??{},dryRun:!!e.options.dryRun,logger:e.logger,packageManager:iu(t),report:SC(),root:t}},"buildContext"),ir=tt(async(e,t,r)=>{if(t.yes||t.dryRun)return!0;const n=await O1(`This will edit files, scripts, and hooks for "${e}". Backups (.bak) will be created. Continue?`);return n||r.info("Aborted."),n},"maybeConfirm"),Gt=tt(e=>{e.dryRun&&e.logger.info(`Running in dry-run mode — no changes will be made.
898
- `)},"announceDryRun"),Ht=[{defaultValue:!1,description:"Preview changes without applying",name:"dry-run",type:Boolean},{alias:"y",defaultValue:!1,description:"Skip the confirmation prompt",name:"yes",type:Boolean}],ej={commandPath:["migrate"],description:"Run all built-in migrations (deps, lint-staged, nano-staged)",examples:[["vis migrate all","Run all built-in migrations"]],execute:tt(({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{const o=Wt({logger:e,options:t,visConfig:r,workspaceRoot:n});Gt(o),e.info("── Migrating dependencies and scripts ──"),mu(o.root,o.packageManager,o.config,{dryRun:o.dryRun},e,o.report),e.info(""),e.info("── Migrating lint-staged ──"),$u(o.root,{dryRun:o.dryRun},e,o.report),e.info(""),e.info("── Migrating nano-staged ──"),Cu(o.root,{dryRun:o.dryRun},e,o.report),e.info(""),Ut(o.report,e)},"execute"),group:"Scaffold & Config",name:"all",options:[...Ht]},tj={commandPath:["migrate"],description:"Migrate dependencies and scripts to vis",execute:tt(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!await ir("deps",t,e))return;const o=Wt({logger:e,options:t,visConfig:r,workspaceRoot:n});Gt(o),e.info("── Migrating dependencies and scripts ──"),mu(o.root,o.packageManager,o.config,{dryRun:o.dryRun},e,o.report),e.info(""),Ut(o.report,e)},"execute"),group:"Scaffold & Config",name:"deps",options:[...Ht]},rj={commandPath:["migrate"],description:"Inline lint-staged configuration into vis",execute:tt(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!await ir("lint-staged",t,e))return;const o=Wt({logger:e,options:t,visConfig:r,workspaceRoot:n});Gt(o),e.info("── Migrating lint-staged ──"),$u(o.root,{dryRun:o.dryRun},e,o.report),e.info(""),Ut(o.report,e)},"execute"),group:"Scaffold & Config",name:"lint-staged",options:[...Ht]},nj={commandPath:["migrate"],description:"Inline nano-staged configuration into vis",execute:tt(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!await ir("nano-staged",t,e))return;const o=Wt({logger:e,options:t,visConfig:r,workspaceRoot:n});Gt(o),e.info("── Migrating nano-staged ──"),Cu(o.root,{dryRun:o.dryRun},e,o.report),e.info(""),Ut(o.report,e)},"execute"),group:"Scaffold & Config",name:"nano-staged",options:[...Ht]},oj={commandPath:["migrate"],description:"Migrate turborepo tasks/config to vis",execute:tt(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!await ir("turborepo",t,e))return;const o=Wt({logger:e,options:t,visConfig:r,workspaceRoot:n});Gt(o),e.info("── Migrating turborepo ──"),H1(o.root,{dryRun:o.dryRun},e,o.report),e.info(""),Ut(o.report,e)},"execute"),group:"Scaffold & Config",name:"turborepo",options:[...Ht]},ij={commandPath:["migrate"],description:"Migrate nx targets/config to vis",execute:tt(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!await ir("nx",t,e))return;const o=Wt({logger:e,options:t,visConfig:r,workspaceRoot:n});Gt(o),e.info("── Migrating nx ──"),R1(o.root,{dryRun:o.dryRun},e,o.report),e.info(""),Ut(o.report,e)},"execute"),group:"Scaffold & Config",name:"nx",options:[...Ht]},sj={commandPath:["migrate"],description:"Migrate moon tasks/templates to vis",execute:tt(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!await ir("moon",t,e))return;const o=Wt({logger:e,options:t,visConfig:r,workspaceRoot:n});Gt(o),e.info("── Migrating moon ──"),p1(o.root,{copyTemplates:!!t.copyTemplates,dryRun:o.dryRun},e,o.report),e.info(""),Ut(o.report,e)},"execute"),group:"Scaffold & Config",name:"moon",options:[...Ht,{defaultValue:!1,description:"Copy .moon/templates/* into .vis/templates/* so `vis generate` works without .moon/",name:"copy-templates",type:Boolean}]},aj={commandPath:["migrate"],description:"Migrate gitleaks config/baseline/hooks to `vis secrets`",examples:[["vis migrate gitleaks","Migrate gitleaks config/baseline/hooks to `vis secrets`"]],execute:tt(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!await ir("gitleaks",t,e))return;const o=Wt({logger:e,options:t,visConfig:r,workspaceRoot:n});Gt(o),e.info("── Migrating gitleaks ──"),MC(o.root,{dryRun:o.dryRun},e,o.report),e.info(""),Ut(o.report,e)},"execute"),group:"Scaffold & Config",name:"gitleaks",options:[...Ht]},cj={commandPath:["migrate"],description:"Migrate Kingfisher baseline/hooks/scripts to `vis secrets`",examples:[["vis migrate kingfisher","Migrate Kingfisher baseline/hooks/scripts to `vis secrets`"]],execute:tt(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!await ir("kingfisher",t,e))return;const o=Wt({logger:e,options:t,visConfig:r,workspaceRoot:n});Gt(o),e.info("── Migrating Kingfisher ──"),GC(o.root,{dryRun:o.dryRun},e,o.report),e.info(""),Ut(o.report,e)},"execute"),group:"Scaffold & Config",name:"kingfisher",options:[...Ht]},lj={commandPath:["migrate"],description:"Replace secretlint with `vis secrets`",examples:[["vis migrate secretlint","Replace secretlint with `vis secrets`"]],execute:tt(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!await ir("secretlint",t,e))return;const o=Wt({logger:e,options:t,visConfig:r,workspaceRoot:n});Gt(o),e.info("── Migrating secretlint ──"),_1(o.root,{dryRun:o.dryRun},e,o.report),e.info(""),Ut(o.report,e)},"execute"),group:"Scaffold & Config",name:"secretlint",options:[...Ht]},dj={commandPath:["migrate"],description:"Audit the workspace for stray gitleaks/secretlint references (exit 1 on issues)",examples:[["vis migrate verify","Audit the workspace for stray gitleaks/secretlint references (exit 1 on issues)"]],execute:tt(({logger:e,workspaceRoot:t})=>{const r=t??process.cwd();Q1(r,e).length>0&&(process.exitCode=1)},"execute"),group:"Scaffold & Config",name:"verify",options:[]},uj=[ej,tj,rj,nj,oj,ij,sj,aj,cj,lj,dj];var pj=Object.defineProperty,fj=b((e,t)=>pj(e,"name",{value:t,configurable:!0}),"a$5");const gj={argument:{description:"Subcommand and arguments (e.g., cache dir, publish --dry-run, list --depth 0)",name:"args",type:String},description:"Package manager utilities (cache, publish, audit, list, config, etc.)",examples:[["vis pm cache dir","Show cache directory"],["vis pm cache clean","Clean cache"],["vis pm publish --dry-run","Preview publishing"],["vis pm list --depth 0","List direct dependencies"],["vis pm audit","Run security audit"],["vis pm whoami","Show logged-in user"]],execute:fj(async({argument:e,logger:t,workspaceRoot:r})=>{const n=e;if(!n||n.length===0)throw new Error("No subcommand specified. Available: cache, publish, audit, list, view, config, whoami, login, logout, pack, owner, dist-tag, search, fund, ping, token, deprecate, rebuild, prune");const[o,...i]=n,s=r??process.cwd(),a=Ne(s),c=Im(a,o,i,s,t);c!==0&&(process.exitCode=c)},"execute"),group:"System",name:"pm"};var mj=Object.defineProperty,hj=b((e,t)=>mj(e,"name",{value:t,configurable:!0}),"t$7");const yj={alias:["rm","un","uninstall"],argument:{description:"Packages to remove",name:"packages",type:String},description:"Remove packages using the detected package manager",examples:[["vis remove lodash","Remove a package"],["vis rm old-package","Remove using alias"],["vis remove --filter app react","Remove from specific workspace"],["vis remove -g typescript","Remove global package"]],execute:hj(async({argument:e,logger:t,options:r,workspaceRoot:n})=>{const o=e;if(!o||o.length===0)throw new Error("No packages specified. Usage: vis remove <packages...>");const i=process.cwd(),s=Ne(n??i),a=xm(s,{filter:Yn(r.filter),global:r.global||!1,packages:o,recursive:r.recursive||!1,saveDev:r.saveDev||!1,workspaceRoot:r.workspaceRoot||!1},i,t);a!==0&&(process.exitCode=a)},"execute"),group:"Dependencies",name:"remove",options:[{alias:"D",defaultValue:!1,description:"Remove from devDependencies",name:"save-dev",type:Boolean},{alias:"g",defaultValue:!1,description:"Remove global package",name:"global",type:Boolean},{alias:"r",defaultValue:!1,description:"Remove from all workspace packages",name:"recursive",type:Boolean},{alias:"w",defaultValue:!1,description:"Remove from workspace root",name:"workspace-root",type:Boolean},{alias:"F",description:"Filter by workspace package name",multiple:!0,name:"filter",type:String}]};var vj=Object.defineProperty,Hs=b((e,t)=>vj(e,"name",{value:t,configurable:!0}),"i$6");const wj=Hs((e,t)=>{let r=0,n=0,o=0;for(const[,a]of e)switch(a.status){case"failure":{o+=1;break}case"local-cache":case"local-cache-kept-existing":case"remote-cache":{n+=1;break}case"success":{r+=1;break}}const i=[];r>0&&i.push(`${String(r)} succeeded`),n>0&&i.push(`${String(n)} cached`),o>0&&i.push(`${String(o)} failed`);const s=(t/1e3).toFixed(1);return i.push(`${s}s`),i.join(" · ")},"formatTimingSummary"),zs=Hs(e=>{const t=v(e,".task-runner","runs");if(!E(t))return[];const r=Ve(t).filter(o=>o.endsWith(".json")),n=[];for(const o of r)try{n.push(ue(v(t,o)))}catch{}return n},"loadRunSummaries"),kj=Hs((e,t,r)=>{const n=r??zs(e);if(n.length<2)return;let o=0,i=0;for(const c of n)typeof c.duration=="number"&&c.duration>0&&(o+=c.duration,i+=1);if(i<2)return;const s=o/i-t,a=Math.abs(s/1e3).toFixed(1);return Math.abs(s)<500?"(about average)":s>0?`(${a}s faster than avg)`:`(${a}s slower than avg)`},"compareDuration");var bj=Object.defineProperty,Gi=b((e,t)=>bj(e,"name",{value:t,configurable:!0}),"c$c");const Ru=Gi((e,t={},r)=>{const n=r??zs(e);if(n.length===0)return[];const o=new Map;for(const a of n)if(!(t.since&&(a.startTime===void 0||a.startTime<t.since))&&Array.isArray(a.tasks))for(const c of a.tasks){if(c.cacheStatus==="HIT"||c.cacheStatus==="REMOTE_HIT"||c.cacheStatus==="SKIPPED")continue;const d=o.get(c.taskId)??{failures:0,project:c.target.project,successes:0,target:c.target.target,totalRuns:0};d.totalRuns+=1,c.exitCode!==void 0&&c.exitCode!==0?(d.failures+=1,d.lastFailure=c.startTime??a.startTime):d.successes+=1,o.set(c.taskId,d)}const i=t.minRuns??2,s=[];for(const[a,c]of o)c.totalRuns<i||c.failures!==0&&s.push({failures:c.failures,flakinessRate:c.failures/c.totalRuns,lastFailure:c.lastFailure,project:c.project,successes:c.successes,target:c.target,taskId:a,totalRuns:c.totalRuns});return s.sort((a,c)=>c.flakinessRate-a.flakinessRate),s},"analyzeFlakiness"),$j=Gi(e=>{if(e.length===0)return["No flaky tasks detected."];const t=["Task","Runs","Failures","Rate","Last Failure"],r=e.map(a=>[a.taskId,String(a.totalRuns),String(a.failures),`${(a.flakinessRate*100).toFixed(1)}%`,a.lastFailure??"—"]),n=t.map((a,c)=>{const d=r.reduce((p,g)=>Math.max(p,(g[c]??"").length),0);return Math.max(a.length,d)}),o=Gi((a,c)=>a.padEnd(c),"pad"),i=n.map(a=>"─".repeat(a)).join("──"),s=[];s.push(t.map((a,c)=>o(a,n[c])).join(" ")),s.push(i);for(const a of r)s.push(a.map((c,d)=>o(c,n[d])).join(" "));return s},"formatFlakinessTable");var xj=Object.defineProperty,di=b((e,t)=>xj(e,"name",{value:t,configurable:!0}),"t$6");const Sj=di(()=>Zp(),"createVisHooks"),Cj=di(async(e,t)=>{if(!(!t||t.length===0))for(const r of t){if(r.hooks)for(const[n,o]of Object.entries(r.hooks)){const i=Array.isArray(o)?o:[o];for(const s of i)e.hook(n,s)}r.setup&&await r.setup(e)}},"registerPlugins");class jj{static{b(this,"HookableLifeCycle")}static{di(this,"HookableLifeCycle")}#e;#t;#n=new Map;constructor(t,r){this.#e=t,this.#t=r}startTasks(t){for(const r of t)this.#n.set(r.id,r),this.#o("task:before",r)}endTasks(t){for(const r of t)this.#n.delete(r.task.id),this.#o("task:after",r.task,r),r.status==="failure"?this.#o("task:failure",r.task,r):Ej(r.status)&&this.#o("task:cacheHit",r.task,r)}printCacheMiss(t,r){this.#o("task:cacheMiss",t,r)}onTaskStdout(t,r){this.#o("task:stdout",t,r)}onTaskStderr(t,r){this.#o("task:stderr",t,r)}#o(t,...r){Promise.resolve(this.#e.callHook(t,...r)).catch(n=>{if(this.#t)try{this.#t(t,n)}catch{}})}}const Ej=di(e=>e==="local-cache"||e==="local-cache-kept-existing"||e==="remote-cache","isCacheStatus");var Tj=Object.defineProperty,ui=b((e,t)=>Tj(e,"name",{value:t,configurable:!0}),"o$5");const Rj=ui(async e=>{if(process.env.VIS_NO_SHELL_HISTORY||Qc()==="win32")return;const t=process.env.SHELL;if(!t)return;const r=Do(t);try{if(r==="zsh"){await Aj(e);return}if(r==="bash"){await Ij(e);return}r==="fish"&&await Oj(e)}catch{}},"appendToShellHistory"),Aj=ui(async e=>{const t=process.env.HISTFILE??v(process.env.ZDOTDIR??Qe(),".zsh_history"),r=`: ${Math.floor(Date.now()/1e3)}:0;${e}
899
- `;await ss(t,r)},"writeZshHistory"),Ij=ui(async e=>{const t=process.env.HISTFILE??v(Qe(),".bash_history");await ss(t,`${e}
900
- `)},"writeBashHistory"),Oj=ui(async e=>{const t=v(Qe(),".local","share","fish","fish_history"),r=`- cmd: ${e.replaceAll("\\","\\\\").replaceAll(`
901
- `,String.raw`\n`)}
902
- when: ${Math.floor(Date.now()/1e3)}
903
- `;await ss(t,r)},"writeFishHistory");var Pj=Object.defineProperty,br=b((e,t)=>Pj(e,"name",{value:t,configurable:!0}),"i$5");const kc=br(e=>{const t=new Set;for(const r of Object.values(e.projects))for(const n of Object.keys(r.targets??{}))t.add(n);return[...t].sort()},"collectAvailableTargets"),Nj=br(e=>{const t=new Map;for(const r of e.values())for(const[n,o]of Object.entries(r))for(const i of o.aliases??[])t.has(i)||t.set(i,n);return t},"buildAliasMap"),Mj=br((e,t)=>t.get(e)??e,"resolveTargetAlias"),Dj=br((e,t)=>{if(e.length===0)return t.length;if(t.length===0)return e.length;const r=[];for(let n=0;n<=t.length;n++)r[n]=[n];for(let n=0;n<=e.length;n++)r[0][n]=n;for(let n=1;n<=t.length;n++)for(let o=1;o<=e.length;o++){const i=t[n-1]===e[o-1]?0:1;r[n][o]=Math.min(r[n-1][o]+1,r[n][o-1]+1,r[n-1][o-1]+i)}return r[t.length][e.length]},"levenshtein"),Bj=br((e,t,r=3)=>Au(e,t,1,r)[0],"suggestTarget"),Au=br((e,t,r=3,n=3)=>{const o=[];for(const i of t){const s=Dj(e.toLowerCase(),i.toLowerCase());s<=n&&o.push({distance:s,name:i})}return o.sort((i,s)=>i.distance-s.distance||i.name.localeCompare(s.name)),o.slice(0,r).map(i=>i.name)},"suggestTargets"),Fj=br(e=>e.length===0?" (no targets found)":e.map(t=>` - ${t}`).join(`
904
- `),"formatTargetList"),Lj=br(async e=>{if(e.length===0||!process.stdin.isTTY||!process.stdout.isTTY)return;const t=gt({input:process.stdin,output:process.stdout});try{process.stdout.write(`Available targets:
905
- `);for(const[o,i]of e.entries())process.stdout.write(` ${String(o+1).padStart(2," ")}. ${i}
906
- `);process.stdout.write(`
907
- `);const r=(await new Promise(o=>{t.question("Select a target (number or name, blank to cancel): ",o)})).trim();if(r.length===0)return;const n=Number.parseInt(r,10);return Number.isFinite(n)&&n>=1&&n<=e.length?e[n-1]:e.includes(r)?r:Bj(r,e)}finally{t.close()}},"promptTargetInteractively");var Vj=Object.defineProperty,qs=b((e,t)=>Vj(e,"name",{value:t,configurable:!0}),"i$4");const _j=qs(e=>Array.isArray(e)?`[${e.join(",")}]`:typeof e=="object"&&e!==null?JSON.stringify(e):String(e),"formatValue"),Uj=qs((e,t,r)=>t==="_"?`${e}${Array.isArray(r)?r.join(" "):String(r)}`:`${e}--${t}=${_j(r)}`,"formatFlags"),Js=qs((e,t,r)=>{const n=new Set(new Set(r.map(h=>h.target.target))),o=new Set(new Set(r.map(h=>h.target.project))),i=t.filter(h=>n.has(h)),s=e.filter(h=>o.has(h)),a=r.length-s.length*i.length,c=i.length===1?"target":"targets",d=i.join(", ");let p;p=s.length===1?`project ${s[0]}`:`${s.length} projects`;let g=`${c} ${d} for ${p}`;return a>0&&(g+=` and ${a} ${a===1?"task":"tasks"} ${a===1?"it depends":"they depend"} on`),g},"formatTargetsAndProjects");var Wj=Object.defineProperty,Gj=b((e,t)=>Wj(e,"name",{value:t,configurable:!0}),"c$8");const Hj={error:"red",info:"white",success:"green"},Hi=Gj(({children:e,title:t,variant:r})=>{const n=Hj[r];return f(m,{flexDirection:"column",children:[f(m,{gap:1,children:[u(l,{bold:!0,inverse:!0,children:" VIS "}),u(l,{bold:!0,color:n,children:"•"}),u(l,{children:t})]}),e]})},"Header");var zj=Object.defineProperty,qj=b((e,t)=>zj(e,"name",{value:t,configurable:!0}),"s$8");const Iu=qj(({cached:e,failed:t,failedIds:r,projectNames:n,skippedIds:o,succeeded:i,targets:s,tasks:a,took:c})=>{const d=Js(n,s,a);if(t===0&&(!o||o.length===0)){const p=e>0?` (${e} read from cache)`:"";return u(oa,{children:b(()=>u(Hi,{title:`Successfully ran ${d}`,variant:"success",children:f(m,{flexDirection:"column",paddingLeft:2,children:[f(l,{children:[u(l,{color:"green",children:_o})," ",i+e," ","tasks completed",p?u(l,{dimColor:!0,children:p}):null]}),f(l,{dimColor:!0,children:[" ","Took",c]})]})}),"children")})}return u(oa,{children:b(()=>u(Hi,{title:`Ran ${d}`,variant:"error",children:f(m,{flexDirection:"column",paddingLeft:2,children:[o&&o.length>0&&f(m,{flexDirection:"column",children:[f(l,{dimColor:!0,children:[o.length," ","task",o.length===1?"":"s"," ","skipped (dependency failed or --bail)"]}),o.map(p=>f(l,{dimColor:!0,children:[" - ",p]},p)),u(l,{})]}),t>0&&f(m,{flexDirection:"column",children:[f(l,{children:[u(l,{color:"red",children:String(t)})," ","task",t===1?"":"s"," ","failed:"]}),r.map(p=>f(l,{children:[" ",u(l,{color:"red",children:qn})," ",p]},p)),u(l,{})]}),f(l,{dimColor:!0,children:[" ","Took",c]})]})}),"children")})},"CommandSummary");var Jj=Object.defineProperty,Ri=b((e,t)=>Jj(e,"name",{value:t,configurable:!0}),"u$6");class Oo{static{b(this,"TaskStore")}static{Ri(this,"TaskStore")}#e;#t=new Set;#n=new Map;constructor(t){this.#e={autoExitCountdown:null,cached:0,completed:0,done:!1,endTime:null,failed:0,filterActive:!1,filterText:"",focusedPanel:"tasks",interactiveMode:!1,outputs:new Map,pinnedTaskIds:[null,null],rerunRequested:!1,retryTaskId:null,rows:t.map(r=>({status:"pending",taskId:r.id})),selectedIndex:0,startTime:Date.now(),statusFilter:"all",succeeded:0,viewMode:"list"}}getSnapshot=Ri(()=>this.#e,"getSnapshot");subscribe=Ri(t=>(this.#t.add(t),()=>{this.#t.delete(t)}),"subscribe");startTasks(t){const r=[...this.#e.rows];for(const n of t){const o=r.findIndex(i=>i.taskId===n.id);o!==-1&&(r[o]={...r[o],elapsed:0,status:"running"},this.#n.set(n.id,process.hrtime()))}this.#r({...this.#e,rows:r})}endTasks(t){const r=[...this.#e.rows];let{cached:n,completed:o,failed:i,succeeded:s}=this.#e;const a=new Map(this.#e.outputs);for(const d of t){const p=r.findIndex(g=>g.taskId===d.task.id);switch(p!==-1&&(r[p]={...r[p],duration:d.startTime&&d.endTime?d.endTime-d.startTime:void 0,status:d.status}),o++,d.status){case"failure":{i++;break}case"local-cache":case"local-cache-kept-existing":case"remote-cache":{n++;break}case"success":{s++;break}}d.terminalOutput&&!a.has(d.task.id)&&a.set(d.task.id,d.terminalOutput),this.#n.delete(d.task.id)}let{selectedIndex:c}=this.#e;if(i>this.#e.failed){const d=r.findIndex(p=>p.status==="failure");d!==-1&&(c=d)}this.#r({...this.#e,cached:n,completed:o,failed:i,outputs:a,rows:r,selectedIndex:c,succeeded:s})}static#o=256*1024;addOutput(t,r){if(!r.trim())return;let n=(this.#e.outputs.get(t)??"")+r;n.length>Oo.#o&&(n=n.slice(-Oo.#o)),this.#e.outputs.set(t,n),this.#r({...this.#e})}setOutput(t,r){this.#e.outputs.set(t,r),this.#r({...this.#e})}markDone(){this.#r({...this.#e,done:!0,endTime:Date.now()})}tick(){if(this.#n.size===0)return;let t=!1;const r=[...this.#e.rows];for(let n=0;n<r.length;n++){const o=r[n];if(o.status==="running"){const i=this.#n.get(o.taskId);if(i){const s=process.hrtime(i),a=s[0]*1e3+s[1]/1e6;r[n]={...o,elapsed:a},t=!0}}}t&&this.#r({...this.#e,rows:r})}setSelectedIndex(t){t!==this.#e.selectedIndex&&this.#r({...this.#e,selectedIndex:t})}setFocusedPanel(t){t!==this.#e.focusedPanel&&this.#r({...this.#e,focusedPanel:t})}setFilter(t){this.#r({...this.#e,filterText:t,selectedIndex:0})}setFilterActive(t){t!==this.#e.filterActive&&this.#r({...this.#e,filterActive:t,filterText:t?this.#e.filterText:"",selectedIndex:0})}pinTask(t,r){const n=[...this.#e.pinnedTaskIds];n[t]=r,this.#r({...this.#e,pinnedTaskIds:n})}clearPins(){this.#r({...this.#e,pinnedTaskIds:[null,null]})}requestRetry(t){const r=[...this.#e.rows],n=r.findIndex(a=>a.taskId===t);let{completed:o,failed:i,succeeded:s}=this.#e;if(n!==-1){const a=r[n].status;a==="failure"?(i=Math.max(0,i-1),o=Math.max(0,o-1)):a==="success"&&(s=Math.max(0,s-1),o=Math.max(0,o-1)),r[n]={...r[n],elapsed:0,status:"running"},this.#n.set(t,process.hrtime())}this.#r({...this.#e,completed:o,done:!1,endTime:null,failed:i,interactiveMode:!1,retryTaskId:t,rows:r,succeeded:s})}acknowledgeRetry(){const t=this.#e.retryTaskId;return t&&this.#r({...this.#e,retryTaskId:null}),t}setInteractiveMode(t){t!==this.#e.interactiveMode&&this.#r({...this.#e,interactiveMode:t})}setViewMode(t){t!==this.#e.viewMode&&this.#r({...this.#e,viewMode:t})}setStatusFilter(t){this.#r({...this.#e,selectedIndex:0,statusFilter:t})}requestRerun(){this.#n.clear(),this.#r({...this.#e,autoExitCountdown:null,cached:0,completed:0,done:!1,endTime:null,failed:0,interactiveMode:!1,outputs:new Map,rerunRequested:!0,rows:this.#e.rows.map(t=>({status:"pending",taskId:t.taskId})),startTime:Date.now(),succeeded:0,viewMode:"list"})}acknowledgeRerun(){this.#e.rerunRequested&&this.#r({...this.#e,rerunRequested:!1})}#r(t){this.#e=t;for(const r of this.#t)try{r()}catch{}}}var Yj=Object.defineProperty,Rt=b((e,t)=>Yj(e,"name",{value:t,configurable:!0}),"t$5");const Kj={d:Rt(()=>" d","d"),future:"in %s",h:Rt(()=>" h","h"),m:Rt(()=>" m","m"),mo:Rt(()=>" mo","mo"),ms:Rt(()=>" ms","ms"),past:"%s ago",s:Rt(()=>" s","s"),w:Rt(()=>" w","w"),y:Rt(()=>" y","y")},Ou={delimiter:" ",language:Kj,largest:2,round:!0,spacer:"",units:["h","m","s","ms"]};Rt(e=>{const t=e[0]*1e3+e[1]/1e6;return ul(t,Ou)},"formatHrtime");const Mr=Rt(e=>ul(e,Ou),"formatMs");var Xj=Object.defineProperty,ro=b((e,t)=>Xj(e,"name",{value:t,configurable:!0}),"n$3");const Vn=ro(e=>e==="local-cache"||e==="local-cache-kept-existing"||e==="remote-cache","isCacheStatus"),no=ro(e=>{switch(e){case"failure":return{color:"red",icon:qn};case"local-cache":case"local-cache-kept-existing":case"remote-cache":case"success":return{color:"green",icon:_o};case"skipped":return{color:"gray",icon:dr};default:return{color:"gray",icon:"?"}}},"getStatusInfo"),Pu=ro(e=>{const{color:t,icon:r}=no(e);return Oe(Q.createElement(l,{color:t},r),{columns:10}).trim()},"getStatusIcon"),Qj=ro(e=>{const{color:t,icon:r}=no(e);switch(e){case"local-cache":case"local-cache-kept-existing":case"remote-cache":return Oe(Q.createElement(l,null,Q.createElement(l,{color:t},r)," ",Q.createElement(l,{color:"cyan"},"[cache]")),{columns:30}).trim();case"skipped":return Oe(Q.createElement(l,null,Q.createElement(l,{dimColor:!0},r)," ",Q.createElement(l,{dimColor:!0},"[skipped]")),{columns:30}).trim();default:return Oe(Q.createElement(l,{color:t},r),{columns:10}).trim()}},"getStatusPrefix"),Zj=ro((e,t,r)=>{const n=r.trim();if(!n)return;const o=`
908
- `;if(process.env.GITHUB_ACTIONS==="true")process.stdout.write(`::group::${Pu(t)} ${e}${o}`),process.stdout.write(n+o),process.stdout.write(`::endgroup::${o}`);else{const i=process.stdout.columns||80,s=Oe(Q.createElement(l,{dimColor:!0},dr.repeat(i)),{columns:i}).trim(),a=Qj(t),c=Oe(Q.createElement(l,{bold:!0},e),{columns:i}).trim();process.stdout.write(`${s}${o}`),process.stdout.write(`${a} ${c}${o}`),process.stdout.write(n+o),process.stdout.write(`${s}${o}`)}},"logCommandOutputCI");var eE=Object.defineProperty,Nu=b((e,t)=>eE(e,"name",{value:t,configurable:!0}),"c$7");const tE=Nu(e=>e==="running"?{color:"white",icon:"•"}:e==="pending"?{color:"gray",icon:"·"}:no(e),"getDisplayInfo"),bc=Nu(({duration:e,focused:t,interactiveMode:r,output:n,scrollRef:o,showFullscreenHint:i,status:s,taskId:a})=>{const c=s??"pending",{icon:d}=tE(c),p=t?"bold":"single",g=c==="failure"?"red":c==="success"||Vn(c)?t?"green":"gray":c==="running"?t?"white":"cyan":t?"white":"gray",h=a?`${d} ${a}`:void 0,y=e===void 0?void 0:Mr(e),w=a?r?"Esc cancel | Enter send":t&&c==="running"&&i?"⏎ FULLSCREEN i INPUT":t&&c==="running"?"i INPUT":t&&i?"<enter> full screen":t?void 0:"<tab> or <enter> to focus":void 0;if(!a)return f(m,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",paddingX:2,paddingY:1,children:[u(l,{dimColor:!0,children:"Select a task to view output"}),u(l,{dimColor:!0,children:"Press Enter or 1/2 to pin"})]});const k=n?n.split(`
909
- `).map($=>$.replace(/\r$/,"")):[];return!n&&(c==="running"||c==="pending")?u(m,{borderBottomTitle:w,borderColor:g,borderStyle:p,borderTopRightTitle:y,borderTopTitle:h,flexDirection:"column",flexGrow:1,paddingX:2,paddingY:1,children:u(m,{alignItems:"center",flexGrow:1,justifyContent:"center",children:u(l,{dimColor:!0,children:"Waiting for task output..."})})}):f(m,{borderBottomTitle:w,borderColor:r?"yellow":g,borderStyle:p,borderTopRightTitle:y,borderTopTitle:h,flexDirection:"column",flexGrow:1,children:[u(m,{flexGrow:1,flexShrink:1,paddingY:1,children:u(cn,{flexGrow:1,followOutput:!0,paddingX:2,ref:o,scrollbar:!0,scrollbarColor:"gray",scrollbarStyle:"block",children:k.map(($,x)=>u(l,{children:$},String(x)))})}),r&&u(m,{flexShrink:0,justifyContent:"center",paddingX:1,children:u(l,{bold:!0,color:"yellow",children:"INTERACTIVE — keystrokes forwarded to task — Esc to exit"})})]})},"OutputPanel");var rE=Object.defineProperty,pi=b((e,t)=>rE(e,"name",{value:t,configurable:!0}),"u$5");const Mu=6,Du=8,Bu=10,nE=pi(e=>e==="running"||e==="pending"?xl:e==="local-cache"||e==="local-cache-kept-existing"?"Local":e==="remote-cache"?"Remote":dr,"getCacheLabel"),$c=pi((e,t)=>t[0]===e?"[1]":t[1]===e?"[2]":"","getPinLabel"),xc=pi(({compact:e,isSelected:t,pinLabel:r,row:n})=>{const{status:o,taskId:i}=n,s=t?">":" ";let a;if(o==="running")a=f(l,{bold:!0,color:"white",children:[" ",u(ns,{type:"dots"})," "]});else if(o==="pending")a=u(l,{bold:!0,color:"gray",children:" · "});else{const{color:d,icon:p}=no(o);a=f(l,{bold:!0,color:d,children:[" ",p," "]})}let c=xl;return o!=="running"&&o!=="pending"?c=n.duration===void 0?dr:Mr(n.duration):o==="running"&&n.elapsed!==void 0&&(c=Mr(n.elapsed)),f(m,{children:[u(l,{children:s}),u(m,{width:Mu,children:a}),f(m,{flexGrow:1,children:[u(l,{bold:t,inverse:t,children:i}),r?u(l,{dimColor:!0,children:` ${r}`}):null]}),!e&&u(m,{justifyContent:"flex-end",width:Du,children:u(l,{dimColor:!Vn(o),children:nE(o)})}),!e&&u(m,{justifyContent:"flex-end",width:Bu,children:u(l,{dimColor:o==="pending",children:c})})]})},"TaskListRow"),Sc=pi(({compact:e,filterActive:t,filterText:r,focused:n,headerStatus:o,parallelSlots:i=3,pinnedTaskIds:s,rows:a,scrollRef:c,selectedIndex:d,title:p})=>{const g=o==="error"?"red":o==="success"?"green":n?"white":"gray",h=a[d]?.taskId,y=a.filter($=>$.status==="running"),w=y.length>0||a.some($=>$.status==="pending"),k=[];if(w)for(let $=0;$<i;$++){const x=y[$];x?k.push(u(xc,{compact:e,isSelected:x.taskId===h,pinLabel:$c(x.taskId,s),row:x},`par-${x.taskId}`)):k.push(f(m,{children:[u(l,{children:" "}),u(m,{width:Mu,children:u(l,{bold:!0,color:"gray",children:" · "})}),u(l,{dimColor:!0,children:"Waiting for task..."})]},`par-empty-${String($)}`))}return f(m,{borderColor:g,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[f(m,{flexShrink:0,gap:1,paddingX:1,children:[u(l,{bold:!0,inverse:!0,children:" VIS "}),u(l,{children:p}),!e&&f(m,{flexGrow:1,gap:0,justifyContent:"flex-end",children:[u(m,{justifyContent:"flex-end",width:Du,children:u(l,{dimColor:!0,children:"Cache"})}),u(m,{justifyContent:"flex-end",width:Bu,children:u(l,{dimColor:!0,children:"Duration"})})]})]}),u(cn,{flexGrow:1,flexShrink:1,paddingLeft:1,paddingY:1,ref:c,scrollbar:!0,scrollbarColor:"gray",scrollbarStyle:"block",children:a.map($=>u(xc,{compact:e,isSelected:$.taskId===h,pinLabel:$c($.taskId,s),row:$},$.taskId))}),w&&u(m,{borderBottom:!1,borderColor:"gray",borderLeft:!1,borderRight:!1,borderStyle:"single",borderTop:!0,flexDirection:"column",flexShrink:0,paddingLeft:1,paddingY:1,children:k}),t&&f(m,{borderBottom:!1,borderColor:"gray",borderLeft:!1,borderRight:!1,borderStyle:"single",borderTop:!0,flexShrink:0,paddingX:1,children:[u(l,{bold:!0,color:"white",children:"/ "}),u(l,{children:r}),u(l,{inverse:!0,children:" "})]})]})},"TaskListPanel");var oE=Object.defineProperty,iE=b((e,t)=>oE(e,"name",{value:t,configurable:!0}),"y$1");const Cc=40,jc=10,Ec=100,sE=iE(({autoExitSeconds:e,parallelSlots:t,projectNames:r,stdinRegistry:n,store:o,targets:i,tasks:s})=>{const{exit:a}=an(),{columns:c,rows:d}=sn(),p=Hn(o.subscribe,o.getSnapshot),[g,h]=we(!1),y=Ue(null),w=Ue(null),k=Ue(null),[$,x]=we(!1),T=Ue({list:0,splitList:0,splitOutput:0}),I=Nt(()=>{p.viewMode==="list"?T.current.list=w.current?.getScrollOffset()??0:p.viewMode==="split"&&(T.current.splitList=w.current?.getScrollOffset()??0,T.current.splitOutput=k.current?.getScrollOffset()??0)},[p.viewMode]),P=Nt(B=>{setTimeout(()=>{if(B==="list"){const O=T.current.list;w.current?.scrollTo(O)}else if(B==="split"){const O=T.current.splitList;O>0?w.current?.scrollTo(O):w.current?.scrollTo(Math.max(0,o.getSnapshot().selectedIndex-2)),k.current?.scrollTo(T.current.splitOutput)}},0)},[o]),R=Ue(!1);Pt(()=>{p.done&&!R.current&&(R.current=!0,e>0&&x(!0)),!p.done&&R.current&&(R.current=!1,x(!1))},[p.done,e]);const M=Dt(()=>{let B=p.rows;if(p.statusFilter!=="all"&&(B=B.filter(O=>p.statusFilter==="failed"?O.status==="failure":p.statusFilter==="running"?O.status==="running"||O.status==="pending":p.statusFilter==="passed"?O.status==="success"||Vn(O.status):!0)),p.filterText){const O=p.filterText.toLowerCase();B=B.filter(H=>H.taskId.toLowerCase().includes(O))}return B},[p.rows,p.filterText,p.statusFilter]),L=Dt(()=>p.rows.filter(B=>B.status==="running").length,[p.rows]),U=(M[p.selectedIndex]??null)?.taskId??null,D=p.pinnedTaskIds[0]??U,C=D?p.rows.find(B=>B.taskId===D):null,j=D?p.outputs.get(D)??"":"",A=Js(r,i,s),V=p.done?`Completed ${A} (${Mr((p.endTime??Date.now())-p.startTime)})`:`Running ${A}...`,N=p.done?p.failed>0?"error":"success":"running",F=Nt(B=>{w.current?.scrollTo(Math.max(0,B-2))},[]);if(Pt(()=>{p.interactiveMode&&C?.status!=="running"&&o.setInteractiveMode(!1)},[p.interactiveMode,C?.status,o]),Pt(()=>{if(!D)return;let B=c;p.viewMode==="split"&&c>=Ec?B=c-Math.floor(c*.4)-2:(p.viewMode==="split"||p.viewMode==="fullscreen")&&(B=c-2);const O=Math.max(1,d-4);n.get(D)?.resize?.(B,O)},[c,d,p.viewMode,D]),kt((B,O)=>{if(O.escape){o.setInteractiveMode(!1);return}if(!D)return;const H=n.get(D);if(!H){o.setInteractiveMode(!1);return}if(O.return)H.write("\r");else if(O.upArrow)H.write("\x1B[A");else if(O.downArrow)H.write("\x1B[B");else if(O.rightArrow)H.write("\x1B[C");else if(O.leftArrow)H.write("\x1B[D");else if(O.backspace)H.write("");else if(O.delete)H.write("\x1B[3~");else if(O.tab)H.write(" ");else if(O.home)H.write("\x1B[H");else if(O.end)H.write("\x1B[F");else if(O.pageUp)H.write("\x1B[5~");else if(O.pageDown)H.write("\x1B[6~");else if(O.ctrl&&B){const ye=B.toUpperCase().codePointAt(0);ye!==void 0&&ye>=65&&ye<=90&&H.write(String.fromCodePoint(ye-64))}else B&&H.write(B)},{isActive:p.interactiveMode}),kt((B,O)=>{if(B==="c"&&O.ctrl){a();return}if(!$){if(g){O.escape||B==="?"?h(!1):B==="q"?(h(!1),x(!0)):O.downArrow||B==="j"?y.current?.scrollBy(1):O.upArrow||B==="k"?y.current?.scrollBy(-1):O.pageDown?y.current?.scrollBy(5):O.pageUp?y.current?.scrollBy(-5):O.home?y.current?.scrollToTop():O.end&&y.current?.scrollToBottom();return}if(B==="?"){h(!0);return}if(B==="q"){x(!0);return}if(B==="r"&&p.done){o.requestRerun();return}if(B==="R"&&p.done){const H=M[p.selectedIndex];H?.status==="failure"&&o.requestRetry(H.taskId);return}if(B==="F"&&!p.filterActive){const H=["all","failed","running","passed"],ye=H.indexOf(p.statusFilter);o.setStatusFilter(H[(ye+1)%H.length]);return}if(p.filterActive){if(O.escape){o.setFilterActive(!1);return}if(O.return){o.setFilterActive(!1);return}if(O.backspace){o.setFilter(p.filterText.slice(0,-1));return}if(B&&!O.ctrl&&!O.meta){o.setFilter(p.filterText+B);return}return}if(B==="i"&&C?.status==="running"&&(p.viewMode==="fullscreen"||p.viewMode==="split"&&p.focusedPanel==="output")){o.setInteractiveMode(!0);return}if(p.viewMode==="fullscreen"){if(O.escape){o.setViewMode("split"),P("split");return}if(O.downArrow||B==="j"){k.current?.scrollBy(1);return}if(O.upArrow||B==="k"){k.current?.scrollBy(-1);return}if(O.pageDown||O.ctrl&&B==="d"){k.current?.scrollBy(12);return}if(O.pageUp||O.ctrl&&B==="u"){k.current?.scrollBy(-12);return}if(O.home){k.current?.scrollToTop();return}if(O.end){k.current?.scrollToBottom();return}return}if(p.viewMode==="split"){if(O.tab){const H=p.focusedPanel==="tasks"?"output":"tasks";o.setFocusedPanel(H);return}if(p.focusedPanel==="output"){if(O.escape){o.setFocusedPanel("tasks");return}if(O.return){I(),o.setViewMode("fullscreen");return}if(O.downArrow||B==="j"){k.current?.scrollBy(1);return}if(O.upArrow||B==="k"){k.current?.scrollBy(-1);return}if(O.pageDown||O.ctrl&&B==="d"){k.current?.scrollBy(12);return}if(O.pageUp||O.ctrl&&B==="u"){k.current?.scrollBy(-12);return}if(O.home){k.current?.scrollToTop();return}if(O.end){k.current?.scrollToBottom();return}return}if(O.escape){o.setViewMode("list"),P("list");return}if(O.return){o.setFocusedPanel("output");return}}if(p.viewMode==="list"||p.viewMode==="split"&&p.focusedPanel==="tasks"){if(O.downArrow||B==="j"){const H=Math.min(p.selectedIndex+1,Math.max(0,M.length-1));o.setSelectedIndex(H),F(H);return}if(O.upArrow||B==="k"){const H=Math.max(p.selectedIndex-1,0);o.setSelectedIndex(H),F(H);return}if(O.return&&p.viewMode==="list"){I(),T.current.splitList=0,T.current.splitOutput=0,o.setViewMode("split"),o.setFocusedPanel("output"),P("split");return}if(B==="/"){o.setFilterActive(!0);return}if(B==="1"&&U){o.pinTask(0,U);return}if(B==="2"&&U){o.pinTask(1,U);return}if(B==="0"){o.clearPins();return}O.escape&&p.filterText&&o.setFilter("")}}},{isActive:!p.interactiveMode}),c<Cc||d<jc)return u(m,{alignItems:"center",height:d,justifyContent:"center",width:c,children:f(l,{color:"yellow",children:["Terminal too small (",c,"x",d,"). Minimum:"," ",Cc,"x",jc]})});const J=f(m,{gap:1,children:[p.succeeded>0&&f(l,{bold:!0,color:"green",children:["✓"," ",p.succeeded]}),p.failed>0&&f(l,{bold:!0,color:"red",children:["✗"," ",p.failed]}),L>0&&f(l,{color:"cyan",children:["◷"," ",L]}),f(l,{dimColor:!0,children:[p.rows.length," ","total"]}),p.statusFilter!=="all"&&f(l,{color:"yellow",children:["[",p.statusFilter,"]"]})]});let Y;if(p.viewMode==="fullscreen")Y=[f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"Esc"}),u(l,{dimColor:!0,children:"BACK"})]},"esc"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"↑↓"}),u(l,{dimColor:!0,children:"SCROLL"})]},"scroll"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"^u ^d"}),u(l,{dimColor:!0,children:"PAGE"})]},"page"),...C?.status==="running"?[f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"i"}),u(l,{dimColor:!0,children:"INPUT"})]},"i")]:[],f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"q"}),u(l,{dimColor:!0,children:"QUIT"})]},"q")];else if(p.done){const B=M[p.selectedIndex]?.status==="failure";Y=[f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"q"}),u(l,{dimColor:!0,children:"QUIT"})]},"q"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"r"}),u(l,{dimColor:!0,children:"RERUN"})]},"r"),...B?[f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"R"}),u(l,{dimColor:!0,children:"RETRY"})]},"R")]:[],f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"?"}),u(l,{dimColor:!0,children:"HELP"})]},"?"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"↑↓"}),u(l,{dimColor:!0,children:"NAV"})]},"nav"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"F"}),u(l,{dimColor:!0,children:"FILTER"})]},"F"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"⏎"}),u(l,{dimColor:!0,children:p.viewMode==="list"?"OUTPUT":"FULLSCREEN"})]},"enter")]}else p.viewMode==="split"&&p.focusedPanel==="output"?Y=[f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"q"}),u(l,{dimColor:!0,children:"QUIT"})]},"q"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"Esc"}),u(l,{dimColor:!0,children:"BACK"})]},"esc"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"↑↓"}),u(l,{dimColor:!0,children:"SCROLL"})]},"scroll"),...C?.status==="running"?[f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"i"}),u(l,{dimColor:!0,children:"INPUT"})]},"i")]:[],f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"⏎"}),u(l,{dimColor:!0,children:"FULLSCREEN"})]},"enter"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"Tab"}),u(l,{dimColor:!0,children:"PANEL"})]},"tab"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"?"}),u(l,{dimColor:!0,children:"HELP"})]},"?")]:Y=[f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"q"}),u(l,{dimColor:!0,children:"QUIT"})]},"q"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"?"}),u(l,{dimColor:!0,children:"HELP"})]},"?"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"↑↓"}),u(l,{dimColor:!0,children:"NAV"})]},"nav"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"/"}),u(l,{dimColor:!0,children:"FILTER"})]},"/"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"F"}),u(l,{dimColor:!0,children:"STATUS"})]},"F"),f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"⏎"}),u(l,{dimColor:!0,children:p.viewMode==="list"?"OUTPUT":"FULLSCREEN"})]},"enter"),...p.viewMode==="split"?[f(m,{gap:1,children:[u(l,{bold:!0,color:"white",children:"Tab"}),u(l,{dimColor:!0,children:"PANEL"})]},"tab")]:[]];const ce=f(m,{borderBottom:!1,borderColor:"gray",borderLeft:!1,borderRight:!1,borderStyle:"single",flexShrink:0,justifyContent:"space-between",children:[u(m,{flexGrow:1,flexWrap:"wrap",gap:2,paddingX:1,children:Y}),u(m,{flexShrink:0,paddingX:1,children:J})]}),le=f(Ar,{backgroundColor:"#1e1e1e",footer:f(l,{dimColor:!0,children:[u(l,{bold:!0,color:"white",children:"↑↓"})," ","scroll"," ",u(l,{bold:!0,color:"white",children:"?"}),"/",u(l,{bold:!0,color:"white",children:"Esc"})," ","close"]}),scrollRef:y,title:"KEYBOARD SHORTCUTS",visible:g,width:52,children:[f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"NAVIGATION"})]}),f(m,{children:[u(m,{width:24,children:f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","↑","/k"]}),u(l,{dimColor:!0,children:" Move up"})]})}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","↓","/j"]}),u(l,{dimColor:!0,children:" Move down"})]})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","Tab"]}),u(l,{dimColor:!0,children:" Switch panel (split)"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","Esc"]}),u(l,{dimColor:!0,children:" Back / close"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","Enter"]}),u(l,{dimColor:!0,children:" Show output / fullscreen"})]})]}),f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"VIEWS"})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","Enter"]}),f(l,{dimColor:!0,children:[" ","List"," ","→"," ","Split"," ","→"," ","Fullscreen"]})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","Esc"]}),f(l,{dimColor:!0,children:[" ","Fullscreen"," ","→"," ","Split"," ","→"," ","List"]})]})]}),f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"ACTIONS"})]}),f(m,{children:[u(m,{width:24,children:f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","/"]}),u(l,{dimColor:!0,children:" Filter by text"})]})}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","F"]}),u(l,{dimColor:!0,children:" Filter by status"})]})]}),f(m,{children:[u(m,{width:24,children:f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","1"]}),u(l,{dimColor:!0,children:"/"}),u(l,{bold:!0,color:"white",children:"2"}),u(l,{dimColor:!0,children:" Pin to output pane"})]})}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","0"]}),u(l,{dimColor:!0,children:" Clear pins"})]})]}),f(m,{children:[u(m,{width:24,children:f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","r"]}),u(l,{dimColor:!0,children:" Rerun all (done)"})]})}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","R"]}),u(l,{dimColor:!0,children:" Retry failed task"})]})]}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","i"]}),u(l,{dimColor:!0,children:" Interactive input (running task)"})]})]}),f(m,{flexDirection:"column",marginBottom:1,children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"SCROLLING"}),u(l,{dimColor:!0,children:" (output panel)"})]}),f(m,{children:[u(m,{width:24,children:f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","↑","/k"]}),u(l,{dimColor:!0,children:" Scroll up"})]})}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","↓","/j"]}),u(l,{dimColor:!0,children:" Scroll down"})]})]}),f(m,{children:[u(m,{width:24,children:f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","^u"]}),u(l,{dimColor:!0,children:" Page up"})]})}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","^d"]}),u(l,{dimColor:!0,children:" Page down"})]})]}),f(m,{children:[u(m,{width:24,children:f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","Home"]}),u(l,{dimColor:!0,children:" Top"})]})}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","End"]}),u(l,{dimColor:!0,children:" Bottom"})]})]})]}),f(m,{flexDirection:"column",children:[f(m,{marginBottom:1,children:[u(l,{dimColor:!0,children:"── "}),u(l,{bold:!0,color:"white",children:"GENERAL"})]}),f(m,{children:[u(m,{width:24,children:f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","q"]}),u(l,{dimColor:!0,children:" Quit"})]})}),f(l,{children:[f(l,{bold:!0,color:"white",children:[" ","?"]}),u(l,{dimColor:!0,children:" Toggle help"})]})]})]})]}),be=u(Nr,{autoExitSeconds:e>0?e:3,onCancel:b(()=>{x(!1)},"onCancel"),visible:$});if(p.viewMode==="fullscreen")return f(m,{flexDirection:"column",height:d,width:c,children:[u(m,{flexGrow:1,children:u(bc,{duration:C?.duration??C?.elapsed,focused:!0,interactiveMode:p.interactiveMode,output:j,scrollRef:k,status:C?.status,taskId:D})}),ce,be,le]});if(p.viewMode==="split"){const B=c>=Ec,O=u(Sc,{compact:!0,filterActive:p.filterActive,filterText:p.filterText,focused:p.focusedPanel==="tasks",headerStatus:N,parallelSlots:t,pinnedTaskIds:p.pinnedTaskIds,rows:M,scrollRef:w,selectedIndex:p.selectedIndex,title:V}),H=u(bc,{duration:C?.duration??C?.elapsed,focused:p.focusedPanel==="output",interactiveMode:p.interactiveMode,output:j,scrollRef:k,showFullscreenHint:!0,status:C?.status,taskId:D});if(B){const Ee=Math.floor(c*.4);return f(m,{flexDirection:"column",height:d,width:c,children:[f(m,{flexDirection:"row",flexGrow:1,children:[u(m,{width:Ee,children:O}),u(m,{flexGrow:1,children:H})]}),ce,be,le]})}const ye=Math.floor(d*.45);return f(m,{flexDirection:"column",height:d,width:c,children:[u(m,{height:ye,children:O}),u(m,{flexGrow:1,children:H}),ce,be,le]})}return f(m,{flexDirection:"column",height:d,width:c,children:[u(m,{flexGrow:1,children:u(Sc,{filterActive:p.filterActive,filterText:p.filterText,focused:!0,headerStatus:N,parallelSlots:t,pinnedTaskIds:p.pinnedTaskIds,rows:M,scrollRef:w,selectedIndex:p.selectedIndex,title:V})}),ce,be,le]})},"VisTaskRunnerApp");var aE=Object.defineProperty,Jr=b((e,t)=>aE(e,"name",{value:t,configurable:!0}),"n$2");const cE=Jr(e=>{const{args:t,autoExit:r=!1,projectNames:n,stdinRegistry:o,tasks:i}=e,s=new Oo(i),a=typeof t.parallel=="number"?t.parallel:3,c=r===!0?3:typeof r=="number"?r:0;let d,p;const g=new Promise(I=>{p=I});let h;const y=Jr(()=>{h&&(clearInterval(h),h=void 0)},"cleanup"),w=Jr(()=>{if(o){for(const I of o.values())I.kill?.();o.clear()}},"killAllPtyProcesses"),k=Jr(()=>{y(),T(),w(),process.stdout.write("\x1B[?1049l\x1B[?25h"),d?.cleanup(),process.exit(1)},"onSignal"),$=Jr(()=>{const I=s.getSnapshot(),P=Mr(Date.now()-I.startTime),R=I.rows.filter(U=>U.status==="failure").map(U=>U.taskId),M=process.stdout.columns||80;process.stdout.write(`
910
- `);for(const U of I.rows){const{status:D,taskId:C}=U,j=no(D);let A="";switch(D){case"local-cache":case"local-cache-kept-existing":{A=" [local cache]";break}case"remote-cache":{A=" [remote cache]";break}case"skipped":{A=" [skipped]";break}}const V=Oe(Q.createElement(l,null," ",Q.createElement(l,{color:j.color},j.icon),` vis run ${C}`,A?Q.createElement(l,{dimColor:!0},` ${A}`):null),{columns:M});process.stdout.write(`${V}
911
- `)}process.stdout.write(`
912
- `);const L=Oe(Q.createElement(Iu,{cached:I.cached,failed:I.failed,failedIds:R,projectNames:n,succeeded:I.succeeded,targets:t.targets,tasks:i,took:P}),{columns:M});if(process.stdout.write(`${L}
913
- `),R.length>0)for(const U of R){const D=I.outputs.get(U);if(D?.trim()){const C=Oe(Q.createElement(l,null,`
914
- `,Q.createElement(l,{bold:!0,color:"red"},` ${qn} vis run ${U}`)),{columns:M});process.stdout.write(`${C}
915
-
916
- `);const j=D.trim().split(`
917
- `).map(A=>` ${A}`).join(`
918
- `);process.stdout.write(`${j}
919
- `)}}},"printExitSummary");let x;const T=Jr(()=>{x&&(clearInterval(x),x=void 0)},"clearKeepAlive");return{lifeCycle:{endCommand(){y(),s.markDone(),x||(x=setInterval(()=>{},1e3)),process.stdin.isTTY&&typeof process.stdin.setRawMode=="function"&&(process.stdin.setRawMode(!0),process.stdin.ref(),process.stdin.resume())},endTasks(I){s.endTasks(I)},printTaskTerminalOutput(I,P,R){s.getSnapshot().outputs.has(I.id)||s.addOutput(I.id,R)},startCommand(){process.on("SIGINT",k),process.on("SIGTERM",k),x||(x=setInterval(()=>{},1e3)),process.stdin.isTTY&&typeof process.stdin.setRawMode=="function"&&(process.stdin.setRawMode(!0),process.stdin.ref(),process.stdin.resume()),d=Xt(Q.createElement(sE,{autoExitSeconds:c,parallelSlots:a,projectNames:n,stdinRegistry:o??new Map,store:s,targets:t.targets,tasks:i}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}),d.waitUntilExit().then(()=>{T(),w(),process.removeListener("SIGINT",k),process.removeListener("SIGTERM",k),$(),p()},()=>{T(),w(),process.removeListener("SIGINT",k),process.removeListener("SIGTERM",k),p()})},startTasks(I){s.startTasks(I),h||(h=setInterval(()=>{s.tick()},100))}},renderIsDone:g,store:s}},"createDynamicOutputRenderer");var lE=Object.defineProperty,dE=b((e,t)=>lE(e,"name",{value:t,configurable:!0}),"m$4");class uE{static{b(this,"StaticOutputLifeCycle")}static{dE(this,"StaticOutputLifeCycle")}#e;#t;#n;#o=[];#r=[];#i=new Map;#s;#a=0;constructor(t){this.#e=t.projectNames,this.#t=t.args.targets,this.#n=t.tasks,this.#s=t.logReporter}startCommand(){this.#a=Date.now();const t=process.stdout.columns||80,r=`Running ${Js(this.#e,this.#t,this.#n)}`,n=Oe(Q.createElement(Hi,{title:r,variant:"info"}),{columns:t});process.stdout.write(n);const o=this.#n[0],i=o?.overrides?Object.entries(o.overrides).filter(([s])=>s!=="command"):[];if(i.length>0){process.stdout.write(`
920
- With additional flags:
921
- `);for(const[s,a]of i)process.stdout.write(`${Uj(" ",s,a)}
922
- `)}process.stdout.write(`
923
- `)}startTasks(t){const r=process.stdout.columns||80;for(const n of t){const o=Oe(Q.createElement(l,null,Q.createElement(l,{dimColor:!0},">"),` ${n.id}`),{columns:r});process.stdout.write(`${o}
924
- `)}}endTasks(t){const r=process.stdout.columns||80;for(const n of t){this.#i.set(n.task.id,n),n.status==="failure"?this.#o.push(n):Vn(n.status)&&this.#r.push(n);const o=Pu(n.status),i=n.startTime&&n.endTime?` (${Mr(n.endTime-n.startTime)})`:"",s=Vn(n.status)?" [cache]":"",a=Oe(Q.createElement(l,null,o,` ${n.task.id}`,s?Q.createElement(l,{color:"cyan"},s):null,i?Q.createElement(l,{dimColor:!0},i):null),{columns:r});process.stdout.write(`${a}
925
- `)}}printTaskTerminalOutput(t,r,n){if(this.#s){this.#s.printTaskTerminalOutput(t,r,n);return}Zj(t.id,r,n)}endCommand(){const t=Mr(Date.now()-this.#a),r=this.#n.filter(i=>!this.#i.has(i.id)).map(i=>i.id);process.stdout.write(`
926
- `);const n=process.stdout.columns||80,o=Oe(Q.createElement(Iu,{cached:this.#r.length,failed:this.#o.length,failedIds:this.#o.map(i=>i.task.id),projectNames:this.#e,skippedIds:r.length>0?r:void 0,succeeded:this.#i.size-this.#o.length-this.#r.length,targets:this.#t,tasks:this.#n,took:t}),{columns:n});process.stdout.write(`${o}
927
- `)}}var pE=Object.defineProperty,Zr=b((e,t)=>pE(e,"name",{value:t,configurable:!0}),"l$5");const fE=[/node_modules(?:\/|$)/,/\.git(?:\/|$)/,/\.vis(?:\/|$)/,/\.task-runner(?:\/|$)/],Tc=Zr((e,t)=>{const r=new Set,n=new Set;for(const[,s]of e){const a=s.task.hashDetails?.nodes;if(a)for(const c of Object.keys(a))r.add(c),n.add(Lt(xe(t,c)))}const o=[...n].sort(),i=[];for(const s of o)i.some(a=>s===a||s.startsWith(`${a}/`))||i.push(s);return{directories:i,files:r}},"collectTrackedWatchTargets"),gE=Zr((e,t,r)=>{const n=new Set;for(const o of e){const i=xe(t,o);for(const s of r)if(i===s||i.startsWith(`${s}/`)){const a=He(s,i);a.length>0&&n.add(a)}}return o=>{const i=o.replaceAll("\\","/");return n.has(i)}},"createTrackedFileFilter"),mE=Zr(e=>{const t=e.replaceAll("\\","/");return fE.some(r=>r.test(t))},"shouldIgnore"),Rc=Zr(e=>{const{debounceMs:t=150,filter:r,onChange:n,paths:o}=e,i=[];let s=new Set,a;const c=Zr(()=>{a=void 0;const d=[...s];s=new Set,d.length!==0&&Promise.resolve(n(d)).catch(p=>{console.error("[vis watch] onChange handler failed:",p)})},"flush");for(const d of o)try{const p=Np(d,{recursive:!0},(g,h)=>{h&&(mE(h)||r&&!r(h)||(s.add(h),a&&clearTimeout(a),a=setTimeout(c,t)))});i.push(p)}catch(p){console.warn(`[vis watch] unable to watch ${d}: ${p.message}`)}return{close:Zr(()=>{a&&clearTimeout(a);for(const d of i)try{d.close()}catch{}},"close")}},"startWatcher");var hE=Object.defineProperty,Ce=b((e,t)=>hE(e,"name",{value:t,configurable:!0}),"c$6");const Ys="VIS_AFFECTED_FILES",Fu=Ce((e,t,r)=>r||!t?e:t.startsWith("/")?t:`${e}/${t}`,"resolveCwd"),Ac=Ce(async(e,t,r,n)=>{const o=e.map(i=>{const s=i.overrides.command;if(!s)return;const a=i.overrides.visOptions,c=Fu(t,i.projectRoot,!!a?.runFromWorkspaceRoot),d=a?.envFile?vl(c,a.envFile):{},p=r&&(a?.affectedFiles==="env"||a?.affectedFiles==="both")?{[Ys]:r.join(`
928
- `)}:{};return{command:s,cwd:c,env:{INIT_CWD:n,...d,...p},name:i.id}}).filter(i=>i!==void 0);o.length!==0&&await ts(o,{killOthers:["failure"]})},"runPersistentTasks"),zi=256*1024;class yE{static{b(this,"ye")}static{Ce(this,"OutputRingBuffer")}#e;#t="";#n=!1;constructor(t){this.#e=t}append(t){this.#t+=t,this.#t.length>this.#e&&(this.#t=this.#t.slice(-this.#e),this.#n=!0)}toString(){return this.#n?`[...output truncated, showing last ${Math.round(this.#e/1024)}KB...]
929
- ${this.#t}`:this.#t}}const Lu=Ce(e=>{const t=e.overrides.visOptions;if(t&&typeof t=="object")return t},"getTaskOptions"),Ks=Ce(e=>`'${e.replaceAll("'",String.raw`'\''`)}'`,"singleQuoteEscape"),vE=Ce((e,t,r)=>{if(!t||t.length===0||r===!1||r===void 0)return e;if(r==="args"||r==="both"){const n=t.map(Ks).join(" ");return`${e} ${n}`}return e},"buildAffectedFilesArgs"),Vu="visForwardedArgs",wE=Ce((e,t)=>{const r=t.overrides[Vu];if(!Array.isArray(r)||r.length===0)return e;const n=r.map(Ks).join(" ");return`${e} ${n}`},"appendForwardedArgs"),kE=Ce(async(e,t,r)=>{if(!t)return r();const n=e.get(t)??Promise.resolve();let o;const i=new Promise(a=>{o=a}),s=n.then(()=>i);e.set(t,s),await n;try{return await r()}finally{o(),e.get(t)===s&&e.delete(t)}},"withMutex"),bE=Ce(e=>{let t=Math.max(0,Math.floor(e));return{claim(r){const n=Math.max(0,Math.min(r,t));return t-=n,n},get remaining(){return t}}},"createRetryBudget"),$E=Ce((e,t,r)=>{const n=`${t}\0${typeof r=="string"?r:String(r)}`,o=e.get(n);if(o)return o;const i=vl(t,r);return e.set(n,i),i},"loadEnvFileCached"),Ic=Ce(e=>{const t=new Map;return async(r,n)=>{const{affectedFiles:o,currentOs:i,initCwd:s,lifeCycle:a,mutexPool:c,onOutput:d,onOutputReplace:p,retryBudget:g,stdinRegistry:h,workspaceRoot:y}=e,w=Lu(r),k=Fu(y,n.cwd??r.projectRoot,w?.runFromWorkspaceRoot===!0),$=r.overrides.command;if(!$)return{code:0,terminalOutput:`No command configured for ${r.target.project}:${r.target.target}`};const x=wE($,r),T=vE(x,o,w?.affectedFiles),I=Sf(w,i),P=I?`${I} -c ${Ks(T)}`:T,R=w?.envFile?$E(t,k,w.envFile):void 0,M={};o&&o.length>0&&(w?.affectedFiles==="env"||w?.affectedFiles==="both")&&(M[Ys]=o.join(`
930
- `));const L={INIT_CWD:s,...R,...n.env,...M},U=w?.pty===!0,D=!!h,C=D||U;C&&(r.cache=!1);const j=C?void 0:new yE(zi),A=C?new Kc(zi):void 0;let V;const N=Ce(J=>{if(J.kind==="started"&&(V=J.kill,J.write&&h&&h.set(r.id,{kill:J.kill,resize:J.resize,write:J.write})),(J.kind==="stdout"||J.kind==="stderr")&&J.text!==void 0)if(J.kind==="stdout"?a?.onTaskStdout?.(r,J.text):a?.onTaskStderr?.(r,J.text),A)A.write(J.text),D&&p?.(r.id,A.toString());else{const Y=`${J.text}
931
- `;j.append(Y),d?.(r.id,Y)}J.kind==="close"&&h&&h.delete(r.id)},"onEvent"),F=Ce(async()=>{const J=w?.retryCount??0,Y=w?.retryDelay,ce=g?g.claim(J):J,le=typeof w?.timeout=="number"&&w.timeout>0?w.timeout:0;let be=!1,B;le>0&&(B=setTimeout(()=>{be=!0,V?.("SIGTERM")},le));let O;try{O=await ts([{command:P,cwd:k,env:L,name:r.id,...C?{ptySize:{cols:process.stdout.columns??80,rows:process.stdout.rows??24},stdin:"pty"}:{}}],{killOthers:["failure"],onEvent:N,...ce>0?{restart:{delay:Y??"exponential",tries:ce}}:{}})}finally{B&&clearTimeout(B)}const H=O.closeEvents[0],ye=A?A.toString():j.toString();return be?{code:124,terminalOutput:`${ye}
932
- [timeout] Task "${r.id}" exceeded ${le}ms budget.
933
- `}:{code:H?.exitCode??1,terminalOutput:ye}},"runOnce");return c?kE(c,w?.mutex,F):F()}},"createConcurrentExecutor"),xE=Ce(e=>{if(!e||e.trim().length===0)return;const t=Number.parseFloat(e);return!Number.isFinite(t)||t<=0?{invalid:e}:{value:Math.floor(t)}},"parseEnvConcurrency"),SE=Ce(async(e,t)=>{const r=await hp(e);if(!r){t.warn("No previous run recorded yet. Run a task at least once to populate .task-runner/last-summary.json.");return}const n=(r.duration/1e3).toFixed(2);if(t.info(""),t.info(`Last run — ${r.startTime} (${n}s)`),t.info(""),t.info(` Total: ${String(r.stats.total)}`),t.info(` Succeeded: ${String(r.stats.succeeded)}`),t.info(` Cached: ${String(r.stats.cached)}`),t.info(` Failed: ${String(r.stats.failed)}`),t.info(` Skipped: ${String(r.stats.skipped)}`),t.info(""),r.stats.failed>0){const i=r.tasks.filter(s=>s.exitCode!==void 0&&s.exitCode!==0);t.info("Failed tasks:");for(const s of i){const a=s.duration??0;t.info(` × ${s.taskId} (exit ${String(s.exitCode??-1)}, ${a}ms)`)}t.info("")}const o=[...r.tasks].filter(i=>typeof i.duration=="number").sort((i,s)=>(s.duration??0)-(i.duration??0)).slice(0,5);if(o.length>0){t.info("Slowest tasks:");for(const i of o)t.info(` ${i.taskId.padEnd(40)} ${String(i.duration??0).padStart(6)}ms [${i.cacheStatus}]`);t.info("")}},"renderLastRunSummary"),CE={argument:{description:"The target to run (e.g., build, test, lint)",name:"target",type:String},description:"Run a target across workspace projects",examples:[["vis run","List all available targets"],["vis run build","Run build on all projects"],["vis run :build","Run build on all projects (moon-style)"],["vis run ~:test","Run test on the project closest to the current directory"],['vis run "#frontend:build"',"Run build on projects tagged 'frontend'"],['vis run :build --query "language=typescript"',"Filter by project metadata"],["vis run test --affected","Run test only on git-changed projects"],["vis run build --fail-fast","Stop on first failure"],["vis run build --dry-run","Show execution plan without running"]],execute:Ce(async({argument:e,logger:t,options:r,runtime:n,visConfig:o,workspaceRoot:i})=>{if(!i)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const s=i;if(r.lastDetails===!0){await SE(s,t);return}const a=process.cwd(),{config:c,packageJsons:d,projectOptions:p,workspace:g}=mt(s,o),h=nr(s,g,d);let y=e[0];if(!y){const K=kc(g);if(process.stdout.isTTY&&process.stdin.isTTY){const de=await Lj(K);if(!de){t.info("No target selected.");return}y=de,await Rj(`vis run ${de}`)}else{t.info("Available targets:"),t.info(""),t.info(Fj(K)),t.info(""),t.info("Usage: vis run <target>");return}}if(c.constraints&&!r.skipConstraints){const K=Xc(h,c.constraints);if(K.length>0){for(const de of K)t.error(`[${de.rule}] ${de.message}`);throw new Error(`${K.length} project constraint violation(s) found. Use --skip-constraints to bypass.`)}}if(r.affected){const K=[y];r.parallel!==void 0&&K.push(`--parallel=${String(r.parallel)}`),r.cache||K.push("--no-cache"),r.query&&K.push(`--query=${String(r.query)}`),await n.runCommand("affected",{argv:K});return}const w=await yl(y,g,process.cwd(),s),k=Nj(p),$=Mj(w.target,k);$!==w.target&&t.debug?.(`Resolved alias "${w.target}" → "${$}"`);let x=w.projects;const T=e.slice(1).map(String);if(r.projects){const K=new Set(r.projects.split(",").map(de=>de.trim()));if(x=x.filter(de=>K.has(de)),x.length===0)throw new Error(`No matching projects found for: ${String(r.projects)}`)}if(r.query&&(x=Bo(x,g,r.query),x.length===0)){t.info(`Query "${String(r.query)}" matched no projects.`);return}const I=as(),P=process.env[Ys],R=P?P.split(`
934
- `).filter(Boolean):void 0,M=[],L=new Map;for(const K of x){const de=p.get(K)?.[$];if(!de)continue;const pe=de.options;if(!pe?.internal){if(!kf(pe,I)){t.debug?.(`Skipping ${K}:${$} — osType does not match ${I}`);continue}if(!bf(pe,!!ft)){t.debug?.(`Skipping ${K}:${$} — runInCI filter`);continue}if(!hf(pe?.when)){t.debug?.(`Skipping ${K}:${$} — \`when\` condition not satisfied`);continue}M.push(K),L.set(K,de)}}if(M.length===0){const K=kc(g),de=Object.entries(g.projects).filter(([,pe])=>pe.targets?.[$]!==void 0).map(([pe])=>pe);if(t.error(`No projects have the "${$}" target.`),de.length>0){t.info(""),t.info(`Target "${$}" exists in these projects but was filtered out:`);for(const pe of de.slice(0,5))t.info(` - ${pe}`);de.length>5&&t.info(` …and ${de.length-5} more`)}else{const pe=Au($,K,3);pe.length>0&&(t.info(""),t.info(pe.length===1?`Did you mean "${pe[0]}"?`:`Did you mean one of: ${pe.map(Me=>`"${Me}"`).join(", ")}?`)),t.info(""),t.info("Run `vis run` without arguments to see all available targets.")}return}const U=r.pty===!0;let D=M.map(K=>{const de=g.projects[K],pe=L.get(K),Me={project:K,target:$},Ie=`${K}:${$}`,vt=U?{...pe.options,pty:pe.options?.pty??!0}:pe.options;return{cache:pe.cache,id:Ie,outputs:pe.outputs??[],overrides:{command:pe.command,...T.length>0?{[Vu]:T}:{},...vt?{visOptions:vt}:{}},parallelism:pe.parallelism,projectRoot:de?.root,target:Me}});const C=[],j=[];for(const K of D)Lu(K)?.persistent?(K.cache=!1,C.push(K)):j.push(K);D=j;const A=yp(r.partition);if(A&&(D=vp.partitionTasks(D,A),t.info(`Partition ${A.index}/${A.total}: running ${D.length} task(s)`),D.length===0)){t.info("No tasks assigned to this partition.");return}const V=es(D,{projectGraph:h,targetDefaults:c.targetDefaults,workspace:g});if(r.dryRun){const K=Object.keys(V.tasks).length,de=V.roots.length;t.info(`Execution plan (${String(K)} task(s), ${String(de)} root(s)):`),t.info("");const pe=new Set,Me=Ce((Ie,vt)=>{if(pe.has(Ie))return;pe.add(Ie);for(const W of V.dependencies[Ie]??[])Me(W,vt+1);const G=V.tasks[Ie],z=" ".repeat(vt+1);t.info(`${z}${Ie}${G?.cache===!1?" (no-cache)":""}`)},"walkPlan");for(const Ie of V.roots)Me(Ie,0);C.length>0&&(t.info(""),t.info(` + ${String(C.length)} persistent task(s) (run after graph completes)`)),t.info("");return}const N=Date.now(),F=Sj(),J=Ce((K,de)=>{const pe=de instanceof Error?de.message:String(de);t.warn(`Plugin error in ${K}: ${pe}`)},"onHookError");await Cj(F,c.plugins);const Y=typeof r.profile=="string"?r.profile:void 0,ce=Ce(async K=>{if(!Y)return;const de=Zs(K,V,N),pe=Y.startsWith("/")?Y:`${s}/${Y}`;await wp(de,pe),t.info(`Profile written to ${Y}`)},"maybeWriteProfile"),le=c.taskRunnerOptions??{},be=$d(s,r.cacheDir,le.cacheDirectory),B=Qv(be,s,c.branchScopedCache),O=xE(process.env.VIS_RUN_CONCURRENCY_LIMIT);O&&"invalid"in O&&t.warn(`VIS_RUN_CONCURRENCY_LIMIT=${O.invalid} is not a positive number; falling back to default concurrency.`);const H=O&&"value"in O?O.value:void 0,ye=r.parallel??H??3,Ee={dryRun:r.dryRun,parallel:ye,skipNxCache:!r.cache,summarize:r.summarize,...le,cacheDirectory:B},Ae=process.stdout.isTTY&&!ft,Tt=c.tui?.autoExit??!1,X={args:{parallel:Ee.parallel,targets:[$]},autoExit:Tt,projectNames:M,tasks:D},te=typeof r.retryBudget=="number"?r.retryBudget:void 0,fe=te===void 0?void 0:bE(te),zt=new jj(F,J);if(await F.callHook("run:before",{tasks:D,workspaceRoot:s}),Ae){const K=new Map,de=cE({...X,stdinRegistry:K}),{lifeCycle:pe,store:Me}=de,Ie=new ea([pe,zt]),vt=Ic({affectedFiles:R,currentOs:I,initCwd:a,lifeCycle:Ie,mutexPool:new Map,onOutput:Ce((ne,he)=>{Me.addOutput(ne,he)},"onOutput"),onOutputReplace:Ce((ne,he)=>{Me.setOutput(ne,he)},"onOutputReplace"),retryBudget:fe,stdinRegistry:K,workspaceRoot:s});let G="rerun",z=null,W=new Map;for(;G!=="quit";){if(G==="rerun")W=await ta(D,Ee,{lifeCycle:Ie,projectGraph:h,taskExecutor:vt,taskGraph:V,workspaceRoot:s});else if(G==="retry"&&z){const ne=D.find(Xe=>Xe.id===z),he=ne?.overrides.command;if(ne&&he){const Xe=ne.projectRoot??s,xr=Xe.startsWith("/")?Xe:`${s}/${Xe}`;Ie.startTasks?.([ne]);const qt=new Kc(zi),sr=(await ts([{command:he,cwd:xr,name:ne.id,ptySize:{cols:process.stdout.columns??80,rows:process.stdout.rows??24},stdin:"pty"}],{onEvent:Ce(ze=>{ze.kind==="started"&&ze.write&&K.set(ne.id,{kill:ze.kill,resize:ze.resize,write:ze.write}),(ze.kind==="stdout"||ze.kind==="stderr")&&ze.text&&(qt.write(ze.text),Me.setOutput(ne.id,qt.toString())),ze.kind==="close"&&K.delete(ne.id)},"onEvent")})).closeEvents[0];Ie.endTasks?.([{code:sr?.exitCode??1,status:sr?.exitCode===0?"success":"failure",task:ne,terminalOutput:Me.getSnapshot().outputs.get(ne.id)}])}else ne&&Ie.endTasks?.([{code:1,status:"failure",task:ne,terminalOutput:`No command configured for ${ne.id}`}]);z=null,Me.markDone()}G=await new Promise(ne=>{const he=Me.subscribe(()=>{const Xe=Me.getSnapshot();Xe.rerunRequested&&(Me.acknowledgeRerun(),he(),ne("rerun")),Xe.retryTaskId&&(z=Me.acknowledgeRetry(),he(),ne("retry"))});de.renderIsDone.then(()=>{he(),ne("quit")},()=>{he(),ne("quit")})})}await de.renderIsDone,await F.callHook("run:after",W),await ce(W),C.length>0&&!r.failFast&&await Ac(C,s,R,a)}else{const K=new Map,de=typeof r.log=="string"?r.log.toLowerCase():"",pe=de==="labeled"||de==="grouped"||de==="interleaved"?de:void 0,Me=pe?kp(pe):void 0,Ie=new ea([new uE({...X,logReporter:Me}),zt]),vt=Ic({affectedFiles:R,currentOs:I,initCwd:a,lifeCycle:Ie,mutexPool:K,retryBudget:fe,workspaceRoot:s}),G=Ce(async()=>{const ne=Date.now(),he=await ta(D,Ee,{lifeCycle:Ie,projectGraph:h,taskExecutor:vt,taskGraph:V,workspaceRoot:s}),Xe=Date.now()-ne;if(r.summarize){const vn=Zs(he,V,N);await bp(vn,s)}let xr=!1;for(const[,vn]of he)vn.status==="failure"&&(xr=!0);const qt=wj(he,Xe),sr=zs(s),ze=kj(s,Xe,sr);return t.info(""),t.info(` ${qt}${ze?` ${ze}`:""}`),{hasFailure:xr,results:he,runHistory:sr}},"runOnce"),z=await G();await F.callHook("run:after",z.results),await ce(z.results);const{hasFailure:W}=z;if(r.watch){const ne=M.map(ot=>{const Jt=g.projects[ot]?.root;if(Jt)return Jt.startsWith("/")?Jt:`${s}/${Jt}`}).filter(ot=>ot!==void 0);let he=!1,Xe=z.results;const xr=Ce(()=>{const ot=Tc(Xe,s);if(ot.directories.length>0&&ot.files.size>0){const Jt=gE(ot.files,s,ot.directories);return{handle:Rc({filter:Jt,onChange:sr,paths:ot.directories}),mode:"tracked"}}return{handle:Rc({onChange:sr,paths:ne}),mode:"roots"}},"buildHandle");let qt;const sr=Ce(async ot=>{if(!he){he=!0;try{t.info(`Change detected in ${ot.length} file(s), rerunning…`),Xe=(await G()).results,qt?.close(),qt=xr().handle}finally{he=!1}}},"onChangeHandler"),ze=xr();qt=ze.handle;const vn=ze.mode==="tracked"?`Watching ${String(Tc(Xe,s).files.size)} tracked file(s)`:`Watching ${String(ne.length)} project root(s)`;t.info(`${vn} — edit a file to rerun, Ctrl+C to exit.`),await new Promise(ot=>{const Jt=Ce(()=>{process.off("SIGINT",Jt),qt?.close(),ot()},"onSigint");process.on("SIGINT",Jt)});return}if(W){if(r.flaky!==!1){const ne=Ru(s,{minRuns:2},z.runHistory);if(ne.length>0){t.info(""),t.info("Flaky tasks (based on historical runs):"),t.info("");for(const he of $j(ne))t.info(` ${he}`);t.info("")}}throw new Error("Some tasks failed.")}C.length>0&&!r.failFast&&await Ac(C,s,R,a)}},"execute"),group:"Run & Execute",name:"run",options:[{alias:"p",description:"Comma-separated list of projects to run",name:"projects",type:String},{defaultValue:3,description:"Maximum number of parallel tasks (falls back to VIS_RUN_CONCURRENCY_LIMIT env var, then 3)",name:"parallel",type:Number},{defaultValue:!0,description:"Enable caching (use --no-cache to disable)",name:"cache",type:Boolean},{description:"Custom cache directory",name:"cache-dir",type:String},{defaultValue:!1,description:"Show what would run without executing",name:"dry-run",type:Boolean},{defaultValue:!1,description:"Generate a run summary after execution",name:"summarize",type:Boolean},{description:'Partition tasks for distributed CI (e.g., "1/4" for first of four runners). Falls back to VIS_PARTITION env var.',name:"partition",type:String},{defaultValue:!1,description:"Skip project constraint validation",name:"skip-constraints",type:Boolean},{description:"Filter matched projects by a query (e.g. 'language=typescript && tag=lib')",name:"query",type:String},{defaultValue:!1,description:"Only run on projects affected by git changes (shorthand for vis affected)",name:"affected",type:Boolean},{defaultValue:!1,description:"Rerun affected tasks on file change. Ctrl+C to exit.",name:"watch",type:Boolean},{defaultValue:!1,description:"Stop all tasks on first failure",name:"fail-fast",type:Boolean},{description:"Output mode: interleaved (pass-through), labeled (prefix each line with [pkg#task]), or grouped (vite-task-style block)",name:"log",type:String},{defaultValue:!1,description:"Run every task through a pseudo-terminal so color-aware tools render as if attached to a TTY (disables caching)",name:"pty",type:Boolean},{description:"Global retry budget: cap on total task retries across the run (per-target retryCount is still honored up to the budget)",name:"retry-budget",type:Number},{description:"Write a Chrome Tracing JSON profile of the run to this path (open in chrome://tracing or Perfetto)",name:"profile",type:String},{defaultValue:!1,description:"Render the most-recent run's saved summary (from .task-runner/last-summary.json) and exit without executing any tasks",name:"last-details",type:Boolean},{defaultValue:!0,description:"Show flaky task report on failure (use --no-flaky to suppress)",name:"flaky",type:Boolean}]};var jE=Object.defineProperty,hn=b((e,t)=>jE(e,"name",{value:t,configurable:!0}),"r$5");const qi=hn(e=>{try{return ue(e)}catch{return}},"readJsonSafe"),EE=hn(e=>{if(e.length===0||e.includes("..")||e.startsWith(".")||e.includes("\0")||e.includes("\\"))return!1;if(e.startsWith("@")){const t=e.indexOf("/");return t>1&&!e.includes("/",t+1)}return!e.includes("/")},"isSafePackageName"),TE=hn(e=>e.length>0&&!e.includes("/")&&!e.includes("\\")&&!e.includes("..")&&!e.includes("\0"),"isSafeVersion"),RE=hn((e,t,r)=>{const n=`${t.replaceAll("/","+")}@${r}`,o=v(e,"node_modules",".pnpm"),i=qi(v(o,n,"node_modules",t,"package.json"));if(i)return i;let s;try{s=Ve(o)}catch{return}const a=`${n}_`;for(const c of s){if(!c.startsWith(a))continue;const d=qi(v(o,c,"node_modules",t,"package.json"));if(d)return d}},"readPnpmVirtualStore"),AE=hn((e,t,r)=>{const n=qi(v(e,"node_modules",t,"package.json"));return n?.version===r?n:void 0},"readHoistedCopy"),IE=hn((e,t,r)=>{if(!(!EE(t)||!TE(r)))return RE(e,t,r)??AE(e,t,r)},"readInstalledPackageMetadata");var OE=Object.defineProperty,_u=b((e,t)=>OE(e,"name",{value:t,configurable:!0}),"i$3");const Uu=new Set(["0BSD","AGPL-3.0","AGPL-3.0-only","AGPL-3.0-or-later","Apache-1.1","Apache-2.0","Artistic-2.0","BlueOak-1.0.0","BSD-2-Clause","BSD-3-Clause","BSL-1.0","CC0-1.0","CC-BY-3.0","CC-BY-4.0","CDDL-1.0","CDDL-1.1","EPL-1.0","EPL-2.0","GPL-2.0","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0","GPL-3.0-only","GPL-3.0-or-later","ISC","LGPL-2.0","LGPL-2.1","LGPL-3.0","MIT","MIT-0","MPL-1.1","MPL-2.0","Python-2.0","Unlicense","WTFPL","Zlib"]),PE={apache2:"Apache-2.0","apache 2.0":"Apache-2.0",bsd:"BSD-3-Clause","bsd-2":"BSD-2-Clause","bsd-3":"BSD-3-Clause",mit:"MIT",public:"Unlicense","public domain":"Unlicense"},NE=(()=>{const e=new Map;for(const t of Uu)e.set(t.toLowerCase(),t);for(const[t,r]of Object.entries(PE))e.set(t,r);return e})(),ME=_u(e=>{const t=e.trim();if(t.length!==0)return Uu.has(t)?t:NE.get(t.toLowerCase())},"normalizeSpdxId"),DE=_u(e=>{let t;if(typeof e.license=="string")t=e.license;else if(e.license&&typeof e.license=="object"&&typeof e.license.type=="string")t=e.license.type;else if(Array.isArray(e.licenses)&&e.licenses.length>0){const o=e.licenses[0];o&&typeof o.type=="string"&&(t=o.type)}if(!t)return;const r=t.trim();if(r.length===0)return;if(/[()]|\b(and|or|with)\b/i.test(r))return[{expression:r}];const n=ME(r);return n?[{license:{id:n}}]:[{license:{name:r}}]},"extractLicenseChoice");var BE=Object.defineProperty,Wu=b((e,t)=>BE(e,"name",{value:t,configurable:!0}),"t$4");const FE={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"},LE={sha256:64,sha384:96,sha512:128},VE=Wu(e=>{const t={name:e.name,version:e.version},{integrity:r}=e;return r&&r.hex.length===LE[r.algorithm]&&(t.hash={alg:FE[r.algorithm],content:r.hex}),e.dependencies&&(t.dependencies=e.dependencies),e.peerDependencies&&(t.peerDependencies=e.peerDependencies),e.optionalDependencies&&(t.optionalDependencies=e.optionalDependencies),t},"toResolvedPackage"),_E=[{file:"pnpm-lock.yaml",type:"pnpm"},{file:"package-lock.json",type:"npm"},{file:"yarn.lock",type:"yarn"},{file:"bun.lock",type:"bun"}],UE=Wu(e=>{for(const{file:t,type:r}of _E){let n;try{n=q(v(e,t))}catch{continue}const o=new Map;for(const i of Hc(n,r))o.set(`${i.name}@${i.version}`,VE(i));return{packages:o,type:r}}},"readLockfilePackages");var WE=Object.defineProperty,Gu=b((e,t)=>WE(e,"name",{value:t,configurable:!0}),"r$4");const $n=Gu(e=>e.replaceAll(/[^\w.~-]/g,t=>`%${(t.codePointAt(0)??0).toString(16).toUpperCase().padStart(2,"0")}`),"encodeSegment"),Er=Gu((e,t)=>{const r=e.toLowerCase();if(r.startsWith("@")){const n=r.indexOf("/");if(n>0){const o=r.slice(0,n),i=r.slice(n+1);return`pkg:npm/${$n(o)}/${$n(i)}@${$n(t)}`}}return`pkg:npm/${$n(r)}@${$n(t)}`},"toNpmPurl");var GE=Object.defineProperty,Hu=b((e,t)=>GE(e,"name",{value:t,configurable:!0}),"s$6");const HE=Hu(e=>{const t=e.indexOf(":");return t<=0?e:e.slice(0,t)==="npm"?e.slice(t+1):e},"stripProtocolPrefix"),Ai=Hu((e,t,r)=>{const n=r.get(e);if(!n||n.size===0)return;if(n.has(t))return t;const o=HE(t);if(o!==t&&n.has(o))return o;const i=[...n];return xp.maxSatisfying(i,o,{includePrerelease:!0})||i[0]},"resolveSpecifier");var zE=Object.defineProperty,nt=b((e,t)=>zE(e,"name",{value:t,configurable:!0}),"p$6");const qE="1.6",JE="CycloneDX",YE="http://cyclonedx.org/schema/bom-1.6.schema.json",KE="@visulima/vis",Oc=nt(e=>{try{return ue(e)}catch{return}},"readPackageJson"),XE=nt(e=>{if(e){if(typeof e=="string")return e;if(typeof e=="object"&&e.name)return e.email?`${e.name} <${e.email}>`:e.name}},"toAuthorString"),QE=nt(e=>{if(e)return typeof e=="string"?e:e.url},"toRepositoryUrl"),ZE=nt(e=>{if(e)return typeof e=="string"?e:e.url},"toBugsUrl"),eT=nt(e=>{const t=[];e.homepage&&t.push({type:"website",url:e.homepage});const r=QE(e.repository);r&&t.push({type:"vcs",url:r});const n=ZE(e.bugs);return n&&t.push({type:"issue-tracker",url:n}),t.length>0?t:void 0},"buildExternalReferences"),Ii=nt((e,t)=>{if(!t)return;t.description&&(e.description=t.description);const r=XE(t.author);r&&(e.author=r);const n=DE(t);n&&(e.licenses=n);const o=eT(t);o&&(e.externalReferences=o)},"decoratePackageComponent"),tT=nt(e=>{const{focus:t,generatorVersion:r,includeDev:n=!1,now:o=new Date,projectGraph:i,serialNumber:s,workspace:a,workspaceRoot:c}=e,d=t&&t.length>0?[...Bd(t,i)].sort():Object.keys(a.projects).sort(),p=new Set(d),g=new Map;for(const N of d){const F=a.projects[N];F&&g.set(N,Oc(v(c,F.root,"package.json")))}const h=[],y=new Map;for(const N of d){const F=a.projects[N];if(!F)continue;const J=g.get(N),Y=J?.version??"0.0.0",ce=Er(N,Y);y.set(N,ce);const le={"bom-ref":ce,name:N,purl:ce,type:F.projectType==="application"?"application":"library",version:Y};Ii(le,J),h.push(le)}const w=UE(c),k=new Map,$=new Map;if(w)for(const N of w.packages.values()){k.set(`${N.name}@${N.version}`,N);let F=$.get(N.name);F||(F=new Set,$.set(N.name,F)),F.add(N.version)}const x=[],T=[],I=new Map;for(const N of d){const F=g.get(N);if(!F)continue;const J=[F.dependencies,F.peerDependencies];n&&J.push(F.devDependencies);const Y=new Set,ce=nt((le,be)=>{if(be)for(const[B,O]of Object.entries(be)){if(p.has(B)){const ye=y.get(B);ye&&Y.add(ye);continue}const H=Ai(B,O,$);H&&(Y.add(Er(B,H)),le.push(`${B}@${H}`))}},"seedRef");for(const le of J)ce(x,le);ce(T,F.optionalDependencies),I.set(N,Y)}const P=new Map,R=new Map,M=nt((N,F)=>{const J=[...N];for(;J.length>0;){const Y=J.pop(),ce=P.get(Y);if(ce==="required"||ce==="optional"&&F==="optional")continue;P.set(Y,F);const le=k.get(Y);if(!le)continue;const be=R.get(Y)??new Set,B=[le.dependencies,le.peerDependencies];for(const O of B)if(O)for(const[H,ye]of Object.entries(O))for(const Ee of ye){const Ae=Ai(H,Ee,$);Ae&&(be.add(Er(H,Ae)),J.push(`${H}@${Ae}`))}if(le.optionalDependencies)for(const[O,H]of Object.entries(le.optionalDependencies))for(const ye of H){const Ee=Ai(O,ye,$);Ee&&(be.add(Er(O,Ee)),T.push(`${O}@${Ee}`))}be.size>0&&R.set(Y,be)}},"walk");M(x,"required"),M(T,"optional");const L=[],U=[...P.keys()].sort();for(const N of U){const F=k.get(N);if(!F)continue;const J=Er(F.name,F.version),Y={"bom-ref":J,name:F.name,purl:J,scope:P.get(N)??"required",type:"library",version:F.version};F.hash&&(Y.hashes=[F.hash]),Ii(Y,IE(c,F.name,F.version)),L.push(Y)}const D=[];for(const[N,F]of I){const J=y.get(N);if(!J)continue;const Y=[...F].sort();D.push(Y.length>0?{dependsOn:Y,ref:J}:{ref:J})}for(const N of U){const F=k.get(N);if(!F)continue;const J=Er(F.name,F.version),Y=R.get(N),ce=Y?[...Y].sort():[];D.push(ce.length>0?{dependsOn:ce,ref:J}:{ref:J})}D.sort((N,F)=>N.ref.localeCompare(F.ref));const C=Oc(v(c,"package.json")),j=(()=>{if(t?.length===1){const ce=h.find(le=>le.name===t[0]);if(ce)return{"bom-ref":ce["bom-ref"],name:ce.name,purl:ce.purl,type:ce.type,version:ce.version}}const N=C?.name??"workspace",F=C?.version??"0.0.0",J=Er(N,F),Y={"bom-ref":J,name:N,purl:J,type:"application",version:F};return Ii(Y,C),Y})(),A=j["bom-ref"],V=A?h.filter(N=>N["bom-ref"]!==A):h;return{$schema:YE,bomFormat:JE,components:[...V,...L],dependencies:D,metadata:{component:j,lifecycles:[{phase:"build"}],timestamp:o.toISOString(),tools:{components:[{name:KE,type:"application",...r?{version:r}:{}}]}},serialNumber:s??`urn:uuid:${ef()}`,specVersion:qE,version:1}},"buildCycloneDxBom"),rT=nt(e=>{const t={version:e.version??1,xmlns:"http://cyclonedx.org/schema/bom/1.6"};e.serialNumber&&(t.serialNumber=e.serialNumber);const r=[];return e.metadata&&r.push(nT(e.metadata)),e.components&&e.components.length>0&&r.push({_content:e.components.map(Ji),_name:"components"}),e.dependencies&&e.dependencies.length>0&&r.push({_content:e.dependencies.map(iT),_name:"dependencies"}),`${tf({_attrs:t,_content:r,_name:"bom"},{header:!0,indent:" ",selfCloseTags:!0})}
935
- `},"serializeBomToXml"),nT=nt(e=>{const t=[];return e.timestamp&&t.push({timestamp:e.timestamp}),e.lifecycles&&e.lifecycles.length>0&&t.push({_content:e.lifecycles.map(r=>{const n=[];return r.phase&&n.push({phase:r.phase}),r.name&&n.push({name:r.name}),r.description&&n.push({description:r.description}),{_content:n,_name:"lifecycle"}}),_name:"lifecycles"}),e.tools?.components&&t.push({_content:[{_content:e.tools.components.map(Ji),_name:"components"}],_name:"tools"}),e.component&&t.push(Ji(e.component)),{_content:t,_name:"metadata"}},"metadataToXmlElement"),Ji=nt(e=>{const t={type:e.type};e["bom-ref"]&&(t["bom-ref"]=e["bom-ref"]);const r=[];e.group&&r.push({group:e.group}),r.push({name:e.name}),e.version&&r.push({version:e.version}),e.description&&r.push({description:e.description}),e.author&&r.push({author:e.author}),e.hashes&&e.hashes.length>0&&r.push({_content:e.hashes.map(o=>({_attrs:{alg:o.alg},_content:o.content,_name:"hash"})),_name:"hashes"});const n=oT(e.licenses);return n&&r.push(n),e.purl&&r.push({purl:e.purl}),e.scope&&r.push({scope:e.scope}),e.externalReferences&&e.externalReferences.length>0&&r.push({_content:e.externalReferences.map(o=>({_attrs:{type:o.type},_content:[{url:o.url}],_name:"reference"})),_name:"externalReferences"}),{_attrs:t,_content:r,_name:"component"}},"componentToXmlElement"),oT=nt(e=>{if(!e||e.length===0)return;const t=[];for(const r of e){if("expression"in r){t.push({expression:r.expression});continue}const n=[];"id"in r.license&&r.license.id?n.push({id:r.license.id}):"name"in r.license&&r.license.name&&n.push({name:r.license.name}),t.push({_content:n,_name:"license"})}return{_content:t,_name:"licenses"}},"licensesToXmlElement"),iT=nt(e=>e.dependsOn&&e.dependsOn.length>0?{_attrs:{ref:e.ref},_content:e.dependsOn.map(t=>({_attrs:{ref:t},_name:"dependency"})),_name:"dependency"}:{_attrs:{ref:e.ref},_name:"dependency"},"dependencyToXmlElement");var sT=Object.defineProperty,zu=b((e,t)=>sT(e,"name",{value:t,configurable:!0}),"i$2");const qu=["json","xml"],aT=zu(e=>qu.includes(e),"isSbomFormat"),cT={description:"Generate a CycloneDX 1.6 Software Bill of Materials for the workspace",examples:[["vis sbom","Write the full-workspace SBOM to sbom.cdx.json"],["vis sbom --focus=my-app","Scope the SBOM to my-app's transitive closure"],["vis sbom --focus=my-app,other","Focus multiple projects"],["vis sbom --format=xml --output=sbom.cdx.xml","Emit XML instead of JSON"],["vis sbom --include-dev","Include devDependencies (default: production only)"],["vis sbom --output=-","Write to stdout"]],execute:zu(async({options:e,visConfig:t,workspaceRoot:r})=>{if(!r)throw new Error("Could not determine workspace root. Run inside a monorepo.");const{packageJsons:n,workspace:o}=mt(r,t),i=nr(r,o,n),s=e.focus,a=s?s.split(",").map(k=>k.trim()).filter(Boolean):void 0,c=(e.format??"json").toLowerCase();if(!aT(c))throw new Error(`Unknown --format: "${c}". Expected one of: ${qu.join(", ")}.`);const d=tT({focus:a,includeDev:!!e.includeDev,projectGraph:i,workspace:o,workspaceRoot:r}),p=c==="xml"?rT(d):`${JSON.stringify(d,void 0,2)}
936
- `,g=e.output??(c==="xml"?"sbom.cdx.xml":"sbom.cdx.json");if(g==="-"){process.stdout.write(p);return}const h=xe(r,g);Se(Lt(h)),me(h,p,"utf8");const y=d.components?.length??0,w=d.dependencies?.length??0;ee(`SBOM written to ${h}`),ie(`${y} components, ${w} dependency edges`)},"execute"),group:"Security & Health",name:"sbom",options:[{description:"Project name(s) to focus on — comma-separated for multiple",name:"focus",type:String},{defaultValue:"json",description:"Output format: json (default) or xml",name:"format",type:String},{description:"Output path (use '-' for stdout; default: sbom.cdx.json)",name:"output",type:String},{defaultValue:!1,description:"Include devDependencies (default: production only)",name:"include-dev",type:Boolean}]};var lT=Object.defineProperty,oo=b((e,t)=>lT(e,"name",{value:t,configurable:!0}),"s$5");const dT=oo((e,t)=>{if(!st(e))return e;const r=He(t,e);return r===""||r.startsWith("..")?e:r},"toRelative"),_n=oo((e,t)=>{const r=dT(e.file,t);return r===e.file?e:{...e,file:r}},"toRelativeFinding"),Ju=oo(e=>{if(!E(e))return[];try{const t=ue(e);return Array.isArray(t)?t:[]}catch{return[]}},"readBaseline"),uT=oo((e,t,r)=>{const n=Ju(t).map(a=>_n(a,r)),o=new Set(n.map(a=>Xr(a))),i=e.map(a=>_n(a,r)),s=new Set(i.map(a=>Xr(a)));return{fresh:i.filter(a=>!o.has(Xr(a))),resolved:n.filter(a=>!s.has(Xr(a))),surviving:i.filter(a=>o.has(Xr(a)))}},"diffBaseline"),Yu=oo((e,t,r,n={})=>{const o=e.map(s=>_n(s,r));let i;if(n.replace)i=o;else{const s=Ju(t).map(c=>_n(c,r)),a=new Set;i=[];for(const c of[...s,...o]){const d=Xr(c);a.has(d)||(a.add(d),i.push(c))}}return Z(t,`${JSON.stringify(i,null,4)}
937
- `),i.length},"writeBaseline");var pT=Object.defineProperty,pt=b((e,t)=>pT(e,"name",{value:t,configurable:!0}),"a$2");const Pc=1,fT=pt(e=>{const t=new Map;for(const r of e){const n=t.get(r.file);n?n.push(r):t.set(r.file,[r])}return t},"groupByFile"),gT=pt(e=>{try{return q(e).split(/\r?\n/)}catch{return}},"loadLines"),mT=pt((e,t,r)=>{const n=Math.max(1,t);return`${e.slice(0,n-1).replaceAll(/[^\t]/g," ")}${"^".repeat(Math.max(1,r))}`},"caretFor"),hT=pt((e,t,r)=>{if(e.length===0)return r?$e("No secrets detected."):"No secrets detected.";const n=r?{cyan:ut,dim:$e,green:Ot,red:Ge,yellow:Re}:{cyan:pt(s=>s,"cyan"),dim:pt(s=>s,"dim"),green:pt(s=>s,"green"),red:pt(s=>s,"red"),yellow:pt(s=>s,"yellow")},o=[],i=fT(e);for(const[s,a]of i){const c=He(t,s)||s;o.push(n.cyan(c));const d=gT(s);for(const p of a){const g=[p.source,p.confidence].filter(Boolean).join(", "),h=g?` ${n.dim(`(${g})`)}`:"",y=p.alternateMatches&&p.alternateMatches.length>0?` ${n.dim(`also: ${p.alternateMatches.join(", ")}`)}`:"";let w="";switch(p.validation){case"error":{w=` ${n.yellow("! error")}`;break}case"rejected":{w=` ${n.red("✗ rejected")}`;break}case"skipped":{w=` ${n.dim("— unverifiable")}`;break}case"verified":{w=` ${n.green("✓ verified")}`;break}}if(o.push(` ${n.red("✖")} ${n.yellow(`[${p.ruleId}]`)}${h}${w} ${n.dim(`line ${String(p.startLine)}:${String(p.startColumn)}`)}${y}`),d){const k=Math.max(0,p.startLine-1-Pc),$=Math.min(d.length,p.startLine+Pc);for(let x=k;x<$;x+=1){const T=String(x+1).padStart(4," "),I=x+1===p.startLine,P=I?n.red("▶"):" ";if(o.push(` ${P} ${n.dim(T)} │ ${d[x]??""}`),I){const R=Math.max(1,(p.endColumn??p.startColumn+1)-p.startColumn),M=mT(d[x]??"",p.startColumn,R);o.push(` ${n.dim(" │ ")}${n.red(M)}`)}}}o.push("")}}return o.join(`
938
- `).trimEnd()},"formatText"),yT=pt((e,t)=>{if(!st(e))return e.replaceAll("\\","/");try{return nl(e).toString()}catch{return`file://${xe(t,e).replaceAll("\\","/")}`}},"toSarifUri"),vT=pt((e,t=100)=>e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`,"shortText"),wT=pt((e,t,r=process.cwd(),n=[])=>{const o=new Map(n.map(c=>[c.id,c])),i=new Set;for(const c of e)i.add(c.ruleId);const s=[...new Set([...o.keys(),...i])].sort((c,d)=>c.localeCompare(d)),a=new Map(s.map((c,d)=>[c,d]));return JSON.stringify({$schema:"https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json",runs:[{originalUriBaseIds:{SRCROOT:{uri:nl(r).toString()}},results:e.map(c=>{const d={};return c.source&&(d.source=c.source),c.confidence&&(d.confidence=c.confidence),c.alternateMatches&&c.alternateMatches.length>0&&(d.alternateRules=c.alternateMatches),c.validation&&(d.validation=c.validation),{level:"error",locations:[{physicalLocation:{artifactLocation:{uri:yT(c.file,r),uriBaseId:st(c.file)?void 0:"SRCROOT"},region:{endColumn:c.endColumn,endLine:c.endLine,snippet:{text:c.match},startColumn:c.startColumn,startLine:c.startLine}}}],message:{text:c.description||c.ruleId},properties:Object.keys(d).length>0?d:void 0,ruleId:c.ruleId,ruleIndex:a.get(c.ruleId)??-1}}),tool:{driver:{informationUri:"https://visulima.com/packages/secret-scanner",name:"visulima-secret-scanner",rules:s.map(c=>{const d=o.get(c),p=d?.description??`Detected by rule \`${c}\``,g={};return d?.tags&&d.tags.length>0&&(g.tags=d.tags),d?.source&&(g.source=d.source),d?.confidence&&(g.confidence=d.confidence),{defaultConfiguration:{level:"error"},fullDescription:{text:p},helpUri:"https://visulima.com/packages/secret-scanner",id:c,name:c,properties:Object.keys(g).length>0?g:void 0,shortDescription:{text:vT(p)}}}),version:t}}}],version:"2.1.0"},void 0,2)},"formatSarif");var kT=Object.defineProperty,io=b((e,t)=>kT(e,"name",{value:t,configurable:!0}),"n$1");const Po=io((e,t)=>{try{return cl("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}catch{return""}},"runGit"),Yi=io(e=>e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),"splitFiles"),bT=io(e=>Yi(Po(e,["diff","--cached","--name-only","--diff-filter=ACMR"])).map(t=>st(t)?t:v(e,t)),"stagedFiles"),Nc=io((e,t)=>{const r=Po(e,["diff","--name-only","--diff-filter=ACMR",`${t}...HEAD`]),n=Yi(r);if(n.length===0){const o=Po(e,["diff","--name-only","--diff-filter=ACMR",t]);return Yi(o).map(i=>st(i)?i:v(e,i))}return n.map(o=>st(o)?o:v(e,o))},"filesSince"),Oi=io(e=>Po(e,["rev-parse","--show-toplevel"]).length>0,"hasGit");var $T=Object.defineProperty,Yr=b((e,t)=>$T(e,"name",{value:t,configurable:!0}),"r$2");const Mc=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],Ku=Yr(e=>{if(!(typeof process.stderr.isTTY=="boolean"&&process.stderr.isTTY))return{stop:Yr(()=>{},"stop"),update:Yr(()=>{},"update")};let t=e,r=0;const n=Yr(()=>{process.stderr.write(`\r${Mc[r%Mc.length]} ${t}`),r+=1},"render");n();const o=setInterval(n,80);return o.unref?.(),{stop:Yr(i=>{clearInterval(o),process.stderr.write("\r\x1B[2K"),i&&process.stderr.write(`${i}
939
- `)},"stop"),update:Yr(i=>{t=i},"update")}},"startSpinner");var xT=Object.defineProperty,et=b((e,t)=>xT(e,"name",{value:t,configurable:!0}),"o$2");const jn=".secrets-baseline.json",Dc=et(e=>e?Array.isArray(e)?e:[e]:[],"toArray"),ST=et(e=>{const t=new Set(["json","sarif","text"]);return e&&!t.has(e)&&(Ze(`--format must be one of: ${[...t].join(", ")} (got "${e}")`),process.exit(2)),e??"text"},"validateFormat"),CT=et(e=>{if(e===void 0)return;const t=new Set(["high","low","medium"]);return t.has(e)||(Ze(`--min-confidence must be one of: ${[...t].join(", ")} (got "${e}")`),process.exit(2)),e},"validateConfidence"),jT=et(async(e,t)=>{const r=await fl(e);process.stdout.write(`${String(r.length)} rules loaded
940
-
941
- `);for(const n of r){const o=t?Re(n.id):n.id,i=n.tags.length>0?` ${t?$e(`[${n.tags.join(", ")}]`):`[${n.tags.join(", ")}]`}`:"";if(process.stdout.write(`${o}${i}
942
- ${n.description}
943
- `),n.keywords.length>0){const s=`keywords: ${n.keywords.slice(0,6).join(", ")}${n.keywords.length>6?", ...":""}`;process.stdout.write(` ${t?$e(s):s}
944
- `)}process.stdout.write(`
945
- `)}},"printListRules"),ET=et(async(e,t)=>{const r=await rf(e);if(r.length===0){process.stdout.write(t?`${$e("No non-HTTP validators required by the current ruleset.")}
946
- `:`No non-HTTP validators required by the current ruleset.
947
- `);return}process.stdout.write(`${String(r.length)} non-HTTP validator type(s) referenced by the current ruleset:
948
-
949
- `);for(const n of r){const o=t?Re(n.displayName):n.displayName,i=`(${n.type}, ${String(n.ruleCount)} rule${n.ruleCount===1?"":"s"})`;process.stdout.write(`${o} ${t?$e(i):i}
950
- `),process.stdout.write(` ${n.summary}
951
- `);const s=n.packageName?`install: npm add ${n.packageName}`:"no driver — bespoke implementation required";process.stdout.write(` ${t?$e(s):s}
952
-
953
- `)}},"printListValidators"),TT=et(async(e,t,r)=>{const n=v(e,jn);!r&&E(n)&&(se(`Detected existing ${jn} — refusing to overwrite. Delete it first to re-init.`),process.exit(1)),S(r?"[dry-run] Previewing init — no files will be written.":"Scanning workspace to seed baseline…");const o=Ku("scanning");let i;try{i=await gl([e],t)}finally{o.stop()}if(r){S(`[dry-run] Would create ${jn} with ${String(i.length)} finding(s).`);return}const s=Yu(i,n,e,{replace:!0});ee(`Wrote ${jn} (${String(s)} findings).`),ie("Commit it. Use `vis secrets --baseline .secrets-baseline.json` in CI. Add path patterns to .gitignore to exclude directories from scanning.")},"runInit"),RT=et((e,t,r)=>{const n=t??{},o=et(k=>k?xe(r,k):void 0,"resolvePath"),i=et((k,$)=>{const x=Dc(k);return x.length>0?x:$},"pickList"),s=i(e.enableRule,n.rules?.enable),a=i(e.excludeRule,n.rules?.exclude),c=i(e.includeRule,n.rules?.include),d=i(e.exclude,n.walk?.excludePatterns),p=Dc(e.excludeFrom).map(k=>xe(r,k)),g=p.length>0?p:n.walk?.excludeFromFiles?.map(k=>xe(r,k)),h=o(e.baseline)??o(n.baseline),y=o(e.config)??o(n.config?.path),w=CT(e.minConfidence??n.config?.minConfidence);return{baseline:h,concurrency:e.concurrency,config:{extendBundled:e.noExtendBundled?!1:n.config?.extendBundled,inline:n.config?.inline,minConfidence:w,onlyVerified:e.onlyVerified??n.config?.onlyVerified??!1,path:y,validate:e.validate??n.config?.validate??!1},redact:e.redact??n.redact,rules:{enable:s,exclude:a,include:c},verbose:e.verbose??!1,walk:{excludeFromFiles:g,excludePatterns:d,gitignore:e.noGitignore?!1:n.walk?.gitignore??!0,includeHidden:e.includeHidden??n.walk?.includeHidden,maxFileSize:e.maxSize??n.walk?.maxFileSize}}},"resolveScanOptions"),AT=et(e=>{process.stderr.write(`${$e("baseline diff: ")}${Ot(`+${String(e.fresh.length)} new`)} · ${Re(`${String(e.surviving.length)} unchanged`)} · ${$e(`-${String(e.resolved.length)} resolved`)}
954
- `)},"printDiff"),IT=et(async(e,t,r)=>{if(e.staged)return Oi(r)||(Ze("--staged requires a git working tree, and none was detected."),process.exit(2)),{files:bT(r)};if(e.since)return Oi(r)||(Ze("--since requires a git working tree, and none was detected."),process.exit(2)),{files:Nc(r,e.since)};if(e.affected){if(!Oi(r))return se("--affected requires git; falling back to full scan"),{paths:t&&t.length>0?t.map(o=>xe(r,o)):[r]};const n=process.env.VIS_BASE??"HEAD~1";return{files:Nc(r,n)}}return{paths:t&&t.length>0?t.map(n=>xe(r,n)):[r]}},"chooseScanPaths"),OT=et((e,t,r,n,o,i)=>{switch(t){case"json":{const s=e.map(a=>_n(a,r));process.stdout.write(`${JSON.stringify(s,null,2)}
955
- `);break}case"sarif":{process.stdout.write(`${wT(e,o,r,i)}
956
- `);break}default:process.stdout.write(`${hT(e,r,n)}
957
- `)}},"emitFindings"),PT={argument:{description:"One or more paths to scan (defaults to workspace root)",name:"paths",type:String},description:"Scan a repository for hardcoded secrets and credentials",examples:[["vis secrets","Scan the workspace with grouped, colourised output"],["vis secrets --staged","Scan only files staged for the current commit (pre-commit hooks)"],["vis secrets --since main","Scan only files changed since the `main` branch"],["vis secrets --affected","Scan only projects affected by the current branch"],["vis secrets --init","Write an initial baseline from current findings"],["vis secrets --list-rules","Print all bundled detection rules"],["vis secrets --list-validators","Print non-HTTP validator types in the ruleset + install hints for each"],["vis secrets --exclude-rule generic-api-key --exclude-rule aws-access-token","Drop noisy rules"],["vis secrets --include-rule stripe-access-token","Check a single rule"],["vis secrets --enable-rule tag:preset:weak-passwords","Enable an opt-in rule group additively (defaults still fire)"],["vis secrets --include-rule tag:preset:password-manager","Restrict output to one opt-in group only"],["vis secrets --min-confidence high","Drop rules without a high confidence label (CI-friendly precision filter)"],["vis secrets --validate --only-verified","Live-verify each finding against its provider (one HTTP call per finding)"],["vis secrets --exclude 'dist/**' --exclude-from .secretsignore","Extra gitignore-syntax exclusions for the walker"],["vis secrets --config ./leaks.json --no-extend-bundled","Use only the supplied config, skip the bundled ruleset"],["vis secrets --concurrency 4","Cap the rayon thread pool (0 / omit = auto)"],["vis secrets --baseline .secrets-baseline.json","Suppress known findings; print diff vs. baseline"],["vis secrets --update-baseline","Merge current findings into the baseline (use --replace-baseline to overwrite)"],["vis secrets --format sarif > report.sarif","SARIF output for GitHub code-scanning"]],execute:et(async({argument:e,options:t,visConfig:r,workspaceRoot:n})=>{const o=t,i=e,s=n??process.cwd(),a=!o.quiet&&process.stdout.isTTY,c=r?.secrets,d=RT(o,c,s),p="0.0.0-alpha";if(o.listRules){await jT(d,a);return}if(o.listValidators){await ET(d,a);return}if(o.init){await TT(s,d,o.dryRun??!1);return}const g=await IT(o,i??[],s);if(g.files?.length===0){o.quiet||ee("No files to scan.");return}const h=!o.quiet&&!["json","sarif"].includes(o.format??"text")?Ku("scanning for secrets"):{stop:et(()=>{},"stop"),update:et(()=>{},"update")};let y;try{y=g.files===void 0?await gl(g.paths??[s],d):await nf(g.files,d)}catch(T){h.stop(),Ze(`secret scan failed: ${T instanceof Error?T.message:String(T)}`),process.exit(2)}finally{h.stop()}if(o.verbose){const T=await of(d);if(T.length>0){se(`${String(T.length)} rule(s) skipped due to invalid regex. First few:`);for(const I of T.slice(0,5))process.stderr.write(` - ${I.ruleId}: ${I.reason}
958
- `)}}const w=d.baseline??v(s,jn),k=!o.quiet&&E(w);if(o.updateBaseline){const T=Yu(y,w,s,{replace:o.replaceBaseline});ee(`Baseline updated: ${He(s,w)||w} now contains ${String(T)} entries.`);return}const $=ST(o.format),x=$==="sarif"?await fl(d).catch(()=>[]):[];OT(y,$,s,a,p,x),$==="text"&&k&&AT(uT(y,w,s)),y.length>0&&(o.quiet||(se(`${String(y.length)} potential secret(s) found`),ie("Suppress individual lines with `gitleaks:allow` / `secret-scanner:allow`, or run `vis secrets --update-baseline`.")),process.exit(1)),o.quiet||ee("No secrets detected.")},"execute"),group:"Security",name:"secrets",options:[{description:"Path to a JSON config (gitleaks-compatible shape). Defaults to the bundled ruleset.",name:"config",type:String},{description:"Drop rules below this author-declared confidence: low (default), medium, high. Rules without a declared confidence (every gitleaks rule) are treated as low, so --min-confidence medium or higher drops them along with explicit low-confidence rules.",name:"min-confidence",type:String},{defaultValue:!1,description:"Live-verify each finding against its provider (one HTTP call per finding, max 8 concurrent). Only supports Kingfisher-style HTTP validators with StatusMatch / WordMatch response matchers; other types (gRPC, multi-step, checksum) mark the finding as validation=skipped. WARNING: sends candidate secrets to the provider — some providers alert their security team on failed auth attempts.",name:"validate",type:Boolean},{defaultValue:!1,description:"With --validate, drop every finding whose validation is not 'verified'. Useful for CI gating.",name:"only-verified",type:Boolean},{defaultValue:!1,description:"With --config, do not merge on top of the bundled ruleset — replace it.",name:"no-extend-bundled",type:Boolean},{defaultValue:"text",description:"Output format: text (default), json, sarif",name:"format",type:String},{description:"Path to a baseline JSON of previously-triaged findings",name:"baseline",type:String},{defaultValue:!1,description:"Scan only files staged for commit",name:"staged",type:Boolean},{description:"Scan only files changed since <ref> (e.g. main, origin/HEAD)",name:"since",type:String},{defaultValue:!1,description:"Scan only projects affected by the current branch",name:"affected",type:Boolean},{description:"Enable an opt-in rule or tag without restricting output — additive (e.g. tag:preset:weak-passwords, tag:preset:password-manager). Repeatable.",multiple:!0,name:"enable-rule",type:String},{description:"Rule id or tag:<name> selector — whitelist, only matching findings are emitted. Implies enablement. Repeatable.",multiple:!0,name:"include-rule",type:String},{description:"Rule id or tag:<name> selector — drop matching findings. Repeatable.",multiple:!0,name:"exclude-rule",type:String},{description:"Gitignore-syntax pattern to exclude from the walk (repeatable)",multiple:!0,name:"exclude",type:String},{description:"Path to a gitignore-shaped file the walker should honor (repeatable)",multiple:!0,name:"exclude-from",type:String},{defaultValue:!1,description:"Mask secret values in output",name:"redact",type:Boolean},{defaultValue:!1,description:"Scan dotfiles",name:"include-hidden",type:Boolean},{defaultValue:!1,description:"Do not respect .gitignore",name:"no-gitignore",type:Boolean},{description:"Skip files larger than this (bytes). Default: 10 MiB",name:"max-size",type:Number},{description:"Rayon worker threads (0 / omit = auto)",name:"concurrency",type:Number},{defaultValue:!1,description:"Merge current findings into the baseline and exit 0",name:"update-baseline",type:Boolean},{defaultValue:!1,description:"With --update-baseline, replace rather than merge",name:"replace-baseline",type:Boolean},{defaultValue:!1,description:"Scaffold a baseline from current findings",name:"init",type:Boolean},{defaultValue:!1,description:"With --init, preview the baseline without writing files",name:"dry-run",type:Boolean},{defaultValue:!1,description:"Print all bundled detection rules and exit",name:"list-rules",type:Boolean},{defaultValue:!1,description:"Print non-HTTP validator types referenced by the current ruleset, with install hints for their optional peer dependencies.",name:"list-validators",type:Boolean},{defaultValue:!1,description:"Suppress all progress output (only emit findings)",name:"quiet",type:Boolean},{defaultValue:!1,description:"Print diagnostic info (skipped rules, etc.)",name:"verbose",type:Boolean}]};var NT=Object.defineProperty,No=b((e,t)=>NT(e,"name",{value:t,configurable:!0}),"d$4");const MT=No(e=>{const t=new Set,r=[],n=No(i=>{const s=xe(i);!t.has(s)&&E(s)&&(t.add(s),r.push(s))},"addFile");n(v(e,"package.json"));const o=Wo(e);if(o){const i=Or(e,o);for(const s of i)n(v(e,s,"package.json"))}else{const i=v(e,"package.json");if(E(i)){const s=JSON.parse(q(i)),a=Array.isArray(s.workspaces)?s.workspaces:s.workspaces?.packages;if(a){const c=Or(e,a);for(const d of c)n(v(e,d,"package.json"))}}}return r},"findPackageJsonFiles"),DT=No((e,t)=>{const r=Go();if(!r)throw new Error("Native bindings unavailable: sort-package-json requires the native addon. Ensure the correct platform binary is installed.");return r.sortPackageJsonStringWithOptions(e,{pretty:!0,sort_scripts:t})},"sortContents"),BT={description:"Sort package.json files across the workspace using the sort-package-json Rust crate",examples:[["vis sort-package-json","Sort all package.json files in the workspace"],["vis sort-package-json --check","Check if files are already sorted (exit 1 if not)"],["vis sort-package-json --sort-scripts","Also sort the scripts field alphabetically"]],execute:No(async({options:e,visConfig:t,workspaceRoot:r})=>{const n=r??process.cwd(),o=t?.sortPackageJson,i=e.check||!1,s=e.sortScripts||o?.sortScripts||!1,a=MT(n);if(a.length===0){S("No package.json files found.");return}let c=0,d=0,p=0;for(const g of a)try{const h=q(g);let y;try{y=DT(h,s)}catch($){Ze(`${g}: ${Ni($)}`),p++;continue}const w=h.endsWith(`
959
- `)?h:`${h}
960
- `,k=y.endsWith(`
961
- `)?y:`${y}
962
- `;if(w===k){d++;continue}c++,i?se(`${g} is not sorted`):(me(g,k,"utf8"),ee(`Sorted ${g}`))}catch(h){Ze(`${g}: ${Ni(h)}`),p++}if(i)c>0?(S(`${c} file${c===1?"":"s"} not sorted, ${d} already sorted`),process.exitCode=1):S(`All ${d} package.json file${d===1?" is":"s are"} sorted`);else{const g=[];c>0&&g.push(`sorted ${c} file${c===1?"":"s"}`),d>0&&g.push(`${d} already sorted`),p>0&&g.push(`${p} error${p===1?"":"s"}`),S(g.join(", "))}p>0&&(process.exitCode=1)},"execute"),group:"Workspace",name:"sort-package-json",options:[{alias:"c",defaultValue:!1,description:"Check if package.json files are sorted without writing (exits 1 if unsorted)",name:"check",type:Boolean},{defaultValue:!1,description:"Also sort the scripts field alphabetically",name:"sort-scripts",type:Boolean}]};var FT=Object.defineProperty,LT=b((e,t)=>FT(e,"name",{value:t,configurable:!0}),"n");const VT="VIS_STAGED_CONCURRENT",Bc=LT(e=>{const t=e.trim();if(t==="true"||t==="")return!0;if(t==="false")return!1;const r=Number(t);return Number.isNaN(r)?!0:r},"parseConcurrent");var _T=Object.defineProperty,bo=b((e,t)=>_T(e,"name",{value:t,configurable:!0}),"s$3");const UT=bo((e,t)=>{const r={};t!==void 0&&(r.config=t);const n=bo(P=>e[P]===void 0?void 0:!!e[P],"readBool"),o=bo(P=>{const R=e[P];return typeof R=="string"&&R.length>0?R:void 0},"readString"),i=n("allow-empty");i!==void 0&&(r.allowEmpty=i);const s=n("auto-stage");s!==void 0&&(r.autoStage=s);const a=n("continue-on-error");a!==void 0&&(r.continueOnError=a);const c=n("debug");c!==void 0&&(r.debug=c);const d=n("fail-on-changes");d!==void 0&&(r.failOnChanges=d);const p=n("hide-partially-staged");p!==void 0&&(r.hidePartiallyStaged=p);const g=n("hide-unstaged");g!==void 0&&(r.hideUnstaged=g);const h=n("quiet");h!==void 0&&(r.quiet=h);const y=n("relative");y!==void 0&&(r.relative=y);const w=n("revert");w!==void 0&&(r.revert=w);const k=n("stash");k!==void 0&&(r.stash=k);const $=n("verbose");$!==void 0&&(r.verbose=$);const x=o("cwd");x!==void 0&&(r.cwd=x);const T=o("diff");T!==void 0&&(r.diff=T);const I=o("diff-filter");if(I!==void 0&&(r.diffFilter=I),n("force-kill")===!0&&(r.killSignal="SIGKILL"),e.concurrent===void 0){const P=process.env[VT];P!==void 0&&(r.concurrent=Bc(P.trim()))}else r.concurrent=Bc(String(e.concurrent));return r},"buildRunOptions"),WT={description:"Run linters on staged files using config from vis.config.ts",examples:[["vis staged","Run staged linters"],["vis staged --verbose","Run with verbose output"],["vis staged --no-stash","Run without backup stash"],["vis staged --diff HEAD~1","Run against a specific diff"]],execute:bo(async({options:e,visConfig:t})=>{const r=(t??{}).staged;if(!r)throw new Error(`No "staged" config found in vis.config.ts. Add one:
963
-
964
- // vis.config.ts
965
- import { defineConfig } from "@visulima/vis/config";
966
-
967
- export default defineConfig({
968
- staged: { '*': 'vis check --fix' },
969
- });
970
-
971
- Migrating from lint-staged or nano-staged? Run \`vis migrate lint-staged\` (or \`vis migrate nano-staged\`) to move the config in and remove the legacy files.`);const n=await _g(UT(e,r));process.exit(n.success?0:1)},"execute"),group:"Run & Execute",name:"staged",options:[{defaultValue:!1,description:"Allow empty commits when tasks revert all staged changes",name:"allow-empty",type:Boolean},{defaultValue:!1,description:"Automatically stage new files that tasks create during the run",name:"auto-stage",type:Boolean},{description:"Number of concurrent tasks or false for serial",name:"concurrent",type:String},{defaultValue:!1,description:"Run all tasks to completion even if one fails",name:"continue-on-error",type:Boolean},{description:"Working directory to run all tasks in",name:"cwd",type:String},{defaultValue:!1,description:"Enable debug output",name:"debug",type:Boolean},{description:"Override the default --staged flag of git diff",name:"diff",type:String},{description:"Override the default diff-filter",name:"diff-filter",type:String},{defaultValue:!1,description:"Fail with exit code 1 when tasks modify tracked files",name:"fail-on-changes",type:Boolean},{defaultValue:!1,description:"Kill in-flight tasks with SIGKILL on fast-fail instead of the default SIGTERM",name:"force-kill",type:Boolean},{defaultValue:!1,description:"Hide unstaged changes from partially staged files",name:"hide-partially-staged",type:Boolean},{defaultValue:!1,description:"Hide all unstaged changes before running tasks",name:"hide-unstaged",type:Boolean},{defaultValue:!1,description:"Suppress console output",name:"quiet",type:Boolean},{defaultValue:!1,description:"Pass filepaths relative to cwd to tasks",name:"relative",type:Boolean},{defaultValue:!1,description:"Revert to original state in case of errors",name:"revert",type:Boolean},{defaultValue:!0,description:"Enable backup stash",name:"stash",type:Boolean},{defaultValue:!1,description:"Show task output even when tasks succeed",name:"verbose",type:Boolean}]};var GT=Object.defineProperty,Xu=b((e,t)=>GT(e,"name",{value:t,configurable:!0}),"d$3");const xn=Xu(e=>e?Ot("✓"):Ge("✗"),"icon"),HT={description:"Show a workspace health dashboard at a glance",examples:[["vis status","Full status overview"],["vis status --json","Machine-readable output"]],execute:Xu(async({logger:e,options:t,visConfig:r,workspaceRoot:n})=>{if(!n)throw new Error("Could not determine workspace root.");const{config:o,packageJsons:i,workspace:s}=mt(n,r),a=nr(n,s,i),c=Object.keys(s.projects).length,d=new Set(Object.values(s.projects).flatMap(k=>Object.keys(k.targets??{}))).size,p=_d(n);let g=0;o.constraints&&(g=Xc(a,o.constraints).length);const h=Ru(n,{minRuns:2});let y;const w=v(n,".task-runner","runs");if(E(w)){const k=Ve(w).filter(T=>T.endsWith(".json")).sort();let $=0,x=0;for(const T of k.slice(-20))try{const I=ue(v(w,T));I.stats&&($+=I.stats.total??0,x+=I.stats.cached??0)}catch{continue}$>0&&(y=`${(x/$*100).toFixed(0)}%`)}if(t.json){e.info(JSON.stringify({cacheHitRate:y??null,constraintViolations:g,flakyTasks:h.length,projects:c,runtimeIssues:p.length,targets:d},null,2));return}e.info(""),e.info(` ${$e("VIS STATUS")}`),e.info(""),e.info(` ${xn(!0)} ${String(c)} projects · ${String(d)} unique targets`),e.info(` ${xn(p.length===0)} Runtime: ${p.length===0?Ot("OK"):Re(`${String(p.length)} issue(s)`)}`),e.info(` ${xn(g===0)} Constraints: ${g===0?Ot("OK"):Ge(`${String(g)} violation(s)`)}`),e.info(` ${xn(h.length===0)} Flaky tasks: ${h.length===0?Ot("none"):Re(String(h.length))}`),y&&e.info(` ${xn(!0)} Cache hit rate: ${y} (last 20 runs)`),e.info("")},"execute"),group:"Workspace",name:"status",options:[{defaultValue:!1,description:"Emit JSON output",name:"json",type:Boolean}]};var zT=Object.defineProperty,Xs=b((e,t)=>zT(e,"name",{value:t,configurable:!0}),"i$1");const qT=Xs((e,t)=>{const r=t.replace(/^\.?\//,"");return r===""||r==="."?`/${e}/`:e===""||e==="."?`/${r}`:`/${e}/${r}`},"toWorkspacePath"),JT=Xs((e,t)=>{const r=[];for(const[n,o]of Object.entries(t?.globalPaths??{}))r.push({owners:o,path:n});for(const[n,o]of Object.entries(e.projects)){const i=o.owners??[];for(const s of i)r.push({channel:s.channel,owners:s.owners,path:qT(o.root??n,s.path),projectId:n})}return(t?.orderBy??"file-source")==="project-id"?r.sort((n,o)=>(n.projectId??"").localeCompare(o.projectId??"")||n.path.localeCompare(o.path)):r.sort((n,o)=>n.path.localeCompare(o.path)),r},"buildCodeownersLines"),YT=["# CODEOWNERS — generated by `vis sync codeowners`. Do not edit by hand.","# Update each project's project.json `owners` field and re-run the command.",""],KT=Xs((e,t="github")=>{const r=[...YT];for(const n of e){const o=n.owners.join(" "),i=n.channel?` # notify: ${n.channel}`:"";r.push(`${n.path} ${o}${i}`)}return r.push(""),r.join(`
972
- `)},"renderCodeowners");var XT=Object.defineProperty,QT=b((e,t)=>XT(e,"name",{value:t,configurable:!0}),"u$4");const ZT={argument:{description:"What to sync: codeowners",name:"kind",type:String},description:"Synchronise derived workspace artefacts (codeowners, tsconfig refs, …)",examples:[["vis sync codeowners","Generate CODEOWNERS at the repository root"],["vis sync codeowners --out=.github/CODEOWNERS","Write to .github/CODEOWNERS instead"],["vis sync codeowners --check","Fail if the existing file is stale"]],execute:QT(async({argument:e,logger:t,options:r,visConfig:n,workspaceRoot:o})=>{const i=e[0];if(!i)throw new Error("Missing sync kind. Usage: vis sync <kind> (known kinds: codeowners)");if(!o)throw new Error("Could not determine workspace root. Run inside a monorepo.");if(i!=="codeowners")throw new Error(`Unknown sync kind: "${i}". Known kinds: codeowners.`);const{workspace:s}=mt(o,n),a=JT(s,n?.codeowners);if(a.length===0){t.info("No `owners` entries found in any project. Nothing to sync.");return}const c=KT(a,n?.codeowners?.provider??"github"),d=r.out?v(o,String(r.out)):v(o,"CODEOWNERS");if(r.check){let p="";try{p=el(d,"utf8")}catch(g){if(g.code==="ENOENT")p="";else throw g}if(p.trim()!==c.trim()){t.error(`${d} is out of date. Run \`vis sync codeowners\` to update it.`),process.exitCode=1;return}t.info(`${d} is up to date.`);return}Z(d,c),t.info(`Wrote ${a.length} entries to ${d}`)},"execute"),group:"Workspace",name:"sync",options:[{description:"Output path for the generated file (default: <workspace>/CODEOWNERS)",name:"out",type:String},{defaultValue:!1,description:"Verify the existing file is up to date (exit non-zero if stale)",name:"check",type:Boolean}]};var eR=Object.defineProperty,Qs=b((e,t)=>eR(e,"name",{value:t,configurable:!0}),"h$2");const tR=Qs((e,t)=>{const r=new Map;for(const[i,s]of Object.entries(e.dependencies))for(const a of s){const c=r.get(a)??[];c.push(i),r.set(a,c)}if(!e.tasks[t])return;const n=new Set([t]),o=[{node:t,path:[t]}];for(;o.length>0;){const i=o.shift();if(e.roots.includes(i.node))return i.path;for(const s of r.get(i.node)??[])n.has(s)||(n.add(s),o.push({node:s,path:[s,...i.path]}))}return[t]},"findShortestPathToRoot"),rR=Qs((e,t)=>{const r=[];for(const[n,o]of Object.entries(e.dependencies))o.includes(t)&&r.push(n);return r.sort()},"collectParents"),nR={argument:{description:"Task ID to explain (e.g. @my/app:build)",name:"taskId",type:String},description:"Explain why a task is included in the graph by walking its dependency chain to a root",examples:[["vis task-why @myorg/app:build","Show what pulls build in"],["vis task-why lib-a:test","Check the test task's triggers"]],execute:Qs(async({argument:e,logger:t,visConfig:r,workspaceRoot:n})=>{if(!n)throw new Error("Could not determine workspace root.");const o=e[0];if(!o)throw new Error("No task ID specified. Usage: vis task-why <project>:<target>");if(!o.includes(":"))throw new Error(`Invalid task ID "${o}" — expected format "project:target".`);const{packageJsons:i,workspace:s}=mt(n,r),a=nr(n,s,i),[c,d]=o.split(":",2),p=s.projects[c];if(!p)throw new Error(`Unknown project "${c}".`);if(!p.targets?.[d])throw new Error(`Project "${c}" has no target "${d}".`);const g=Object.entries(s.projects).flatMap(([$,x])=>Object.keys(x.targets??{}).map(T=>({id:`${$}:${T}`,outputs:[],overrides:{},target:{project:$,target:T}}))),h=es(g,{projectGraph:a,workspace:s});if(!h.tasks[o])throw new Error(`Task "${o}" is not reachable in the graph.`);const y=tR(h,o),w=rR(h,o);if(t.info(""),t.info(`Why ${o}?`),t.info(""),y&&y.length>1){t.info("Shortest path from a root to this task:");for(const[$,x]of y.entries()){const T=$===0?" ":`${" ".repeat($+1)}└─ `;t.info(`${T}${x}`)}t.info("")}else t.info(" This task is itself a root — nothing upstream depends on it."),t.info("");if(w.length>0){t.info(`Directly depended on by ${w.length} task(s):`);for(const $ of w)t.info(` - ${$}`);t.info("")}const k=h.dependencies[o]??[];if(k.length>0){t.info(`This task depends on ${k.length} task(s):`);for(const $ of[...k].sort())t.info(` - ${$}`);t.info("")}},"execute"),group:"Workspace",name:"task-why"};var oR=Object.defineProperty,iR=b((e,t)=>oR(e,"name",{value:t,configurable:!0}),"c$2");const sR={argument:{description:"Packages to unlink (omit for current package)",name:"packages",type:String},description:"Unlink a previously linked package",examples:[["vis unlink","Unlink current package"],["vis unlink react","Unlink specific package"],["vis unlink -r","Unlink in all workspace packages"]],execute:iR(async({argument:e,logger:t,options:r,workspaceRoot:n})=>{const o=e||[],i=n??process.cwd(),s=Ne(i),a=Rm(s,o,r.recursive||!1,i,t);a!==0&&(process.exitCode=a)},"execute"),group:"Dependencies",name:"unlink",options:[{alias:"r",defaultValue:!1,description:"Unlink in all workspace packages",name:"recursive",type:Boolean}]};var aR=Object.defineProperty,yn=b((e,t)=>aR(e,"name",{value:t,configurable:!0}),"s$1");const cR=yn(e=>{const t=[];for(const r of e.filters)t.push("--filter",r);return e.workspaceRoot&&t.push("--filter","."),t.push("update"),e.latest&&t.push("--latest"),e.recursive&&t.push("--recursive"),e.interactive&&t.push("--interactive"),e.dev&&t.push("--dev"),e.prod&&t.push("--prod"),e.noOptional&&t.push("--no-optional"),e.noSave&&t.push("--no-save"),t.push(...e.packages),{args:t,bin:"pnpm"}},"resolvePnpm"),lR=yn(e=>{const t=[];return e.filters.length>0&&t.push("workspace",e.filters[0]),t.push("upgrade"),e.latest&&t.push("--latest"),t.push(...e.packages),{args:t,bin:"yarn"}},"resolveYarnV1"),dR=yn(e=>{const t=[];if(e.filters.length>0||e.recursive){t.push("workspaces","foreach","--all");for(const r of e.filters)t.push("--include",r)}return t.push("up"),e.interactive&&t.push("--interactive"),t.push(...e.packages),{args:t,bin:"yarn"}},"resolveYarnBerry"),uR=yn((e,t)=>{const r=["update"];e.latest&&t.push("npm does not support --latest flag. Packages will be updated within their semver range."),e.interactive&&t.push("npm does not support --interactive mode.");for(const n of e.filters)r.push("--workspace",n);return e.recursive&&r.push("--workspaces"),e.workspaceRoot&&r.push("--include-workspace-root"),e.dev&&r.push("--dev"),e.prod&&r.push("--production"),e.noOptional&&r.push("--no-optional"),e.noSave&&r.push("--no-save"),r.push(...e.packages),{args:r,bin:"npm"}},"resolveNpm"),pR=yn(e=>{const t=["update"];e.latest&&t.push("--latest");for(const r of e.filters)t.push("--filter",r);return t.push(...e.packages),{args:t,bin:"bun"}},"resolveBun"),fR=yn((e,t,r)=>{const n=[];if(r.global)return{command:{args:["update","--global",...r.packages],bin:"npm"},warnings:n};let o;switch(e){case"bun":{o=pR(r);break}case"npm":{o=uR(r,n);break}case"pnpm":{o=cR(r);break}case"yarn":{o=t.startsWith("1.")?lR(r):dR(r);break}default:{const i=e;throw new Error(`Unsupported package manager: ${String(i)}`)}}return{command:o,warnings:n}},"resolveUpdateCommand");var gR=Object.defineProperty,$r=b((e,t)=>gR(e,"name",{value:t,configurable:!0}),"w");const mR=$r((e,t)=>{try{if(t==="pnpm"){const r=v(e,"pnpm-workspace.yaml");if(E(r)){const n=ln(r);if(typeof n?.minimumReleaseAge=="number")return n.minimumReleaseAge}}else if(t==="bun"){const r=v(e,"package.json");if(E(r)){const n=ue(r);if(typeof n.minimumReleaseAge=="number")return n.minimumReleaseAge}}}catch{}},"readPmNativeMinimumReleaseAge"),hR=$r((e,t,r)=>{const n=e.latest?"latest":e.target??t.target??"latest";if(!["latest","minor","patch"].includes(n))throw new Error(`Invalid target "${n}". Use: latest, minor, or patch.`);return{exclude:[...bt(e.exclude),...bt(t.exclude)],ignore:bt(t.ignore),include:[...bt(e.include),...bt(t.include),...r],includeLocked:e.includeLocked||t.includeLocked||!1,includePrerelease:e.prerelease||t.prerelease||!1,minimumReleaseAge:t.minimumReleaseAge,minimumReleaseAgeExclude:t.minimumReleaseAgeExclude,packageMode:t.packageMode,security:e.security||e.ai||t.security||!1,target:n}},"buildCatalogCheckOptions"),Fc=$r((e,t)=>{if(e.length!==0){t.info(`
973
- ${Re("⚠")} ${String(e.length)} package${e.length===1?"":"s"} skipped by target constraint (use --target latest to include):`);for(const r of e)t.info(` ${r.packageName} ${r.currentRange} → ${r.newRange} (${r.updateType})`)}},"logFilteredByTarget"),Lc=$r((e,t,r,n)=>{r==="json"?process.stdout.write(`${lv({checkedCount:0,failed:t,filteredByTarget:[],ignored:[],outdated:e})}
974
- `):r==="minimal"?process.stdout.write(`${pd(e)}
975
- `):(fd(e,n),n.info(Eo(e)))},"writeFormattedOutput"),Vc=$r(async(e,t,r,n,o)=>{const i=vv(e,r,t),s=t==="pnpm"?"pnpm-workspace.yaml":"package.json";if(o.info(`
976
- Updated ${s}`),i&&o.info(`Backup saved to ${i}`),n.changelog){o.info(`
977
- Fetching changelogs...`);const a=await gd(r);for(const c of a){const d=c.releaseUrl??c.repoUrl??c.npmUrl;o.info(` ${c.packageName}: ${d}`)}}if(n.install??!0){const a={bun:"bun install",npm:"npm install",pnpm:"pnpm install",yarn:"yarn install"}[t]??`${t} install`;o.info(`Running ${a}...
978
- `);try{zn(a,{cwd:e,env:process.env,stdio:"inherit"})}catch{o.warn(`${a} failed. You may need to run it manually.`)}}},"applyCatalogAndInstall"),yR=$r(async(e,t,r,n,o,i)=>{const s=r.update??{},a=[["global","--global is not supported in catalog mode"],["recursive","--recursive is not needed in catalog mode (catalogs are workspace-level)"],["filter","--filter is not supported in catalog mode (use --include/--exclude instead)"],["no-save","--no-save is not supported in catalog mode"],["workspace-root","--workspace-root is not needed in catalog mode"],["no-optional","--no-optional is not supported in catalog mode"]];for(const[N,F]of a)n[N]&&i.warn(`${Re("⚠")} ${F}, ignoring.`);const c=mR(e,t),d=s.minimumReleaseAge??c;if(s.minimumReleaseAge!==void 0&&c!==void 0&&s.minimumReleaseAge!==c){const N=t==="pnpm"?"pnpm-workspace.yaml":"package.json";i.warn(`${Re("⚠")} minimumReleaseAge mismatch: vis config = ${String(s.minimumReleaseAge)} min, ${N} = ${String(c)} min. Consider keeping them in sync.`)}const p=$s(e),g=Jo(e,t,{depFields:s.depFields,dev:n.dev,prod:n.prod});if(g.size===0){i.info("No catalogs found.");return}const h={...s,minimumReleaseAge:d},y=hR(n,h,o);let w=0;for(const N of g.values())w+=N.size;const k=!!process.stdout.isTTY&&!ft;let $;const x=k?(N,F)=>{$?$.rerender(Q.createElement(Bn,{current:N,total:F})):$=Xt(Q.createElement(Bn,{current:N,total:F}),{interactive:!0,patchConsole:!1})}:(N,F)=>{i.info(`Checking ${String(N)}/${String(F)} dependencies...`)};k||i.info(`Checking ${String(w)} catalog dependencies...
979
- `);const T=Lr(r.security?.socket),{checkedCount:I,failed:P,filteredByTarget:R,ignored:M,outdated:L}=await xs(g,y,p,x,e,T,r.security?.socket?.acceptedRisks);$&&($.clear(),$.unmount());const U=I-L.length-P.length;if(P.length>0&&i.warn(`Failed to fetch: ${P.join(", ")}`),M.length>0&&i.info(`Skipped ${String(M.length)} ignored package${M.length===1?"":"s"}: ${M.join(", ")}`),!k&&I>L.length){const N=[...g.values()].reduce((J,Y)=>J+Y.size,0),F=N>I?` (${String(N)} catalog entries, ${String(N-I)} duplicates)`:"";i.info(`Checked ${String(I)} unique packages${F}: ${String(L.length)} outdated, ${String(U)} up-to-date${P.length>0?`, ${String(P.length)} failed`:""}${R.length>0?`, ${String(R.length)} skipped by target`:""}`)}if(L.length===0){R.length>0?i.info(`All catalog dependencies are up to date within the current target.
980
- ${String(R.length)} package${R.length===1?" has":"s have"} newer versions available with --target latest:
981
- ${R.map(N=>` ${N.packageName} ${N.currentRange} → ${N.newRange} (${N.updateType})`).join(`
982
- `)}`):i.info("All catalog dependencies are up to date.");return}const D=n.format??s.format??"table";let C;if(n.ai){const N=vs(n.aiType??"impact");C=await ws(L,i,r.ai,N)}const j=!!n.dryRun;if(k&&D==="table"){const N=new Sd(L,C??null);let F;if(n.changelog){i.info("Fetching changelogs...");const B=await gd(L);F=new Map;for(const O of B){const H=O.releaseUrl??O.repoUrl??O.npmUrl;H&&F.set(O.packageName,H)}}const J=r.tui?.autoExit??!1,Y=J===!0?3:typeof J=="number"?J:0,ce=await Xt(Q.createElement(Cd,{autoExitSeconds:Y,changelogUrls:F,checkedCount:I,filteredOutEntries:R,isDryRun:j,store:N,totalCatalogEntries:w}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit(),le=process.stdout.columns||80;process.stdout.write(`
983
- `);for(const B of L){const O=B.vulnerabilities?.length||B.socketReport&&B.socketReport.alerts.length>0,H=!!B.acceptedRisk,ye=O?H?"✓":"⚠":"✓",Ee=H?"gray":B.updateType==="major"?"red":B.updateType==="minor"?"yellow":"green",Ae=B.socketReport?.score.overall,Tt=Ae===void 0?"":` [${String(Math.round(Ae*100))}%]`,X=Ae===void 0?void 0:Jn(Ae);process.stdout.write(`${Oe(Q.createElement(l,null," ",Q.createElement(l,{color:Ee},ye),` ${B.packageName} ${B.currentRange} → ${B.newRange}`,Q.createElement(l,{dimColor:!0},` ${B.updateType}`),X?Q.createElement(l,{color:X},Tt):null),{columns:le})}
984
- `)}if(process.stdout.write(`
985
- `),i.info(Eo(L)),I>L.length){const B=[...g.values()].reduce((H,ye)=>H+ye.size,0),O=B>I?` (${String(B)} catalog entries, ${String(B-I)} duplicates)`:"";i.info(` Checked ${String(I)} unique packages${O}: ${String(U)} up-to-date${P.length>0?`, ${String(P.length)} failed`:""}`)}if(R.length>0){process.stdout.write(`
986
- `);const B=`${String(R.length)} package${R.length===1?"":"s"} skipped by target constraint (use --target latest to include):`;process.stdout.write(`${Oe(Q.createElement(l,{color:"yellow"},` ${B}`),{columns:le})}
987
- `);for(const O of R)process.stdout.write(`${Oe(Q.createElement(l,null," ",Q.createElement(l,{dimColor:!0},O.packageName),` ${O.currentRange} → ${O.newRange}`,Q.createElement(l,{dimColor:!0},` ${O.updateType}`)),{columns:le})}
988
- `)}const be=Array.isArray(ce)?ce:[];if(be.length>0&&!j){i.info(`
989
- Applying ${String(be.length)} updates...
990
- `);const B={...n,install:n.install??s.install};await Vc(e,t,be,B,i)}return}if(j){if(D==="json"){const N={failed:P,filteredByTarget:R,ignored:M,outdated:L};C&&(N.aiAnalysis=C),process.stdout.write(`${JSON.stringify(N,void 0,2)}
991
- `)}else i.info(`Would update ${String(L.length)} dependencies:
992
- `),Lc(L,P,D,i),C&&(i.info(""),i.info(jo(C))),Fc(R,i);return}C&&D!=="json"&&(i.info(jo(C)),i.info(""));let A=L;if(n.interactive&&(A=await wv(L),A.length===0)){i.info("No updates selected.");return}i.info(`Updating ${String(A.length)} catalog dependencies...
993
- `),Lc(A,[],D,i),Fc(R,i);const V={...n,install:n.install??s.install};await Vc(e,t,A,V,i)},"executeCatalogUpdate"),vR=$r((e,t,r,n,o,i)=>{const s={dev:n.dev,filters:bt(n.filter),global:n.global,interactive:n.interactive,latest:n.latest||n.target==="latest",noOptional:n.noOptional,noSave:n.noSave,packages:o,prod:n.prod,recursive:n.recursive,workspaceRoot:n.workspaceRoot},{command:a,warnings:c}=fR(t,r,s);for(const p of c)i.warn(p);const d=`${a.bin} ${a.args.join(" ")}`.trim();if(n.dryRun){i.info(`Would run: ${d}`);return}i.info(`Running: ${d}`);try{zn(d,{cwd:e,env:process.env,stdio:"inherit"})}catch(p){const g=p.status??1;i.error(`
994
- ${Ge("✖")} Update failed (exit code ${String(g)})`),i.error(` Command: ${d}`),i.error(` Directory: ${e}
995
- `),process.exitCode=g}},"executePmWrapper"),wR={alias:"up",argument:{description:"Packages to update (updates all if omitted)",name:"packages",type:String},description:"Update packages to their latest versions",examples:[["vis update react","Update react within semver range"],["vis up react -L","Update react to latest"],["vis update -i","Interactive mode"],["vis update --filter app","Update in specific workspace"],["vis update -r","Update in all workspaces"],["vis update --target minor","Only apply minor/patch updates (catalog mode)"],["vis update --dry-run","Preview changes without applying"],["vis update --exclude '@types/*'","Exclude packages by pattern"],["vis update --changelog","Show changelog links after updating"],["vis update --rollback","Restore catalog from last backup"],["vis update --ai","Run AI analysis before applying updates"]],execute:$r(async({argument:e,logger:t,options:r,visConfig:n,workspaceRoot:o})=>{if(!o)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");let i=e;const s=o,{packageManager:a}=Mo(s);if(!r.noTyposquatCheck){if(i.length>0){const c=i.map(g=>ms(g)),d=n?.security?.typosquatAllowlist,p=await Ll(c.map(g=>g.name),d);if(!p.ok){process.exitCode=1;return}i=c.map((g,h)=>{const y=p.packages[h];return y!==g.name?g.versionSpec?`${y}@${g.versionSpec}`:y??"":i[h]??""})}else if(!await Vl(s,n?.security?.typosquatAllowlist)){process.exitCode=1;return}}if(r.rollback){if(!cv(s,a)){t.info("No backup found. Run 'vis update' first to create a backup.");return}if(av(s,a))t.info("Restored from backup.");else throw new Error("Failed to restore from backup.");return}if(!r.noCatalog&&Uy(s,a))await yR(s,a,n??{},r,i,t);else{const c=up(a);vR(s,a,c,r,i,t)}},"execute"),group:"Dependencies",name:"update",options:[{alias:"L",defaultValue:!1,description:"Update to latest version (ignore semver range)",name:"latest",type:Boolean},{alias:"t",description:"Update target: latest, minor, or patch (default: latest, catalog mode)",name:"target",type:String},{alias:"d",defaultValue:!1,description:"Preview changes without applying",name:"dry-run",type:Boolean},{alias:"g",defaultValue:!1,description:"Update global packages",name:"global",type:Boolean},{alias:"r",defaultValue:!1,description:"Update recursively in all workspace packages",name:"recursive",type:Boolean},{description:"Filter packages in monorepo",name:"filter",type:String},{alias:"w",defaultValue:!1,description:"Include workspace root",name:"workspace-root",type:Boolean},{alias:"D",defaultValue:!1,description:"Update only devDependencies",name:"dev",type:Boolean},{alias:"P",defaultValue:!1,description:"Update only dependencies",name:"prod",type:Boolean},{alias:"i",defaultValue:!1,description:"Interactive mode",name:"interactive",type:Boolean},{defaultValue:!1,description:"Don't update optionalDependencies",name:"no-optional",type:Boolean},{alias:"l",defaultValue:!1,description:"Include packages with pinned/exact versions (no ^ or ~ prefix)",name:"include-locked",type:Boolean},{defaultValue:!1,description:"Update lockfile only",name:"no-save",type:Boolean},{description:"Glob pattern to include packages (repeatable, catalog mode)",lazyMultiple:!0,name:"include",type:String},{description:"Glob pattern to exclude packages (repeatable, catalog mode)",lazyMultiple:!0,name:"exclude",type:String},{defaultValue:!1,description:"Include prerelease versions (catalog mode)",name:"prerelease",type:Boolean},{defaultValue:!1,description:"Check for known security vulnerabilities (via OSV.dev)",name:"security",type:Boolean},{defaultValue:!1,description:"Skip catalog mode, use package manager directly",name:"no-catalog",type:Boolean},{description:"Output format: table, json, or minimal (default: table)",name:"format",type:String},{defaultValue:!1,description:"Show changelog URLs for updated packages",name:"changelog",type:Boolean},{description:"Run install after catalog update, --no-install to skip (default: true)",name:"install",type:Boolean},{defaultValue:!1,description:"Restore catalog file from the last backup",name:"rollback",type:Boolean},{defaultValue:!1,description:"Run AI analysis on outdated packages before updating (catalog mode)",name:"ai",type:Boolean},{description:"AI analysis type: impact, security, compatibility, or recommend (default: impact)",name:"ai-type",type:String},{defaultValue:!1,description:"Skip typosquat name check for package arguments",name:"no-typosquat-check",type:Boolean}]};var kR=Object.defineProperty,bR=b((e,t)=>kR(e,"name",{value:t,configurable:!0}),"o$1");const $R={argument:{description:"Target version (defaults to latest)",name:"version",type:String},description:"Update vis itself to the latest version",examples:[["vis self-update","Update to latest"],["vis self-update 2.0.0","Install specific version"],["vis self-update --check","Check for updates without installing"]],execute:bR(async({argument:e,logger:t,options:r})=>{const n=e?.[0];t.info("info: checking for updates...");const o=Pn.version;let i;try{const s=zn("npm view @visulima/vis version",{encoding:"utf8"}).trim();i=n??s}catch{throw new Error("Failed to query npm registry. Check your network connection.")}if(o===i&&!r.force){t.info(`
996
- ✓ Already up to date (${o})`);return}if(r.check){o===i?t.info(`✓ Already up to date (${o})`):t.info(`info: found @visulima/vis@${i} (current: ${o})`);return}if(t.info(`info: found @visulima/vis@${i} (current: ${o})`),t.info("info: installing..."),De("npm",["install","-g",`@visulima/vis@${i}`],{encoding:"utf8",stdio:"inherit"}).status!==0)throw new Error("Failed to update. Try running with sudo or fix npm permissions.");t.info(`
997
- ✓ Updated @visulima/vis from ${o} → ${i}`)},"execute"),group:"System",name:"self-update",options:[{defaultValue:!1,description:"Check for updates without installing",name:"check",type:Boolean},{defaultValue:!1,description:"Reinstall even if already current",name:"force",type:Boolean},{defaultValue:!1,description:"Suppress output (CI mode)",name:"silent",type:Boolean}]};var xR=Object.defineProperty,SR=b((e,t)=>xR(e,"name",{value:t,configurable:!0}),"t$2");const CR={alias:"explain",argument:{description:"Package(s) to explain",name:"packages",type:String},description:"Show why a package is installed (dependency chain)",examples:[["vis why react","Show why react is installed"],["vis why react --json","Output as JSON"],["vis why react -r","Check across all workspaces"],["vis explain react","Alias matching npm's command"]],execute:SR(async({argument:e,logger:t,options:r,workspaceRoot:n})=>{const o=e;if(!o||o.length===0)throw new Error("No packages specified. Usage: vis why <package...>");const i=n??process.cwd(),s=Ne(i),a=Cm(s,{depth:r.depth===void 0?void 0:Number(r.depth),dev:r.dev||!1,filter:Yn(r.filter),global:r.global||!1,json:r.json||!1,long:r.long||!1,noOptional:r.noOptional||!1,packages:o,parseable:r.parseable||!1,prod:r.prod||!1,recursive:r.recursive||!1},i,t);a!==0&&a!==1&&(process.exitCode=a)},"execute"),group:"Dependencies",name:"why",options:[{defaultValue:!1,description:"Output as JSON",name:"json",type:Boolean},{defaultValue:!1,description:"Show extended information (pnpm)",name:"long",type:Boolean},{defaultValue:!1,description:"Machine-readable output (pnpm)",name:"parseable",type:Boolean},{alias:"r",defaultValue:!1,description:"Check across all workspaces",name:"recursive",type:Boolean},{alias:"D",defaultValue:!1,description:"Filter to dev dependencies (pnpm)",name:"dev",type:Boolean},{alias:"P",defaultValue:!1,description:"Filter to production dependencies (pnpm)",name:"prod",type:Boolean},{defaultValue:!1,description:"Exclude optional dependencies (pnpm)",name:"no-optional",type:Boolean},{alias:"g",defaultValue:!1,description:"Check globally installed packages (pnpm)",name:"global",type:Boolean},{description:"Limit dependency tree depth",name:"depth",type:Number},{alias:"F",description:"Filter by workspace package name",multiple:!0,name:"filter",type:String}]};var jR=Object.defineProperty,ER=b((e,t)=>jR(e,"name",{value:t,configurable:!0}),"l$2");const TR={beforeCommand:ER(async e=>{try{const t=e.options?.cwd;let r;if(t)r=sf(process.cwd(),t);else{const i=process.env.VIS_MONOREPO_ROOT;r=i&&i.length>0?i:zc(process.cwd()).path}e.workspaceRoot=r;let n=dn(r);try{e.visConfig=await aa(r);const i=e.visConfig?.versionConstraint;if(i&&!Ep(i)){e.logger.error(""),e.logger.error(Ge(Sr("✖ Invalid versionConstraint"))),e.logger.error(` vis.config.ts has versionConstraint ${Sr(JSON.stringify(i))}, which is not a valid semver range.`),e.logger.error(""),process.exitCode=1;return}if(i&&!Tp(Pn.version,i)){e.logger.error(""),e.logger.error(Ge(Sr("✖ vis version too old"))),e.logger.error(` vis.config.ts requires vis ${Sr(i)}, but the current version is ${Sr(Pn.version)}.`),e.logger.error(` ${Re("→")} Upgrade: ${ut("pnpm add -D @visulima/vis@latest")}`),e.logger.error(""),process.exitCode=1;return}}catch(i){const s=n;if(s){const a=i instanceof Error?i.message:String(i);if(e.logger.error(""),e.logger.error(Ge(Sr(`✖ Failed to load ${s}`))),e.logger.error(` ${a}`),e.logger.error(""),a.includes("Cannot find module")){const c=/Cannot find module '([^']+)'/.exec(a)?.[1]??"unknown";e.logger.error(`${Re("→ Hint:")} The module ${Sr(c)} could not be resolved.`),c.includes("@visulima/vis")?(e.logger.error(" This usually means the package isn't installed or the export path changed."),e.logger.error(` Try: ${ut("pnpm add @visulima/vis")}`),e.logger.error(` Or regenerate: ${ut("vis init --force")}`)):e.logger.error(` Try: ${ut(`pnpm add ${c}`)}`)}else a.includes("SyntaxError")||a.includes("Unexpected token")?(e.logger.error(`${Re("→ Hint:")} The config file has a syntax error.`),e.logger.error(" Check your config for typos or invalid syntax."),e.logger.error(` Or regenerate: ${ut("vis init --force")}`)):(e.logger.error(`${Re("→ Hint:")} Delete the broken config and recreate it:`),e.logger.error(` ${ut(`rm ${s} && vis init`)}`));e.logger.error(""),e.logger.error(` Continuing with default settings.
998
- `)}e.visConfig={}}const o=process.argv[2]??"";if(!new Set(["--help","--version","-h","-V","create","help","implode","init"]).has(o)&&!n&&!ft)if(process.stdin.isTTY){const i=gt({input:process.stdin,output:process.stderr}),s=await new Promise(a=>{i.question("\x1B[36;1m?\x1B[0m \x1B[1mNo vis.config.ts found. Create one with best-practice security defaults?\x1B[0m \x1B[90m(\x1B[92mY\x1B[90m/n)\x1B[0m ",a),i.on("SIGINT",()=>{i.close(),a("n")})});if(i.close(),!s.trim()||s.trim().toLowerCase()==="y"||s.trim().toLowerCase()==="yes"){const a=af(r,"vis.config.ts"),c=['import { defineConfig } from "@visulima/vis/config";',"","// Secure defaults are applied automatically by defineConfig().","// You only need to add allowBuilds for packages with build scripts.","// Run 'vis check --security-config' to see all active settings.","export default defineConfig({"," security: {"," allowBuilds: {",' // "esbuild": true,'," },"," },","});",""].join(`
999
- `);me(a,c),e.logger.info(`✓ Created ${a}
1000
- `),e.visConfig=await aa(r),n=a}}else e.logger.warn("No vis.config.ts found. Run 'vis init' to create one with best-practice security defaults.")}catch(t){t instanceof Error&&!t.message.includes("monorepo root")&&e.logger.warn(`Failed to detect workspace: ${t.message}`),e.visConfig={}}},"beforeCommand"),name:"config-loader"};var RR=Object.defineProperty,ge=b((e,t)=>RR(e,"name",{value:t,configurable:!0}),"e");const _c=300*1e3,Ki=v(Qe(),".vis",".tip-state.json"),AR=ge(()=>{try{if(E(Ki))return ue(Ki)}catch{}return{lastGlobal:0,perTip:{}}},"readState"),IR=ge(e=>{try{Se(v(Qe(),".vis")),Z(Ki,JSON.stringify(e))}catch{}},"writeState"),OR=[{cooldownMs:1800*1e3,id:"short-aliases",matches:ge(e=>["install","link","remove","uninstall","update"].includes(e.command),"matches"),message:ge(e=>{const t={install:"i",link:"ln",remove:"rm",uninstall:"rm",update:"up"}[e.command];return t?`You can use 'vis ${t}' as a shorthand for 'vis ${e.command}'`:""},"message"),probability:.5},{id:"use-exec",matches:ge(e=>e.command==="dlx"&&e.success,"matches"),message:ge(()=>"Use 'vis exec' to run locally installed binaries without downloading.","message")},{id:"security-check",matches:ge(e=>(e.command==="check"||e.command==="update")&&e.success&&!e.args.includes("--security"),"matches"),message:ge(()=>"Add --security to check for known vulnerabilities via OSV.dev","message"),probability:.3},{cooldownMs:3600*1e3,id:"ai-analysis",matches:ge(e=>(e.command==="check"||e.command==="update")&&e.success&&!e.args.includes("--ai"),"matches"),message:ge(()=>"Add --ai to run AI analysis on outdated packages before updating.","message"),probability:.2},{cooldownMs:1440*60*1e3,id:"socket-security",matches:ge(e=>(e.command==="install"||e.command==="update"||e.command==="check")&&e.success,"matches"),message:ge(()=>"Enable Socket.dev in vis.config.ts for security scores and supply chain alerts: security.socket.enabled = true","message"),probability:.15},{id:"dedupe-after-install",matches:ge(e=>e.command==="install"&&e.success,"matches"),message:ge(()=>"Run 'vis dedupe' periodically to remove duplicate dependencies.","message"),probability:.15},{cooldownMs:720*60*1e3,id:"doctor-checkup",matches:ge(e=>(e.command==="install"||e.command==="add"||e.command==="update")&&e.success,"matches"),message:ge(()=>"Run 'vis doctor' for a full project health check — outdated, security, duplicates, and optimizations in one view.","message"),probability:.25},{cooldownMs:10080*60*1e3,id:"init-config",matches:ge(e=>(e.command==="install"||e.command==="run")&&e.success&&!e.hasVisConfig,"matches"),message:ge(()=>"Run 'vis init' to create a vis.config.ts with secure defaults — supply chain protection enabled automatically.","message"),probability:.4},{id:"why-command",matches:ge(e=>e.command==="outdated"&&e.success,"matches"),message:ge(()=>"Use 'vis why <package>' to understand why a dependency is installed.","message"),probability:.3},{id:"graph-command",matches:ge(e=>e.command==="run"&&e.success,"matches"),message:ge(()=>"Use 'vis graph' to visualize your project dependency graph.","message"),probability:.1},{id:"affected-command",matches:ge(e=>e.command==="run"&&e.success&&!e.args.includes("--projects"),"matches"),message:ge(()=>"Use 'vis affected <target>' to run tasks only on changed projects.","message"),probability:.2},{id:"pm-cache",matches:ge(e=>e.command==="install"&&e.success,"matches"),message:ge(()=>"Use 'vis pm cache dir' to find your package manager's cache location.","message"),probability:.1},{id:"create-editor",matches:ge(e=>e.command==="create"&&e.success,"matches"),message:ge(()=>"Add --editor vscode to generate VS Code configuration during project creation.","message"),probability:.5},{id:"env-pin",matches:ge(e=>e.command==="env"&&e.args.includes("install")&&e.success,"matches"),message:ge(()=>"Use 'vis env pin <version>' to pin the Node.js version for your project.","message"),probability:.5},{id:"upgrade-check",matches:ge(e=>e.command!=="self-update"&&e.success,"matches"),message:ge(()=>"Run 'vis self-update --check' to see if a newer version of vis is available.","message"),probability:.05}],PR=ge(e=>{if(process.env.VIS_CLI_TEST||ft)return;const t=Date.now(),r=AR();if(t-r.lastGlobal<_c)return;const n=OR.filter(s=>{if(!s.matches(e))return!1;const a=r.perTip[s.id]??0,c=s.cooldownMs??_c;return t-a>=c});if(n.length===0)return;const o=n.find(s=>{const a=s.probability??1;return Math.random()<a});if(!o)return;const i=o.message(e);i&&(process.stderr.write(`
1001
- \x1B[2mtip: ${i}\x1B[0m
1002
- `),r.lastGlobal=t,r.perTip[o.id]=t,IR(r))},"showTip");var NR=Object.defineProperty,Uc=b((e,t)=>NR(e,"name",{value:t,configurable:!0}),"o");const MR=Uc(e=>({afterCommand:Uc(async t=>{const r=process.argv.slice(2),n=r[0]??"";e&&e(),PR({args:r,command:n,hasVisConfig:t.visConfig!==void 0&&Object.keys(t.visConfig).length>0,success:process.exitCode===void 0||process.exitCode===0})},"afterCommand"),name:"post-command"}),"postCommandPlugin");var DR=Object.defineProperty,Xi=b((e,t)=>DR(e,"name",{value:t,configurable:!0}),"f$1");const Wc=new Set(["add","install","update"]),BR=new Set(["add","dedupe","install","remove","update"]),FR=/(\d+\.\d+\.\d+)/,LR=Xi(e=>{const t=v(e,"package.json");if(!E(t))return[];const r=[];try{const n=ue(t),o={...n.dependencies,...n.devDependencies};for(const[i,s]of Object.entries(o)){const a=v(e,"node_modules",i,"package.json");if(E(a))try{const d=ue(a);if(d.version){r.push({name:i,version:d.version});continue}}catch{}const c=FR.exec(s);c?.[1]&&r.push({name:i,version:c[1]})}}catch{}return r},"resolveInstalledPackages"),VR={afterCommand:Xi(async e=>{if(process.exitCode&&process.exitCode!==0)return;const t=e.scriptEnforcement;t?.postInstallPackages.length&&e.workspaceRoot&&Iv(e.workspaceRoot,t.postInstallPackages);const r=process.argv[2]??"",n=Lr(e.visConfig?.security?.socket);if(Wc.has(r)&&n&&e.workspaceRoot)try{const o=LR(e.workspaceRoot);if(o.length>0){const i=await pn(o,n);if(i.size>0){const s=_m(i);if(s){S(""),S(s);let a=0;for(const c of i.values())for(const d of c.alerts)(d.severity==="critical"||d.severity==="high")&&a++;a>0&&se(`${String(a)} critical/high severity alert${a===1?"":"s"} detected. Run 'vis check --security' for details.`)}}}}catch{}},"afterCommand"),beforeCommand:Xi(async e=>{const t=process.argv[2]??"";if(BR.has(t)&&e.visConfig&&e.workspaceRoot){const r=Ne(e.workspaceRoot);if(jv(e.visConfig,r.name),Wc.has(t)){const n=Rv(r.name,e.workspaceRoot,e.visConfig);for(const o of n.warnings)e.logger.warn(`security: ${o}`);e.scriptEnforcement=n}}},"beforeCommand"),name:"security-enforcement"};var _R=Object.defineProperty,fr=b((e,t)=>_R(e,"name",{value:t,configurable:!0}),"s");const Qu=v(Qe(),".vis"),Qi=v(Qu,".upgrade-check.json"),UR=1440*60*1e3,WR=1440*60*1e3,GR=500,HR=new Set(["--help","--version","-h","-V","help","implode","self-update","upgrade"]),zR=fr(()=>{try{if(E(Qi))return ue(Qi)}catch{}},"readCache"),Zu=fr(e=>{try{Se(Qu),Z(Qi,JSON.stringify(e))}catch{}},"writeCache"),qR=fr(async e=>{try{const t=new AbortController,r=setTimeout(()=>{t.abort()},GR),n=await fetch(`https://registry.npmjs.org/${e}/latest`,{headers:{accept:"application/json"},signal:t.signal});return clearTimeout(r),n.ok?(await n.json()).version:void 0}catch{return}},"fetchLatestVersion"),JR=fr((e,t)=>{const r=fr(i=>i.replace(/^v/,"").split("-")[0].split(".").map(Number),"parseSemver"),n=r(e),o=r(t);for(let i=0;i<3;i++){if((o[i]??0)>(n[i]??0))return!0;if((o[i]??0)<(n[i]??0))return!1}return!1},"isNewerVersion"),Gc=fr((e,t)=>{if(!JR(e,t.latestVersion))return;const r=Date.now();r-t.lastNoticeAt<WR||(process.stderr.write(`
1003
- ${re("vis update available:")} ${Il(e)} ${re(ls.arrow)} ${Al(ve(t.latestVersion))}${re(", run")} ${Fe("vis upgrade")}
1004
- `),t.lastNoticeAt=r,Zu(t))},"showUpgradeNotice"),YR=fr(e=>{if(ft||process.env.VIS_CLI_TEST||process.env.VIS_NO_UPDATE_CHECK==="1"||!process.stderr.isTTY||HR.has(e))return!1;const t=new Set(process.argv.slice(2));return!(t.has("--silent")||t.has("-s")||t.has("--json"))},"shouldCheck"),KR=fr((e,t)=>{if(!YR(t))return;const r=zR(),n=Date.now();if(r&&n-r.lastQueryAt<UR)return()=>{Gc(e,r)};let o=r;return qR("@visulima/vis").then(i=>{i&&(o={lastNoticeAt:r?.lastNoticeAt??0,lastQueryAt:n,latestVersion:i},Zu(o))}).catch(()=>{}),()=>{o&&Gc(e,o)}},"startUpgradeCheck");sp();gm();try{const e=zc(process.cwd()).path;process.env.VIS_MONOREPO_ROOT=e;const t=ue(v(e,"package.json"));t.name&&mm(t.name)}catch{}const XR=KR(Pn.version,process.argv[2]??"");ip();const oe=np("vis",{packageName:"vis",packageVersion:Pn.version}),QR=process.argv.includes("--debug")||!!process.env.DEBUG;oe.addPlugin(ap({detailed:QR,exitOnError:!1}));oe.addGlobalOption({description:"Override workspace root directory",name:"cwd",type:String});oe.addPlugin(TR);oe.addPlugin(VR);oe.addCommand(CE);oe.addCommand(Uw);oe.addCommand(Jx);oe.addCommand(om);oe.addCommand(lh);oe.addCommand(nR);oe.addCommand(WS);oe.addCommand(wR);oe.addCommand(Lw);oe.addCommand(py);oe.addCommand(Sv);oe.addCommand(BT);oe.addCommand(WT);oe.addCommand(HT);oe.addCommand(ZT);oe.addCommand(l$);oe.addCommand(lC);oe.addCommand(op);oe.addCommand(oC);oe.addCommand(sh);oe.addCommand(yj);oe.addCommand(Xk);oe.addCommand(CR);oe.addCommand(YS);oe.addCommand(aC);oe.addCommand(sR);oe.addCommand(e$);oe.addCommand(X$);oe.addCommand(gj);oe.addCommand(tC);oe.addCommand(qw);oe.addCommand(Jk);oe.addCommand(Ex);oe.addCommand(Xb);oe.addCommand($R);oe.addCommand(zS);oe.addCommand(Nv);oe.addCommand(zv);oe.addCommand(J$);oe.addCommand(W$);oe.addCommand(cT);oe.addCommand(PT);for(const e of TS)oe.addCommand(e);for(const e of uj)oe.addCommand(e);for(const e of uw)oe.addCommand(e);oe.addPlugin(MR(XR));try{await oe.run()}catch{process.exitCode=process.exitCode||1}
2
+ import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/compile-cache";import"@visulima/cerebro/heap-tuning";import"@visulima/cerebro/plugins/error-handler";import"@visulima/fs";import"@visulima/package";import"@visulima/path";import"./packem_shared/bin-BaZZ32BK.js";