@visulima/vis 1.0.0-alpha.10 → 1.0.0-alpha.11

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 (120) hide show
  1. package/CHANGELOG.md +95 -42
  2. package/LICENSE.md +213 -0
  3. package/README.md +8 -4
  4. package/dist/bin.js +9 -1
  5. package/dist/config/index.d.ts +1818 -0
  6. package/dist/config/index.js +2 -0
  7. package/dist/generate/index.d.ts +1 -1
  8. package/dist/generate/index.js +3 -1
  9. package/dist/packem_chunks/applyDefaults.js +336 -0
  10. package/dist/packem_chunks/bin.js +9554 -64
  11. package/dist/packem_chunks/doctor-probe.js +112 -0
  12. package/dist/packem_chunks/fix.js +229 -48
  13. package/dist/packem_chunks/handler.js +99 -1
  14. package/dist/packem_chunks/handler10.js +53 -1
  15. package/dist/packem_chunks/handler11.js +32 -1
  16. package/dist/packem_chunks/handler12.js +100 -2
  17. package/dist/packem_chunks/handler13.js +25 -1
  18. package/dist/packem_chunks/handler14.js +916 -5
  19. package/dist/packem_chunks/handler15.js +206 -1
  20. package/dist/packem_chunks/handler16.js +122 -18
  21. package/dist/packem_chunks/handler17.js +13 -1
  22. package/dist/packem_chunks/handler18.js +106 -1
  23. package/dist/packem_chunks/handler19.js +19 -1
  24. package/dist/packem_chunks/handler2.js +75 -1
  25. package/dist/packem_chunks/handler20.js +29 -1
  26. package/dist/packem_chunks/handler21.js +222 -1
  27. package/dist/packem_chunks/handler22.js +237 -5
  28. package/dist/packem_chunks/handler23.js +101 -1
  29. package/dist/packem_chunks/handler24.js +110 -1
  30. package/dist/packem_chunks/handler25.js +402 -5
  31. package/dist/packem_chunks/handler26.js +13 -1
  32. package/dist/packem_chunks/handler27.js +63 -3
  33. package/dist/packem_chunks/handler28.js +34 -1
  34. package/dist/packem_chunks/handler29.js +458 -7
  35. package/dist/packem_chunks/handler3.js +95 -2
  36. package/dist/packem_chunks/handler30.js +168 -21
  37. package/dist/packem_chunks/handler31.js +530 -3
  38. package/dist/packem_chunks/handler32.js +214 -2
  39. package/dist/packem_chunks/handler33.js +119 -24
  40. package/dist/packem_chunks/handler34.js +630 -2
  41. package/dist/packem_chunks/handler35.js +283 -19
  42. package/dist/packem_chunks/handler36.js +521 -407
  43. package/dist/packem_chunks/handler37.js +762 -22
  44. package/dist/packem_chunks/handler38.js +989 -22
  45. package/dist/packem_chunks/handler39.js +574 -22
  46. package/dist/packem_chunks/handler4.js +90 -4
  47. package/dist/packem_chunks/handler40.js +1685 -3
  48. package/dist/packem_chunks/handler41.js +1088 -10
  49. package/dist/packem_chunks/handler42.js +785 -141
  50. package/dist/packem_chunks/handler43.js +2658 -42
  51. package/dist/packem_chunks/handler44.js +3886 -3
  52. package/dist/packem_chunks/handler45.js +2568 -21
  53. package/dist/packem_chunks/handler46.js +3769 -0
  54. package/dist/packem_chunks/handler47.js +1491 -0
  55. package/dist/packem_chunks/handler5.js +174 -2
  56. package/dist/packem_chunks/handler6.js +95 -13
  57. package/dist/packem_chunks/handler7.js +115 -8
  58. package/dist/packem_chunks/handler8.js +12 -1
  59. package/dist/packem_chunks/handler9.js +29 -1
  60. package/dist/packem_chunks/heal-accept.js +522 -0
  61. package/dist/packem_chunks/heal.js +673 -0
  62. package/dist/packem_chunks/index.js +873 -7
  63. package/dist/packem_chunks/loader.js +23 -1
  64. package/dist/packem_shared/VisUpdateApp-D-Yz_wvg.js +1316 -0
  65. package/dist/packem_shared/_commonjsHelpers-BqLXS_qQ.js +5 -0
  66. package/dist/packem_shared/ai-analysis-CHeB1joD.js +367 -0
  67. package/dist/packem_shared/ai-cache-Be_jexe4.js +142 -0
  68. package/dist/packem_shared/ai-fix-B9iQVcD2.js +379 -0
  69. package/dist/packem_shared/cache-directory-2qvs4goY.js +98 -0
  70. package/dist/packem_shared/catalog-BJTtyi-O.js +1371 -0
  71. package/dist/packem_shared/dependency-scan-A0KSklpG.js +188 -0
  72. package/dist/packem_shared/docker-2iZzc280.js +181 -0
  73. package/dist/packem_shared/failure-log-Cz3Z4SKL.js +100 -0
  74. package/dist/packem_shared/flakiness-goTxXuCX.js +180 -0
  75. package/dist/packem_shared/otel-DCvqCTz_.js +158 -0
  76. package/dist/packem_shared/otelPlugin-DFaLDvJf.js +3 -0
  77. package/dist/packem_shared/registry-CbqXI0rc.js +272 -0
  78. package/dist/packem_shared/run-summary-utils-PVMl4aIh.js +130 -0
  79. package/dist/packem_shared/runtime-check-Cobi3p6l.js +127 -0
  80. package/dist/packem_shared/selectors-SM69TfqC.js +194 -0
  81. package/dist/packem_shared/symbols-Ta7g2nU-.js +14 -0
  82. package/dist/packem_shared/toolchain-BdZd9eBi.js +975 -0
  83. package/dist/packem_shared/typosquats-C-bCh3PX.js +1210 -0
  84. package/dist/packem_shared/use-measured-height-CNP0vT4M.js +20 -0
  85. package/dist/packem_shared/utils-CthVdBPS.js +40 -0
  86. package/dist/packem_shared/xxh3-Ck8mXNg1.js +239 -0
  87. package/index.js +727 -555
  88. package/package.json +35 -17
  89. package/schemas/project.schema.json +8 -10
  90. package/schemas/vis-config.schema.json +132 -8
  91. package/skills/vis/SKILL.md +96 -0
  92. package/templates/buildkite-ci/.buildkite/pipeline.yml.tera +85 -0
  93. package/templates/buildkite-ci/template.yml +20 -0
  94. package/dist/errors/index.d.ts +0 -26
  95. package/dist/errors/index.js +0 -1
  96. package/dist/packem_chunks/config.js +0 -2
  97. package/dist/packem_shared/VisConfigCycleError-CAYNC7d-.js +0 -1
  98. package/dist/packem_shared/VisConfigError-B5LP1zRf.js +0 -1
  99. package/dist/packem_shared/VisConfigLoadError-CeqBSd2Z.js +0 -2
  100. package/dist/packem_shared/VisConfigNotFoundError-DZ9KC527.js +0 -5
  101. package/dist/packem_shared/VisUpdateApp-D-L4_-Iu.js +0 -1
  102. package/dist/packem_shared/_commonjsHelpers-D6W6KoPK.js +0 -1
  103. package/dist/packem_shared/ai-analysis-CGuy7dfE.js +0 -67
  104. package/dist/packem_shared/ai-cache-Bynt6Y9x.js +0 -1
  105. package/dist/packem_shared/cache-directory-D72ZEag2.js +0 -1
  106. package/dist/packem_shared/catalog-BVPerCwG.js +0 -12
  107. package/dist/packem_shared/dependency-scan-Du0tBu64.js +0 -2
  108. package/dist/packem_shared/docker-BcfqH4Av.js +0 -2
  109. package/dist/packem_shared/failure-log-DqYen0LC.js +0 -2
  110. package/dist/packem_shared/flakiness-DSIHZGBT.js +0 -1
  111. package/dist/packem_shared/run-summary-utils-C24Aaf9E.js +0 -1
  112. package/dist/packem_shared/runtime-check-CGHal8SO.js +0 -1
  113. package/dist/packem_shared/selectors-CfH9ZY08.js +0 -3
  114. package/dist/packem_shared/symbols-CQmER5MT.js +0 -1
  115. package/dist/packem_shared/target-merge-DNa-6eWu.js +0 -1
  116. package/dist/packem_shared/toolchain-DQfTQY8E.js +0 -5
  117. package/dist/packem_shared/typosquats-DOR8izpX.js +0 -1
  118. package/dist/packem_shared/use-measured-height-DjYgUOKk.js +0 -1
  119. package/dist/packem_shared/utils-DrNg0XTR.js +0 -1
  120. package/dist/packem_shared/xxh3-DrAUNq4n.js +0 -1
@@ -1,22 +1,989 @@
1
- var ee=Object.defineProperty;var $=(e,t)=>ee(e,"name",{value:t,configurable:!0});import{createRequire as te}from"node:module";import{isAccessibleSync as y,readFileSync as A,ensureDirSync as G}from"@visulima/fs";import{join as l}from"@visulima/path";import{P as z,X as ae,_ as le,a0 as ce,a1 as fe,a2 as ue,a3 as K,a4 as J,a5 as U,a6 as Y}from"./bin.js";import{readTomlSync as de}from"@visulima/fs/toml";import{parse as pe}from"yaml";const se=te(import.meta.url),F=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,L=$(e=>{if(typeof F<"u"&&F.versions&&F.versions.node){const[t,s]=F.versions.node.split(".").map(Number);if(t>22||t===22&&s>=3||t===20&&s>=16)return F.getBuiltinModule(e)}return se(e)},"__cjs_getBuiltinModule"),{readdirSync:q,statSync:C,writeFileSync:S,unlinkSync:ne,rmSync:re,chmodSync:ie}=L("node:fs"),{cwd:j}=F,{createInterface:oe}=L("node:readline"),{spawnSync:x}=L("node:child_process");var ge=Object.defineProperty,P=$((e,t)=>ge(e,"name",{value:t,configurable:!0}),"c$2");const he=/^# ([^:\s]\S*)(?::\s+(.+))?$/,me=P(e=>{const t=[],s=e.split(`
2
- `);let n;for(const r of s){if(r.startsWith("#!")||r.startsWith("# Generated by")||r.startsWith("# NOTE:")||r==="set -e"||r==="")continue;const o=he.exec(r);if(o){n&&t.push(n),n={command:"",id:o[1]??"",...o[2]?{name:o[2]}:{}};continue}n?n.command=n.command.length>0?`${n.command}
3
- ${r}`:r:n={command:r,id:"(custom)"}}return n&&t.push(n),t},"parseStageScript"),ke=P((e,t)=>{const s=l(e,t),n=[],r=new Set(z);if(y(s))for(const o of q(s)){if(o.startsWith(".")||o==="_"||!r.has(o))continue;const i=l(s,o);if(!C(i).isFile())continue;const a=A(i),u=me(a);n.push({blocks:u,rawLineCount:a.split(`
4
- `).length,stage:o})}return n.sort((o,i)=>o.stage.localeCompare(i.stage)),{hooksDirectory:t,stages:n}},"listHooks"),ye=P(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 s of e.stages)if(t.push("",`${s.stage} (${s.rawLineCount} lines)`),s.blocks.length===0)t.push(" (empty)");else for(const n of s.blocks){const r=n.name?`${n.id} — ${n.name}`:n.id;t.push(` - ${r}`);const o=n.command.split(`
5
- `).find(i=>i.trim()!=="");if(o){const i=o.length>120?`${o.slice(0,117)}...`:o;t.push(` ${i}`)}}return t},"formatListResult"),be=P((e,t)=>{const s=ke(j(),e);for(const n of ye(s))t.info(n)},"runList"),E="prek-runner.mjs",xe={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"]},we=["binary","directory","executable","non-executable","symlink","text"],ve={bash:["bash","shell"],node:["javascript"],nodejs:["javascript"],perl:["perl"],python:["python"],python3:["python","python3"],ruby:["ruby"],sh:["shell"],zsh:["shell","zsh"]},$e=["check-json","check-merge-conflict","end-of-file-fixer","mixed-line-ending","trailing-whitespace"],Ee=[...Object.keys(xe),...Object.values(ve).flat(),...we],Se=["#!/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);",""],_e=Se.join(`
6
- `);var Re=Object.defineProperty,d=$((e,t)=>Re(e,"name",{value:t,configurable:!0}),"a$1");const Fe=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"]]),je=/[<>=!~]=/,Ae=/github\.com[/:]([^/\s]+\/[^/\s.]+)/i,X=`node "$(dirname "$0")/.builtins/${E}"`,Me="# Generated by `vis hook migrate` from prek",v=d(e=>`'${e.replaceAll("'",String.raw`'\''`)}'`,"shellQuote"),B=d(e=>{for(const t of ae)if(y(l(e,t)))return t},"detectPrekConfig"),Oe=d(e=>le[e]??e,"mapPrekStage"),Ie=d(e=>Ae.exec(e)?.[1]??e,"normalizeRepoKey"),De=d(e=>{if(je.test(e))return;if(e.startsWith("@")){const n=e.indexOf("@",1);if(n===-1)return{name:e,version:"latest"};const r=e.slice(n+1).trim();return{name:e.slice(0,n),version:r||"latest"}}const t=e.indexOf("@");if(t===-1)return{name:e,version:"latest"};const s=e.slice(t+1).trim();return{name:e.slice(0,t),version:s||"latest"}},"parseAdditionalDep"),Ne=new Set(Ee),Pe=d(e=>{const t=[];for(const s of[e.types,e.types_or,e.exclude_types])for(const n of s??[])Ne.has(n)||t.push(n);return t},"unknownTypes"),Te=d((e,t)=>(e.stages&&e.stages.length>0?e.stages:t??["pre-commit"]).map(s=>Oe(s)),"resolveStages"),Ce=d(e=>{const t=[];return e.files&&t.push("--files",v(e.files)),e.exclude&&t.push("--exclude",v(e.exclude)),e.types&&e.types.length>0&&t.push("--types",v(e.types.join(","))),e.types_or&&e.types_or.length>0&&t.push("--types-or",v(e.types_or.join(","))),e.exclude_types&&e.exclude_types.length>0&&t.push("--exclude-types",v(e.exclude_types.join(","))),e.always_run&&t.push("--always-run"),e.pass_filenames===!1&&t.push("--no-pass-filenames"),t},"buildRunnerFilterFlags"),H=d((e,t)=>{const s=[X,...Ce(e)];if(t)return s.push("--builtin",t),Array.isArray(e.args)&&e.args.length>0&&s.push("--",...e.args.map(n=>v(n))),s.join(" ");if(s.push("--",e.entry??""),Array.isArray(e.args))for(const n of e.args)s.push(v(n));return s.join(" ")},"buildRunnerInvocation"),We=d((e,t,s)=>{if(e.language==="fail"){const n=e.entry??e.name??e.id??"hook failed";return`echo ${v(n)}; exit 1`}if(s)return H(e,s);if(ce.has(t)){const n=[];if(e.entry&&n.push(e.entry),Array.isArray(e.args))for(const r of e.args)n.push(v(r));return(e.pass_filenames??!0)&&!e.always_run&&n.push('"$@"'),n.join(" ")}return H(e)},"buildHookCommand"),Le=d((e,t,s,n)=>{if(Array.isArray(e.additional_dependencies))for(const r of e.additional_dependencies){const o=De(r);if(!o){n.push(`"${t}": additional_dependency "${r}" uses a pip-style pin and cannot be added to package.json — install manually.`);continue}s.push({hookId:t,name:o.name,raw:r,version:o.version})}},"collectAdditionalDeps"),Be=d(e=>{const t=new Map,s=[],n=[],r=[],o=[];let i=!1;(e.files||e.exclude)&&n.push("top-level files/exclude filter dropped — apply it per hook if needed");for(const u of e.repos??[]){const c=u.repo??"<unknown>",b=c==="local",k=b?void 0:Ie(c);for(const h of u.hooks??[]){const g=h.id??"<unknown>";let M;if(b){const p=h.language??"system";if(!fe.has(p)){s.push({hookId:g,reason:`language "${p}" needs an isolated toolchain — run via prek or reimplement as a system command`,repo:c});continue}if(p!=="fail"&&!h.entry){s.push({hookId:g,reason:"missing `entry`",repo:c});continue}}else if(k&&(M=Fe.get(`${k}#${g}`)),!M){s.push({hookId:g,reason:`remote repo "${c}"@${u.rev??"?"} has no bundled equivalent — run via prek or replace with a system command`,repo:c});continue}Le(h,g,o,r);const O=Pe(h);O.length>0&&n.push(`hook "${g}": unsupported types ${O.join(", ")} — those entries are ignored by the runner`);const I=Te(h,e.default_stages);for(const p of I){if(p==="manual")continue;if(!ue.has(p)){s.push({hookId:g,reason:`unsupported stage "${p}"`,repo:c});continue}let w=We(h,p,M);w.startsWith(X)&&(i=!0),h.verbose&&(w=`(set -x; ${w})`);const D=`${`# ${g}${h.name?`: ${h.name}`:""}`}
7
- ${w}`,f=t.get(p);f?f.push(D):t.set(p,[D])}}}const a=new Map;for(const[u,c]of t){const b=["#!/usr/bin/env sh",Me];e.fail_fast&&b.push("set -e"),b.push("",c.join(`
8
-
9
- `),""),a.set(u,b.join(`
10
- `))}return{additionalDeps:o,droppedFilters:n,manualSteps:r,scripts:a,skippedHooks:s,usesRunner:i}},"convertPrekConfig"),He=d(e=>{const t=pe(e);if(t&&typeof t=="object")return t},"parsePrekConfig"),Ve=d(e=>{if(e.endsWith(".toml")){const s=de(e);return s&&typeof s=="object"?s:void 0}const t=A(e);return He(t)},"loadPrekConfig"),qe=d((e,t)=>{const s=l(e,"package.json"),n=[],r=[];if(!y(s)||t.length===0)return{added:n,skipped:r};const o=A(s),i=JSON.parse(o),a=i.devDependencies??{},u=i.dependencies??{};for(const k of t){if(k.name in a||k.name in u){r.push(k.name);continue}a[k.name]=k.version,n.push(k.name)}if(n.length===0)return{added:n,skipped:r};i.devDependencies=a;const c=/^(\s+)"/m.exec(o),b=c?c[1]:" ";return S(s,`${JSON.stringify(i,void 0,b)}
11
- `,"utf8"),{added:n,skipped:r}},"mergeAdditionalDependencies"),Ge=d((e,t)=>{const s=l(e,t,".builtins");G(s),S(l(s,E),_e,{mode:493}),S(l(s,"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: ${$e.join(", ")}`,""].join(`
12
- `),"utf8")},"writeRunnerAssets"),ze=d((e,t)=>{x("prek",["--version"],{cwd:e,encoding:"utf8"}).status===0?x("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"),Q=d((e,t,s,n={})=>{const r=B(e),o=n.dryRun===!0;if(!r)return{isError:!0,message:"No prek configuration found (.pre-commit-config.yaml, .pre-commit-config.yml, or prek.toml)"};s.info(`Found prek config at ${r}`);const i=l(e,r),a=A(i),u=Ve(i);if(!u)return{isError:!0,message:`Could not parse ${r}`};const{additionalDeps:c,droppedFilters:b,manualSteps:k,scripts:h,skippedHooks:g,usesRunner:M}=Be(u);if(h.size===0&&g.length===0)return{isError:!0,message:`${r} has no hooks to migrate`};if(!o){const f=x("git",["config","--local","core.hooksPath"],{cwd:e,encoding:"utf8"});if(f.status===0){const T=f.stdout?.toString().trim();T&&(T.includes(".prek")||T.includes("prek-hooks"))&&x("git",["config","--local","--unset","core.hooksPath"],{cwd:e})}const _=K(t);if(_.isError)return _;_.message&&s.info(_.message)}const O=l(e,t);o||G(O),M&&(o?s.info(` (would write) ${t}/.builtins/${E}`):(Ge(e,t),s.info(` Wrote ${t}/.builtins/${E}`)));let I=0;for(const[f,_]of h)o?s.info(` (would write) ${t}/${f} (${_.split(`
13
- `).length} lines)`):(S(l(O,f),_,{mode:493}),s.info(` Wrote ${t}/${f}`)),I+=1;const{added:p,skipped:w}=o?{added:c.map(f=>f.name),skipped:[]}:qe(e,c);if(p.length>0){const f=o?"would add":"Added";s.info(`${f} ${p.length} package${p.length===1?"":"s"} to devDependencies: ${p.join(", ")}`),o||s.info("Run your package manager's install (e.g. `pnpm install`) to pick up the new devDependencies.")}w.length>0&&s.info(`Skipped ${w.length} already-declared package${w.length===1?"":"s"}: ${w.join(", ")}`),o||ze(e,s);const D=`${i}.bak`;if(o?s.info(` (would remove) ${r} and back it up to ${r}.bak`):(y(D)||S(D,a,"utf8"),ne(i),s.info(`Removed ${r} (backup at ${r}.bak)`)),g.length>0){s.warn(`Skipped ${g.length} hook${g.length===1?"":"s"} that cannot run without prek:`);for(const f of g)s.warn(` - ${f.repo}::${f.hookId} — ${f.reason}`)}if(b.length>0){s.warn("Partial filter translations:");for(const f of b)s.warn(` - ${f}`)}if(k.length>0){s.warn("Manual follow-up required:");for(const f of k)s.warn(` - ${f}`)}return{isError:!1,message:`${o?"would migrate":"Migration complete:"} ${I} stage script${I===1?"":"s"} ${o?"into":"written to"} ${t}/`}},"migrateFromPrek");var Ke=Object.defineProperty,Z=$((e,t)=>Ke(e,"name",{value:t,configurable:!0}),"a");const Je="pre-commit",Ue=Z((e,t,s,n)=>{const r=s.stage??Je,o=l(e,t,r);if(!y(o))throw new Error(`No script found at ${t}/${r}. Install or migrate hooks first.`);if(s.lastCommit&&(s.fromRef||s.toRef))throw new Error("--last-commit cannot be combined with --from-ref or --to-ref");const i=s.lastCommit?"HEAD~1":s.fromRef,a=s.lastCommit?"HEAD":s.toRef;if(i&&!a)throw new Error("--from-ref requires --to-ref");if(a&&!i)throw new Error("--to-ref requires --from-ref");const u={...process.env};s.allFiles&&(u.VIS_HOOK_ALL_FILES="1"),i&&(u.VIS_HOOK_FROM_REF=i),a&&(u.VIS_HOOK_TO_REF=a),n.info(`Running ${t}/${r}${s.allFiles?" (--all-files)":""}${i?` (${i}..${a})`:""}`);const c=x("sh",["-e",o],{cwd:e,env:u,stdio:"inherit"});if(c.error)throw c.error;return c.status??1},"runHookStage"),Ye=Z((e,t,s)=>{const n=Ue(j(),e,t,s);if(n!==0)throw new Error(`Hook stage exited with code ${n}`)},"runRun");var Xe=Object.defineProperty,Qe=$((e,t)=>Xe(e,"name",{value:t,configurable:!0}),"e");const Ze=Qe((e=J)=>{if(x("git",["config","--local","core.hooksPath"]).status!==0)return{isError:!1,message:"No custom hooks path configured"};const{status:t,stderr:s}=x("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(s)};const n=l(e,"_");return y(n)&&re(n,{force:!0,recursive:!0}),{isError:!1,message:""}},"uninstallHooks");var et=Object.defineProperty,N=$((e,t)=>et(e,"name",{value:t,configurable:!0}),"u");const tt=new Set(z),st=N(e=>{const t=x("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"),nt=N(e=>{const t=x("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"),rt=N((e,t)=>{const s=[],n=l(e,t),r=x("git",["config","--local","core.hooksPath"],{cwd:e,encoding:"utf8"});if(r.status===0){const i=r.stdout.trim(),a=`${t}/_`;i&&i!==a&&s.push({kind:"warning",message:`core.hooksPath is "${i}" — expected "${a}". Re-run \`vis hook install\` to fix.`})}else s.push({kind:"warning",message:"core.hooksPath is not set — run `vis hook install`."});if(y(l(n,"_"))||s.push({kind:"error",message:`Dispatcher directory ${t}/_ is missing. Run \`vis hook install\`.`}),!y(n))return s.push({kind:"error",message:`Hooks directory ${t}/ is missing.`}),{issues:s,ok:!1};let o=!1;for(const i of q(n)){if(i.startsWith(".")||i==="_")continue;if(!tt.has(i)){s.push({kind:"warning",message:`Unknown hook "${i}" — not a standard git hook.`,path:l(t,i)});continue}const a=l(n,i);if(!C(a).isFile())continue;const u=C(a).mode&511;(u&64)===0&&s.push({kind:"warning",message:`Script is not owner-executable (mode ${u.toString(8)}).`,path:l(t,i)});const c=st(a);c&&s.push({kind:"error",message:`Shell syntax error: ${c}`,path:l(t,i)}),A(a).includes(`/.builtins/${E}`)&&(o=!0)}if(o){const i=l(n,".builtins",E);if(y(i)){const a=nt(i);a&&s.push({kind:"error",message:`prek-runner.mjs has a syntax error: ${a}`,path:l(t,".builtins",E)})}else s.push({kind:"error",message:`Hook scripts reference ${t}/.builtins/${E} but the file is missing. Re-run \`vis hook migrate\`.`})}return{issues:s,ok:!s.some(i=>i.kind==="error")}},"validateHooks"),it=N((e,t)=>{if(e.issues.length===0)return[`Hook directory ${t}/ looks good.`];const s=[];for(const n of e.issues){const r=n.kind==="error"?"ERROR":"WARN ",o=n.path?` (${n.path})`:"";s.push(`${r} ${n.message}${o}`)}return s.push("",e.ok?"No errors — warnings only.":`${e.issues.filter(n=>n.kind==="error").length} error(s).`),s},"formatValidationResult"),ot=N((e,t)=>{const s=rt(j(),e),n=it(s,e);for(const r of n)r.startsWith("ERROR")||r.startsWith("WARN")?t.warn(r):t.info(r);if(!s.ok)throw new Error("Hook validation failed")},"runValidate");var at=Object.defineProperty,m=$((e,t)=>at(e,"name",{value:t,configurable:!0}),"i");const R=m(e=>e.hooksDir??J,"resolveHooksDirectory"),V=m(e=>new Promise(t=>{const s=oe({input:process.stdin,output:process.stdout});s.question(`${e} (y/N) `,n=>{s.close();const r=n.trim().toLowerCase();t(r==="y"||r==="yes")})}),"confirmPrompt"),lt=m(async(e,t)=>{const s=j(),n=U(s),r=B(s);if(n&&r)throw new Error(`Found both husky (${n}/) and prek (${r}). Remove or migrate one before running \`vis hook install\`.`);if(n){if(t.info(`Existing husky installation found at ${n}/`),await V("Would you like to migrate your husky hooks to vis?")){const i=Y(s,e,t);if(i.isError)throw new Error(i.message);i.message&&t.info(i.message);return}t.info("Aborting install. Remove husky first or run 'vis hook migrate' to migrate.");return}if(r){if(t.info(`Existing prek configuration found at ${r}`),await V("Would you like to migrate your prek hooks to vis?")){const i=Q(s,e,t);if(i.isError)throw new Error(i.message);i.message&&t.info(i.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 o=K(e);if(o.message){if(o.isError)throw new Error(o.message);t.info(o.message);return}y(l(s,e,"pre-commit"))||S(l(s,e,"pre-commit"),`#!/usr/bin/env sh
14
- `,{mode:493}),t.info("Git hooks installed successfully.")},"executeInstall"),ct=m((e,t,s)=>{const n=j(),r=U(n),o=B(n);if(r&&o)throw new Error(`Found both husky (${r}/) and prek (${o}). Migrate one at a time — rename or remove one before retrying.`);if(!r&&!o)throw new Error("No husky (.husky/) or prek (.pre-commit-config.yaml / prek.toml) configuration found to migrate.");t&&s.info("(dry-run) no files will be written");const i=r?Y(n,e,s,{dryRun:t}):Q(n,e,s,{dryRun:t});if(i.isError)throw new Error(i.message);i.message&&s.info(i.message)},"executeMigrate"),W="# vis:secrets-hook",ft=`#!/usr/bin/env sh
15
- ${W}
16
- # Scan staged files for secrets before each commit. Remove this block or the whole file to disable.
17
- pnpm exec vis secrets --staged --quiet || exit 1
18
- `,ut=m((e,t,s)=>{if(e!=="secrets")throw new Error(`Unknown hook add target "${String(e)}". Currently supported: "secrets".`);const n=j(),r=l(n,t,"pre-commit");if(!y(l(n,t)))throw new Error(`Hooks directory ${t}/ does not exist. Run \`vis hook install\` first.`);if(y(r)){const o=A(r);if(o.includes(W)){s.info(`Secrets hook already present in ${r}.`);return}if(/\bvis secrets\b/.test(o)){s.warn(`Found a \`vis secrets\` invocation in ${r} without the managed marker — leaving it untouched.`);return}const i=`${o.trimEnd()}
19
-
20
- ${W}
21
- pnpm exec vis secrets --staged --quiet || exit 1
22
- `;S(r,i),ie(r,493),s.info(`Appended secrets scan to ${r}.`);return}S(r,ft,{mode:493}),s.info(`Created ${r} with a secrets-scan pre-commit check.`)},"executeAdd"),dt=m((e,t)=>{t.info("Removing git hooks...");const s=Ze(e);if(s.message){if(s.isError)throw new Error(s.message);t.info(s.message);return}t.info("Git hooks removed successfully.")},"executeUninstall"),pt=m(async({logger:e,options:t})=>{await lt(R(t),e)},"hookInstallImpl"),gt=m(({logger:e,options:t})=>{dt(R(t),e)},"hookUninstallImpl"),ht=m(({logger:e,options:t})=>{ct(R(t),!!t.dryRun,e)},"hookMigrateImpl"),mt=m(({logger:e,options:t})=>{be(R(t),e)},"hookListImpl"),kt=m(({logger:e,options:t})=>{ot(R(t),e)},"hookValidateImpl"),yt=m(({argument:e,logger:t,options:s})=>{Ye(R(s),{allFiles:!!s.allFiles,fromRef:s.fromRef,lastCommit:!!s.lastCommit,stage:e[0],toRef:s.toRef},t)},"hookRunImpl"),bt=m(({argument:e,logger:t,options:s})=>{ut(e[0],R(s),t)},"hookAddImpl"),Rt=pt,Ft=gt,jt=ht,At=mt,Mt=kt,Ot=yt,It=bt;export{It as hookAddExecute,Rt as hookInstallExecute,At as hookListExecute,jt as hookMigrateExecute,Ot as hookRunExecute,Ft as hookUninstallExecute,Mt as hookValidateExecute};
1
+ import { createRequire as __cjs_createRequire } from "node:module";
2
+
3
+ const __cjs_require = __cjs_createRequire(import.meta.url);
4
+
5
+ const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
6
+
7
+ const __cjs_getBuiltinModule = (module) => {
8
+ // Check if we're in Node.js and version supports getBuiltinModule
9
+ if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) {
10
+ const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number);
11
+ // Node.js 20.16.0+ and 22.3.0+
12
+ if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) {
13
+ return __cjs_getProcess.getBuiltinModule(module);
14
+ }
15
+ }
16
+ // Fallback to createRequire
17
+ return __cjs_require(module);
18
+ };
19
+
20
+ const {
21
+ writeFileSync
22
+ } = __cjs_getBuiltinModule("node:fs");
23
+ import { bold, cyan, dim } from '@visulima/colorize';
24
+ import { projectGraphToDot } from '@visulima/task-runner';
25
+ import { Box, Text, ScrollView, ScrollBar, useApp, useWindowSize, useInput, Dialog, render } from '@visulima/tui';
26
+ import { _ as QuitDialog, d as discoverWorkspace, b as buildProjectGraph, i as isInCi } from './bin.js';
27
+ import React, { useSyncExternalStore, useState, useRef, useMemo, useCallback, useEffect } from 'react';
28
+ import { jsx, jsxs } from 'react/jsx-runtime';
29
+
30
+ const buildNodes = (projectGraph) => {
31
+ const reverseDeps = /* @__PURE__ */ new Map();
32
+ for (const [source, deps] of Object.entries(projectGraph.dependencies)) {
33
+ for (const dep of deps) {
34
+ const existing = reverseDeps.get(dep.target) ?? [];
35
+ existing.push(source);
36
+ reverseDeps.set(dep.target, existing);
37
+ }
38
+ }
39
+ return Object.values(projectGraph.nodes).map((node) => {
40
+ return {
41
+ deps: projectGraph.dependencies[node.name] ?? [],
42
+ name: node.name,
43
+ reverseDeps: reverseDeps.get(node.name) ?? [],
44
+ type: node.type
45
+ };
46
+ }).sort((a, b) => {
47
+ if (a.type !== b.type) {
48
+ return a.type === "application" ? -1 : 1;
49
+ }
50
+ return a.name.localeCompare(b.name);
51
+ });
52
+ };
53
+ const filterNodes = (allNodes, filterType, filterText) => {
54
+ let filtered = allNodes;
55
+ if (filterType === "app") {
56
+ filtered = filtered.filter((n) => n.type === "application");
57
+ } else if (filterType === "lib") {
58
+ filtered = filtered.filter((n) => n.type !== "application");
59
+ }
60
+ if (filterText) {
61
+ const lower = filterText.toLowerCase();
62
+ filtered = filtered.filter((n) => n.name.toLowerCase().includes(lower));
63
+ }
64
+ return filtered;
65
+ };
66
+ class GraphStore {
67
+ #state;
68
+ #listeners = /* @__PURE__ */ new Set();
69
+ #projectGraph;
70
+ constructor(projectGraph) {
71
+ this.#projectGraph = projectGraph;
72
+ const allNodes = buildNodes(projectGraph);
73
+ this.#state = {
74
+ allNodes,
75
+ filterActive: false,
76
+ filterText: "",
77
+ filterType: "all",
78
+ focusedPanel: "list",
79
+ selectedIndex: 0
80
+ };
81
+ }
82
+ // ── React integration ───────────────────────────────────────────
83
+ getSnapshot = () => this.#state;
84
+ subscribe = (listener) => {
85
+ this.#listeners.add(listener);
86
+ return () => {
87
+ this.#listeners.delete(listener);
88
+ };
89
+ };
90
+ // ── Derived data ────────────────────────────────────────────────
91
+ getFilteredNodes() {
92
+ return filterNodes(this.#state.allNodes, this.#state.filterType, this.#state.filterText);
93
+ }
94
+ getStats() {
95
+ const apps = this.#state.allNodes.filter((n) => n.type === "application").length;
96
+ const total = this.#state.allNodes.length;
97
+ const deps = Object.values(this.#projectGraph.dependencies).reduce((s, d) => s + d.length, 0);
98
+ return { apps, deps, libs: total - apps, total };
99
+ }
100
+ // ── Navigation ──────────────────────────────────────────────────
101
+ setSelectedIndex(index) {
102
+ const filtered = this.getFilteredNodes();
103
+ const clamped = filtered.length === 0 ? -1 : Math.max(0, Math.min(index, filtered.length - 1));
104
+ if (clamped !== this.#state.selectedIndex) {
105
+ this.#emit({ ...this.#state, selectedIndex: clamped });
106
+ }
107
+ }
108
+ setFocusedPanel(panel) {
109
+ if (panel !== this.#state.focusedPanel) {
110
+ this.#emit({ ...this.#state, focusedPanel: panel });
111
+ }
112
+ }
113
+ // ── Filtering ───────────────────────────────────────────────────
114
+ setFilterType(type) {
115
+ if (type !== this.#state.filterType) {
116
+ this.#emit({
117
+ ...this.#state,
118
+ filterType: type,
119
+ selectedIndex: 0
120
+ });
121
+ }
122
+ }
123
+ setFilter(text) {
124
+ this.#emit({
125
+ ...this.#state,
126
+ filterText: text,
127
+ selectedIndex: 0
128
+ });
129
+ }
130
+ setFilterActive(active) {
131
+ if (active !== this.#state.filterActive) {
132
+ this.#emit({
133
+ ...this.#state,
134
+ filterActive: active,
135
+ filterText: active ? this.#state.filterText : "",
136
+ selectedIndex: active ? this.#state.selectedIndex : 0
137
+ });
138
+ }
139
+ }
140
+ // ── Internal ────────────────────────────────────────────────────
141
+ #emit(newState) {
142
+ this.#state = newState;
143
+ for (const listener of this.#listeners) {
144
+ try {
145
+ listener();
146
+ } catch {
147
+ }
148
+ }
149
+ }
150
+ }
151
+
152
+ const ProjectDetailPanel = ({ focused, node, scrollRef }) => {
153
+ const borderColor = focused ? "white" : "gray";
154
+ if (!node) {
155
+ return jsx(Box, { alignItems: "center", borderColor: "gray", borderStyle: "single", flexDirection: "column", flexGrow: 1, justifyContent: "center", children: jsx(Text, { dimColor: true, children: "No project selected" }) });
156
+ }
157
+ const isApp = node.type === "application";
158
+ const typeColor = isApp ? "yellow" : "cyan";
159
+ const typeLabel = isApp ? "Application" : "Library";
160
+ return jsx(
161
+ Box,
162
+ {
163
+ borderColor,
164
+ borderStyle: "single",
165
+ borderTopRightTitle: ` ${typeLabel} `,
166
+ borderTopTitle: ` ${node.name} `,
167
+ flexDirection: "column",
168
+ flexGrow: 1,
169
+ children: jsxs(ScrollView, { flexGrow: 1, flexShrink: 1, paddingX: 2, ref: scrollRef, scrollbar: true, scrollbarColor: "gray", children: [
170
+ jsxs(Box, { flexDirection: "column", marginTop: 1, children: [
171
+ jsxs(Box, { children: [
172
+ jsx(Text, { dimColor: true, children: "── " }),
173
+ jsx(Text, { bold: true, color: "white", children: "DEPENDS ON" }),
174
+ jsxs(Text, { dimColor: true, children: [
175
+ " (",
176
+ node.deps.length,
177
+ ")"
178
+ ] })
179
+ ] }),
180
+ node.deps.length === 0 ? jsx(Box, { marginTop: 1, paddingLeft: 2, children: jsx(Text, { dimColor: true, children: "No dependencies" }) }) : jsx(Box, { flexDirection: "column", marginTop: 1, children: node.deps.map((dep) => jsxs(Box, { gap: 1, paddingLeft: 2, children: [
181
+ jsx(Text, { color: "cyan", children: "→" }),
182
+ jsx(Text, { children: dep.target }),
183
+ dep.type !== "static" && jsxs(Text, { dimColor: true, children: [
184
+ "(",
185
+ dep.type,
186
+ ")"
187
+ ] })
188
+ ] }, dep.target)) })
189
+ ] }),
190
+ jsxs(Box, { flexDirection: "column", marginTop: 1, children: [
191
+ jsxs(Box, { children: [
192
+ jsx(Text, { dimColor: true, children: "── " }),
193
+ jsx(Text, { bold: true, color: "white", children: "REQUIRED BY" }),
194
+ jsxs(Text, { dimColor: true, children: [
195
+ " (",
196
+ node.reverseDeps.length,
197
+ ")"
198
+ ] })
199
+ ] }),
200
+ node.reverseDeps.length === 0 ? jsx(Box, { marginTop: 1, paddingLeft: 2, children: jsx(Text, { dimColor: true, children: "No reverse dependencies" }) }) : jsx(Box, { flexDirection: "column", marginTop: 1, children: node.reverseDeps.map((rdep) => jsxs(Box, { gap: 1, paddingLeft: 2, children: [
201
+ jsx(Text, { color: "magenta", children: "←" }),
202
+ jsx(Text, { children: rdep })
203
+ ] }, rdep)) })
204
+ ] }),
205
+ jsxs(Box, { flexDirection: "column", marginTop: 1, children: [
206
+ jsxs(Box, { children: [
207
+ jsx(Text, { dimColor: true, children: "── " }),
208
+ jsx(Text, { bold: true, color: "white", children: "INFO" })
209
+ ] }),
210
+ jsxs(Box, { flexDirection: "column", marginTop: 1, paddingLeft: 2, children: [
211
+ jsxs(Box, { children: [
212
+ jsx(Box, { width: 16, children: jsx(Text, { dimColor: true, children: "Type:" }) }),
213
+ jsx(Text, { color: typeColor, children: typeLabel })
214
+ ] }),
215
+ jsxs(Box, { children: [
216
+ jsx(Box, { width: 16, children: jsx(Text, { dimColor: true, children: "Dependencies:" }) }),
217
+ jsx(Text, { children: String(node.deps.length) })
218
+ ] }),
219
+ jsxs(Box, { children: [
220
+ jsx(Box, { width: 16, children: jsx(Text, { dimColor: true, children: "Required by:" }) }),
221
+ jsx(Text, { children: String(node.reverseDeps.length) })
222
+ ] }),
223
+ jsxs(Box, { children: [
224
+ jsx(Box, { width: 16, children: jsx(Text, { dimColor: true, children: "Connectivity:" }) }),
225
+ jsx(Text, { children: String(node.deps.length + node.reverseDeps.length) })
226
+ ] })
227
+ ] })
228
+ ] })
229
+ ] })
230
+ }
231
+ );
232
+ };
233
+
234
+ const FILTER_LABELS = [
235
+ { key: "all", label: "All", shortcut: "1" },
236
+ { key: "app", label: "Apps", shortcut: "2" },
237
+ { key: "lib", label: "Libs", shortcut: "3" }
238
+ ];
239
+ const ProjectRow = ({ isSelected, node }) => {
240
+ const isApp = node.type === "application";
241
+ const typeColor = isApp ? "yellow" : "cyan";
242
+ const typeLabel = isApp ? "app" : "lib";
243
+ return jsxs(Box, { flexShrink: 0, height: 1, children: [
244
+ jsxs(Text, { children: [
245
+ isSelected ? "▶" : " ",
246
+ " "
247
+ ] }),
248
+ jsx(Box, { flexGrow: 1, children: jsx(Text, { bold: isSelected, inverse: isSelected, wrap: "truncate", children: node.name }) }),
249
+ jsxs(Text, { color: typeColor, children: [
250
+ " ",
251
+ typeLabel
252
+ ] }),
253
+ jsxs(Text, { dimColor: true, children: [
254
+ " ",
255
+ "→",
256
+ node.deps.length,
257
+ " ",
258
+ "←",
259
+ node.reverseDeps.length
260
+ ] })
261
+ ] });
262
+ };
263
+ const TypeHeader = ({ count, label }) => jsxs(Box, { flexShrink: 0, height: 1, marginTop: 1, children: [
264
+ jsxs(Text, { dimColor: true, children: [
265
+ "▼",
266
+ " "
267
+ ] }),
268
+ jsx(Text, { bold: true, color: "white", children: label.toUpperCase() }),
269
+ jsxs(Text, { dimColor: true, children: [
270
+ " (",
271
+ count,
272
+ ")"
273
+ ] })
274
+ ] });
275
+ const ProjectListPanel = ({
276
+ filterActive,
277
+ filterText,
278
+ filterType,
279
+ focused,
280
+ nodes,
281
+ scrollOffset,
282
+ selectedIndex,
283
+ stats,
284
+ viewportHeight
285
+ }) => {
286
+ const borderColor = focused ? "white" : "gray";
287
+ const apps = nodes.filter((n) => n.type === "application");
288
+ const libs = nodes.filter((n) => n.type !== "application");
289
+ const rows = [];
290
+ let flatIndex = 0;
291
+ if (apps.length > 0) {
292
+ rows.push(jsx(TypeHeader, { count: apps.length, label: "Applications" }, "hdr-apps"));
293
+ for (const node of apps) {
294
+ const currentIndex = flatIndex;
295
+ rows.push(jsx(ProjectRow, { isSelected: currentIndex === selectedIndex, node }, node.name));
296
+ flatIndex++;
297
+ }
298
+ }
299
+ if (libs.length > 0) {
300
+ rows.push(jsx(TypeHeader, { count: libs.length, label: "Libraries" }, "hdr-libs"));
301
+ for (const node of libs) {
302
+ const currentIndex = flatIndex;
303
+ rows.push(jsx(ProjectRow, { isSelected: currentIndex === selectedIndex, node }, node.name));
304
+ flatIndex++;
305
+ }
306
+ }
307
+ let contentHeight = 0;
308
+ if (apps.length > 0) {
309
+ contentHeight += 2 + apps.length;
310
+ }
311
+ if (libs.length > 0) {
312
+ contentHeight += 2 + libs.length;
313
+ }
314
+ const showScrollbar = contentHeight > viewportHeight && viewportHeight > 0;
315
+ return jsxs(Box, { borderColor, borderStyle: "single", flexDirection: "column", flexGrow: 1, children: [
316
+ jsxs(Box, { flexShrink: 0, gap: 1, paddingX: 1, children: [
317
+ jsx(Text, { bold: true, inverse: true, children: " VIS " }),
318
+ jsxs(Text, { wrap: "truncate", children: [
319
+ stats.total,
320
+ " packages"
321
+ ] }),
322
+ jsxs(Text, { dimColor: true, children: [
323
+ "(",
324
+ stats.apps,
325
+ " apps, ",
326
+ stats.libs,
327
+ " libs, ",
328
+ stats.deps,
329
+ " deps)"
330
+ ] })
331
+ ] }),
332
+ jsx(Box, { flexShrink: 0, gap: 1, paddingX: 1, paddingY: 1, children: FILTER_LABELS.map((f) => {
333
+ const isActive = filterType === f.key;
334
+ return jsxs(Box, { children: [
335
+ jsx(Text, { dimColor: !isActive, children: "[" }),
336
+ jsx(Text, { bold: isActive, color: isActive ? "cyan" : "gray", children: f.shortcut }),
337
+ jsx(Text, { dimColor: !isActive, children: "]" }),
338
+ jsxs(Text, { color: isActive ? "white" : "gray", children: [
339
+ " ",
340
+ f.label
341
+ ] })
342
+ ] }, f.key);
343
+ }) }),
344
+ filterActive && jsxs(Box, { flexShrink: 0, paddingX: 1, children: [
345
+ jsx(Text, { bold: true, color: "white", children: "/ " }),
346
+ jsx(Text, { children: filterText }),
347
+ jsx(Text, { inverse: true, children: " " })
348
+ ] }),
349
+ jsxs(Box, { flexDirection: "row", flexGrow: 1, overflow: "hidden", children: [
350
+ jsx(Box, { flexDirection: "column", flexGrow: 1, overflow: "hidden", paddingLeft: 1, children: jsx(Box, { flexDirection: "column", marginTop: -scrollOffset, children: rows }) }),
351
+ showScrollbar && jsx(Box, { flexShrink: 0, marginLeft: 1, marginRight: 1, children: jsx(ScrollBar, { contentHeight, placement: "inset", scrollOffset, style: "block", viewportHeight }) })
352
+ ] })
353
+ ] });
354
+ };
355
+
356
+ const MIN_HORIZONTAL_WIDTH = 100;
357
+ const MIN_VIEWPORT_WIDTH = 40;
358
+ const MIN_VIEWPORT_HEIGHT = 10;
359
+ const FILTER_KEYS = {
360
+ 1: "all",
361
+ 2: "app",
362
+ 3: "lib"
363
+ };
364
+ const VisGraphApp = ({ autoExitSeconds = 0, store }) => {
365
+ const { exit } = useApp();
366
+ const { columns, rows } = useWindowSize();
367
+ const state = useSyncExternalStore(store.subscribe, store.getSnapshot);
368
+ const [helpVisible, setHelpVisible] = useState(false);
369
+ const helpScrollRef = useRef(null);
370
+ const detailScrollRef = useRef(null);
371
+ const [listScrollOffset, setListScrollOffset] = useState(0);
372
+ const [quitDialogVisible, setQuitDialogVisible] = useState(false);
373
+ const filteredNodes = useMemo(() => store.getFilteredNodes(), [state.allNodes, state.filterType, state.filterText]);
374
+ const stats = useMemo(() => store.getStats(), [state.allNodes]);
375
+ const selectedNode = filteredNodes[state.selectedIndex] ?? null;
376
+ const getRowForIndex = useCallback(
377
+ (index) => {
378
+ const apps = filteredNodes.filter((n) => n.type === "application");
379
+ const libs = filteredNodes.filter((n) => n.type !== "application");
380
+ let row = 0;
381
+ let count = 0;
382
+ if (apps.length > 0) {
383
+ row += 2;
384
+ for (let i = 0; i < apps.length; i++) {
385
+ if (count === index) {
386
+ return row;
387
+ }
388
+ row += 1;
389
+ count++;
390
+ }
391
+ }
392
+ if (libs.length > 0) {
393
+ row += 2;
394
+ for (let i = 0; i < libs.length; i++) {
395
+ if (count === index) {
396
+ return row;
397
+ }
398
+ row += 1;
399
+ count++;
400
+ }
401
+ }
402
+ return row;
403
+ },
404
+ [filteredNodes]
405
+ );
406
+ const listViewportHeight = Math.max(1, rows - 8 - (state.filterActive ? 1 : 0));
407
+ const scrollToIndex = useCallback(
408
+ (index) => {
409
+ const targetRow = getRowForIndex(index);
410
+ setListScrollOffset((current) => {
411
+ if (targetRow > current + listViewportHeight - 2) {
412
+ return Math.max(0, targetRow - listViewportHeight + 2);
413
+ }
414
+ if (targetRow < current + 1) {
415
+ return Math.max(0, targetRow - 1);
416
+ }
417
+ return current;
418
+ });
419
+ },
420
+ [getRowForIndex, listViewportHeight]
421
+ );
422
+ useEffect(() => {
423
+ detailScrollRef.current?.scrollToTop();
424
+ }, [selectedNode?.name]);
425
+ useInput(
426
+ (input, key) => {
427
+ if (input === "c" && key.ctrl) {
428
+ exit();
429
+ return;
430
+ }
431
+ if (quitDialogVisible) {
432
+ return;
433
+ }
434
+ if (helpVisible) {
435
+ if (key.escape || input === "?") {
436
+ setHelpVisible(false);
437
+ } else if (input === "q") {
438
+ setHelpVisible(false);
439
+ setQuitDialogVisible(true);
440
+ } else if (key.downArrow || input === "j") {
441
+ helpScrollRef.current?.scrollBy(1);
442
+ } else if (key.upArrow || input === "k") {
443
+ helpScrollRef.current?.scrollBy(-1);
444
+ }
445
+ return;
446
+ }
447
+ if (input === "?") {
448
+ setHelpVisible(true);
449
+ return;
450
+ }
451
+ if (input === "q") {
452
+ setQuitDialogVisible(true);
453
+ return;
454
+ }
455
+ if (key.tab) {
456
+ store.setFocusedPanel(state.focusedPanel === "list" ? "detail" : "list");
457
+ return;
458
+ }
459
+ if (FILTER_KEYS[input]) {
460
+ store.setFilterType(FILTER_KEYS[input]);
461
+ return;
462
+ }
463
+ if (state.filterActive) {
464
+ if (key.escape) {
465
+ store.setFilterActive(false);
466
+ return;
467
+ }
468
+ if (key.return) {
469
+ store.setFilterActive(false);
470
+ return;
471
+ }
472
+ if (key.backspace) {
473
+ store.setFilter(state.filterText.slice(0, -1));
474
+ return;
475
+ }
476
+ if (input && !key.ctrl && !key.meta) {
477
+ store.setFilter(state.filterText + input);
478
+ return;
479
+ }
480
+ return;
481
+ }
482
+ if (state.focusedPanel === "list") {
483
+ if (filteredNodes.length === 0) {
484
+ if (input === "/") {
485
+ store.setFilterActive(true);
486
+ }
487
+ return;
488
+ }
489
+ if (key.downArrow || input === "j") {
490
+ const next = Math.min(state.selectedIndex + 1, filteredNodes.length - 1);
491
+ store.setSelectedIndex(next);
492
+ scrollToIndex(next);
493
+ return;
494
+ }
495
+ if (key.upArrow || input === "k") {
496
+ const next = Math.max(state.selectedIndex - 1, 0);
497
+ store.setSelectedIndex(next);
498
+ scrollToIndex(next);
499
+ return;
500
+ }
501
+ if (key.pageDown) {
502
+ const next = Math.min(state.selectedIndex + 10, filteredNodes.length - 1);
503
+ store.setSelectedIndex(next);
504
+ scrollToIndex(next);
505
+ return;
506
+ }
507
+ if (key.pageUp) {
508
+ const next = Math.max(state.selectedIndex - 10, 0);
509
+ store.setSelectedIndex(next);
510
+ scrollToIndex(next);
511
+ return;
512
+ }
513
+ if (key.home) {
514
+ store.setSelectedIndex(0);
515
+ setListScrollOffset(0);
516
+ return;
517
+ }
518
+ if (key.end) {
519
+ const last = filteredNodes.length - 1;
520
+ store.setSelectedIndex(last);
521
+ scrollToIndex(last);
522
+ return;
523
+ }
524
+ if (input === "/") {
525
+ store.setFilterActive(true);
526
+ return;
527
+ }
528
+ if (key.rightArrow) {
529
+ store.setFocusedPanel("detail");
530
+ return;
531
+ }
532
+ return;
533
+ }
534
+ if (state.focusedPanel === "detail") {
535
+ if (key.escape || key.leftArrow) {
536
+ store.setFocusedPanel("list");
537
+ return;
538
+ }
539
+ if (key.downArrow || input === "j") {
540
+ detailScrollRef.current?.scrollBy(1);
541
+ return;
542
+ }
543
+ if (key.upArrow || input === "k") {
544
+ detailScrollRef.current?.scrollBy(-1);
545
+ return;
546
+ }
547
+ if (key.pageDown) {
548
+ detailScrollRef.current?.scrollBy(10);
549
+ return;
550
+ }
551
+ if (key.pageUp) {
552
+ detailScrollRef.current?.scrollBy(-10);
553
+ return;
554
+ }
555
+ if (key.home) {
556
+ detailScrollRef.current?.scrollToTop();
557
+ return;
558
+ }
559
+ if (key.end) {
560
+ detailScrollRef.current?.scrollToBottom();
561
+ }
562
+ }
563
+ },
564
+ { isActive: true }
565
+ );
566
+ if (columns < MIN_VIEWPORT_WIDTH || rows < MIN_VIEWPORT_HEIGHT) {
567
+ return jsx(Box, { alignItems: "center", height: rows, justifyContent: "center", width: columns, children: jsxs(Text, { color: "yellow", children: [
568
+ "Terminal too small (",
569
+ columns,
570
+ "x",
571
+ rows,
572
+ ")"
573
+ ] }) });
574
+ }
575
+ const isHorizontal = columns >= MIN_HORIZONTAL_WIDTH;
576
+ const footer = jsx(Box, { borderBottom: false, borderColor: "gray", borderLeft: false, borderRight: false, borderStyle: "single", flexShrink: 0, children: jsxs(Box, { flexWrap: "wrap", gap: 2, paddingX: 1, children: [
577
+ jsxs(Box, { gap: 1, children: [
578
+ jsx(Text, { bold: true, color: "white", children: "q" }),
579
+ jsx(Text, { dimColor: true, children: "QUIT" })
580
+ ] }, "q"),
581
+ jsxs(Box, { gap: 1, children: [
582
+ jsx(Text, { bold: true, color: "white", children: "?" }),
583
+ jsx(Text, { dimColor: true, children: "HELP" })
584
+ ] }, "?"),
585
+ jsxs(Box, { gap: 1, children: [
586
+ jsx(Text, { bold: true, color: "white", children: "↑↓" }),
587
+ jsx(Text, { dimColor: true, children: "NAV" })
588
+ ] }, "nav"),
589
+ jsxs(Box, { gap: 1, children: [
590
+ jsx(Text, { bold: true, color: "white", children: "1-3 /" }),
591
+ jsx(Text, { dimColor: true, children: "FILTER" })
592
+ ] }, "f"),
593
+ jsxs(Box, { gap: 1, children: [
594
+ jsx(Text, { bold: true, color: "white", children: "Tab" }),
595
+ jsx(Text, { dimColor: true, children: "PANEL" })
596
+ ] }, "t")
597
+ ] }) });
598
+ const helpPopup = jsxs(
599
+ Dialog,
600
+ {
601
+ footer: jsxs(Text, { dimColor: true, children: [
602
+ jsx(Text, { bold: true, color: "white", children: "↑↓" }),
603
+ " ",
604
+ "scroll",
605
+ " ",
606
+ jsx(Text, { bold: true, color: "white", children: "?" }),
607
+ "/",
608
+ jsx(Text, { bold: true, color: "white", children: "Esc" }),
609
+ " ",
610
+ "close"
611
+ ] }),
612
+ scrollRef: helpScrollRef,
613
+ title: "KEYBOARD SHORTCUTS",
614
+ visible: helpVisible,
615
+ width: 52,
616
+ children: [
617
+ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
618
+ jsxs(Box, { marginBottom: 1, children: [
619
+ jsx(Text, { dimColor: true, children: "── " }),
620
+ jsx(Text, { bold: true, color: "white", children: "NAVIGATION" })
621
+ ] }),
622
+ jsxs(Box, { children: [
623
+ jsx(Box, { width: 24, children: jsxs(Text, { children: [
624
+ jsxs(Text, { bold: true, color: "white", children: [
625
+ " ",
626
+ "↑",
627
+ "/k"
628
+ ] }),
629
+ jsx(Text, { dimColor: true, children: " Move up" })
630
+ ] }) }),
631
+ jsxs(Text, { children: [
632
+ jsxs(Text, { bold: true, color: "white", children: [
633
+ " ",
634
+ "↓",
635
+ "/j"
636
+ ] }),
637
+ jsx(Text, { dimColor: true, children: " Move down" })
638
+ ] })
639
+ ] }),
640
+ jsxs(Text, { children: [
641
+ jsxs(Text, { bold: true, color: "white", children: [
642
+ " ",
643
+ "Tab"
644
+ ] }),
645
+ jsx(Text, { dimColor: true, children: " Switch panel" })
646
+ ] }),
647
+ jsxs(Text, { children: [
648
+ jsxs(Text, { bold: true, color: "white", children: [
649
+ " ",
650
+ "→",
651
+ "/",
652
+ "←"
653
+ ] }),
654
+ jsx(Text, { dimColor: true, children: " Focus detail/list" })
655
+ ] }),
656
+ jsxs(Text, { children: [
657
+ jsxs(Text, { bold: true, color: "white", children: [
658
+ " ",
659
+ "PgUp/PgDn"
660
+ ] }),
661
+ jsx(Text, { dimColor: true, children: " Jump 10 items" })
662
+ ] }),
663
+ jsxs(Text, { children: [
664
+ jsxs(Text, { bold: true, color: "white", children: [
665
+ " ",
666
+ "Home/End"
667
+ ] }),
668
+ jsx(Text, { dimColor: true, children: " Jump to start/end" })
669
+ ] })
670
+ ] }),
671
+ jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [
672
+ jsxs(Box, { marginBottom: 1, children: [
673
+ jsx(Text, { dimColor: true, children: "── " }),
674
+ jsx(Text, { bold: true, color: "white", children: "FILTERS" })
675
+ ] }),
676
+ jsxs(Box, { children: [
677
+ jsx(Box, { width: 24, children: jsxs(Text, { children: [
678
+ jsxs(Text, { bold: true, color: "white", children: [
679
+ " ",
680
+ "1"
681
+ ] }),
682
+ jsx(Text, { dimColor: true, children: " All" })
683
+ ] }) }),
684
+ jsxs(Text, { children: [
685
+ jsxs(Text, { bold: true, color: "white", children: [
686
+ " ",
687
+ "2"
688
+ ] }),
689
+ jsx(Text, { dimColor: true, children: " Apps only" })
690
+ ] })
691
+ ] }),
692
+ jsxs(Text, { children: [
693
+ jsxs(Text, { bold: true, color: "white", children: [
694
+ " ",
695
+ "3"
696
+ ] }),
697
+ jsx(Text, { dimColor: true, children: " Libraries only" })
698
+ ] }),
699
+ jsxs(Text, { children: [
700
+ jsxs(Text, { bold: true, color: "white", children: [
701
+ " ",
702
+ "/"
703
+ ] }),
704
+ jsx(Text, { dimColor: true, children: " Text filter" })
705
+ ] })
706
+ ] }),
707
+ jsxs(Box, { flexDirection: "column", children: [
708
+ jsxs(Box, { marginBottom: 1, children: [
709
+ jsx(Text, { dimColor: true, children: "── " }),
710
+ jsx(Text, { bold: true, color: "white", children: "ACTIONS" })
711
+ ] }),
712
+ jsxs(Text, { children: [
713
+ jsxs(Text, { bold: true, color: "white", children: [
714
+ " ",
715
+ "q"
716
+ ] }),
717
+ jsx(Text, { dimColor: true, children: " Quit" })
718
+ ] }),
719
+ jsxs(Text, { children: [
720
+ jsxs(Text, { bold: true, color: "white", children: [
721
+ " ",
722
+ "?"
723
+ ] }),
724
+ jsx(Text, { dimColor: true, children: " Toggle help" })
725
+ ] })
726
+ ] })
727
+ ]
728
+ }
729
+ );
730
+ const listPanel = jsx(
731
+ ProjectListPanel,
732
+ {
733
+ filterActive: state.filterActive,
734
+ filterText: state.filterText,
735
+ filterType: state.filterType,
736
+ focused: state.focusedPanel === "list",
737
+ nodes: filteredNodes,
738
+ scrollOffset: listScrollOffset,
739
+ selectedIndex: state.selectedIndex,
740
+ stats,
741
+ viewportHeight: listViewportHeight
742
+ }
743
+ );
744
+ const detailPanel = jsx(ProjectDetailPanel, { focused: state.focusedPanel === "detail", node: selectedNode, scrollRef: detailScrollRef });
745
+ if (isHorizontal) {
746
+ const detailWidth = Math.floor(columns * 0.35);
747
+ return jsxs(Box, { flexDirection: "column", height: rows, width: columns, children: [
748
+ jsxs(Box, { flexDirection: "row", flexGrow: 1, children: [
749
+ jsx(Box, { flexGrow: 1, children: listPanel }),
750
+ jsx(Box, { width: detailWidth, children: detailPanel })
751
+ ] }),
752
+ footer,
753
+ jsx(
754
+ QuitDialog,
755
+ {
756
+ autoExitSeconds: autoExitSeconds ?? 3,
757
+ onCancel: () => {
758
+ setQuitDialogVisible(false);
759
+ },
760
+ visible: quitDialogVisible
761
+ }
762
+ ),
763
+ helpPopup
764
+ ] });
765
+ }
766
+ const listHeight = Math.floor(rows * 0.55);
767
+ return jsxs(Box, { flexDirection: "column", height: rows, width: columns, children: [
768
+ jsx(Box, { height: listHeight, children: listPanel }),
769
+ jsx(Box, { flexGrow: 1, children: detailPanel }),
770
+ footer,
771
+ jsx(
772
+ QuitDialog,
773
+ {
774
+ autoExitSeconds: autoExitSeconds ?? 3,
775
+ onCancel: () => {
776
+ setQuitDialogVisible(false);
777
+ },
778
+ visible: quitDialogVisible
779
+ }
780
+ ),
781
+ helpPopup
782
+ ] });
783
+ };
784
+
785
+ var __freeze = Object.freeze;
786
+ var __defProp = Object.defineProperty;
787
+ var __template = (cooked, raw) => __freeze(__defProp(cooked, "raw", { value: __freeze(raw || cooked.slice()) }));
788
+ const printDepsTree = (name, prefix, isLast, nodes, printed, lines, maxDepth, currentDepth) => {
789
+ const connector = isLast ? dim("└── ") : dim("├── ");
790
+ const isDuplicate = printed.has(name);
791
+ const suffix = isDuplicate ? dim(" (*)") : "";
792
+ const node = nodes.get(name);
793
+ const isApp = node?.type === "application";
794
+ const displayName = isApp ? bold(name) : name;
795
+ lines.push(`${prefix}${connector}${displayName}${suffix}`);
796
+ if (isDuplicate) {
797
+ return;
798
+ }
799
+ printed.add(name);
800
+ const deps = node?.deps ?? [];
801
+ const childPrefix = isLast ? `${prefix} ` : `${prefix}${dim("│")} `;
802
+ if (currentDepth >= maxDepth && deps.length > 0) {
803
+ lines.push(`${childPrefix}${dim(`... ${deps.length} more`)}`);
804
+ return;
805
+ }
806
+ for (let i = 0; i < deps.length; i++) {
807
+ const dep = deps[i];
808
+ if (dep) {
809
+ printDepsTree(dep.target, childPrefix, i === deps.length - 1, nodes, printed, lines, maxDepth, currentDepth + 1);
810
+ }
811
+ }
812
+ };
813
+ const printRootProject = (name, nodes, printed, lines, maxDepth, indent) => {
814
+ const node = nodes.get(name);
815
+ const isApp = node?.type === "application";
816
+ const displayName = isApp ? bold(name) : name;
817
+ lines.push(`${indent}${displayName}`);
818
+ printed.add(name);
819
+ const deps = node?.deps ?? [];
820
+ if (deps.length === 0) {
821
+ lines.push(`${indent} ${dim("(no dependencies)")}`);
822
+ return;
823
+ }
824
+ if (maxDepth <= 0) {
825
+ lines.push(`${indent} ${dim(`... ${deps.length} dependencies`)}`);
826
+ return;
827
+ }
828
+ for (let i = 0; i < deps.length; i++) {
829
+ const dep = deps[i];
830
+ if (dep) {
831
+ printDepsTree(dep.target, indent, i === deps.length - 1, nodes, printed, lines, maxDepth, 1);
832
+ }
833
+ }
834
+ };
835
+ const projectGraphToAscii = (projectGraph, maxDepth) => {
836
+ const nodes = /* @__PURE__ */ new Map();
837
+ for (const [name, node] of Object.entries(projectGraph.nodes)) {
838
+ nodes.set(name, {
839
+ deps: (projectGraph.dependencies[name] ?? []).map((d) => {
840
+ return { target: d.target, type: d.type };
841
+ }),
842
+ name,
843
+ type: node.type
844
+ });
845
+ }
846
+ const apps = [];
847
+ const libs = [];
848
+ for (const [name, node] of nodes) {
849
+ if (node.type === "application") {
850
+ apps.push(name);
851
+ } else {
852
+ libs.push(name);
853
+ }
854
+ }
855
+ apps.sort();
856
+ libs.sort();
857
+ const totalPackages = apps.length + libs.length;
858
+ const totalDeps = Object.values(projectGraph.dependencies).reduce((sum, deps) => sum + deps.length, 0);
859
+ const lines = [];
860
+ lines.push(bold("Project Dependency Graph"), "");
861
+ if (apps.length > 0) {
862
+ lines.push(` ${bold(cyan(`Applications (${apps.length})`))}`, "");
863
+ for (const name of apps) {
864
+ const printed = /* @__PURE__ */ new Set();
865
+ printRootProject(name, nodes, printed, lines, maxDepth, " ");
866
+ lines.push("");
867
+ }
868
+ }
869
+ if (libs.length > 0) {
870
+ lines.push(` ${bold(cyan(`Libraries (${libs.length})`))}`, "");
871
+ for (const name of libs) {
872
+ const printed = /* @__PURE__ */ new Set();
873
+ printRootProject(name, nodes, printed, lines, maxDepth, " ");
874
+ lines.push("");
875
+ }
876
+ }
877
+ const width = process.stdout.columns || 80;
878
+ lines.push(dim("─".repeat(Math.min(width, 60))));
879
+ lines.push(
880
+ `${bold(String(totalPackages))} packages ${dim("·")} ${bold(String(totalDeps))} dependencies ${dim("·")} ${bold(String(apps.length))} apps${dim(",")} ${bold(String(libs.length))} libraries`
881
+ );
882
+ const allPrinted = /* @__PURE__ */ new Set();
883
+ let hasDuplicates = false;
884
+ for (const name of [...apps, ...libs]) {
885
+ const deps = nodes.get(name)?.deps ?? [];
886
+ for (const dep of deps) {
887
+ if (allPrinted.has(dep.target)) {
888
+ hasDuplicates = true;
889
+ }
890
+ allPrinted.add(dep.target);
891
+ }
892
+ allPrinted.add(name);
893
+ }
894
+ if (hasDuplicates) {
895
+ lines.push(dim("(*) = already shown above"));
896
+ }
897
+ return lines.join("\n");
898
+ };
899
+ const projectGraphToJson = (projectGraph) => {
900
+ const nodes = Object.values(projectGraph.nodes).map((node) => {
901
+ return {
902
+ name: node.name,
903
+ type: node.type
904
+ };
905
+ });
906
+ const edges = Object.values(projectGraph.dependencies).flat();
907
+ return { edges, nodes };
908
+ };
909
+ var _a;
910
+ const projectGraphToHtml = (projectGraph) => {
911
+ const nodes = Object.values(projectGraph.nodes).map((node) => {
912
+ return {
913
+ name: node.name,
914
+ type: node.type
915
+ };
916
+ });
917
+ const edges = [];
918
+ for (const deps of Object.values(projectGraph.dependencies)) {
919
+ for (const dep of deps) {
920
+ edges.push({ source: dep.source, target: dep.target, type: dep.type });
921
+ }
922
+ }
923
+ const apps = nodes.filter((n) => n.type === "application");
924
+ const libs = nodes.filter((n) => n.type !== "application");
925
+ const graphData = { apps: apps.length, edges, libs: libs.length, nodes };
926
+ return String.raw(_a || (_a = __template(['<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="UTF-8">\n<title>Project Dependency Graph</title>\n<style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #e2e8f0; overflow: hidden; }\n svg { width: 100vw; height: 100vh; }\n .edge { fill: none; marker-end: url(#arrow); }\n .node rect { rx: 8; ry: 8; cursor: pointer; transition: stroke-width 0.15s; }\n .node text { font-size: 12px; font-weight: 600; pointer-events: none; }\n .node:hover rect { stroke-width: 2.5; stroke: #fff; }\n #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); }\n #info b { font-variant-numeric: tabular-nums; }\n .app-count { color: #fbbf24; }\n .lib-count { color: #38bdf8; }\n .dep-count { color: #a78bfa; }\n #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; }\n .legend-dot { width: 12px; height: 12px; border-radius: 3px; display: inline-block; vertical-align: middle; margin-right: 6px; }\n #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; }\n #tooltip h3 { font-size: 14px; margin-bottom: 6px; }\n #tooltip .type-badge { display: inline-block; padding: 1px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; margin-left: 8px; }\n #tooltip .dep-section { margin-top: 8px; color: #94a3b8; }\n #tooltip ul { list-style: none; padding-left: 0; margin-top: 4px; }\n #tooltip li { padding: 1px 0; color: #cbd5e1; }\n #tooltip li::before { content: "92 "; color: #64748b; }\n</style>\n</head>\n<body>\n<div id="info">\n <b class="app-count">', '</b> apps &middot;\n <b class="lib-count">', '</b> libraries &middot;\n <b class="dep-count">', '</b> dependencies\n</div>\n<div id="legend">\n <span><span class="legend-dot" style="background:#fbbf24"></span>Application</span>\n <span><span class="legend-dot" style="background:#38bdf8"></span>Library</span>\n <span style="color:#64748b">&mdash; solid = static &nbsp; - - - = implicit</span>\n</div>\n<div id="tooltip"></div>\n<svg id="graph">\n <defs>\n <marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto">\n <path d="M 0 0 L 10 5 L 0 10 z" fill="#64748b"/>\n </marker>\n </defs>\n</svg>\n<script>\nconst data = ', ";\nconst svg = document.getElementById('graph');\nconst tooltip = document.getElementById('tooltip');\nconst W = window.innerWidth, H = window.innerHeight;\n\n// Build adjacency\nconst depMap = {}, rdepMap = {};\ndata.nodes.forEach(n => { depMap[n.name] = []; rdepMap[n.name] = []; });\ndata.edges.forEach(e => { depMap[e.source]?.push(e.target); rdepMap[e.target]?.push(e.source); });\n\n// Escape text for safe DOM insertion\nfunction esc(s) { const d = document.createElement('div'); d.textContent = s; return d.textContent; }\n\n// Force-directed layout\nconst repulsion = 5000 + data.nodes.length * 150;\nconst nodes = data.nodes.map(n => ({\n ...n, x: W/2 + (Math.random()-0.5)*Math.min(W*0.6, 600),\n y: H/2 + (Math.random()-0.5)*Math.min(H*0.6, 400), vx: 0, vy: 0\n}));\nconst nodeMap = new Map(nodes.map(n => [n.name, n]));\nconst edges = data.edges.map(e => ({\n source: nodeMap.get(e.source), target: nodeMap.get(e.target), type: e.type\n}));\n\nfor (let iter = 0; iter < 400; iter++) {\n for (let i = 0; i < nodes.length; i++) {\n for (let j = i+1; j < nodes.length; j++) {\n let dx = nodes[j].x - nodes[i].x, dy = nodes[j].y - nodes[i].y;\n let d = Math.sqrt(dx*dx + dy*dy) || 1;\n let f = repulsion / (d * d);\n nodes[i].vx -= dx/d * f; nodes[i].vy -= dy/d * f;\n nodes[j].vx += dx/d * f; nodes[j].vy += dy/d * f;\n }\n }\n edges.forEach(e => {\n if (!e.source || !e.target) {\n return;\n }\n let dx = e.target.x - e.source.x, dy = e.target.y - e.source.y;\n let d = Math.sqrt(dx*dx + dy*dy) || 1;\n let f = (d - 180) * 0.008;\n e.source.vx += dx/d * f; e.source.vy += dy/d * f;\n e.target.vx -= dx/d * f; e.target.vy -= dy/d * f;\n });\n nodes.forEach(n => {\n n.vx += (W/2 - n.x) * 0.001; n.vy += (H/2 - n.y) * 0.001;\n n.x += n.vx * 0.3; n.y += n.vy * 0.3;\n n.vx *= 0.75; n.vy *= 0.75;\n n.x = Math.max(80, Math.min(W-80, n.x));\n n.y = Math.max(40, Math.min(H-40, n.y));\n });\n}\n\n// Measure text widths\nconst measure = document.createElementNS('http://www.w3.org/2000/svg','text');\nmeasure.setAttribute('font-size','12'); measure.setAttribute('font-weight','600');\nmeasure.setAttribute('font-family','system-ui');\nsvg.appendChild(measure);\nconst widths = {};\nnodes.forEach(n => { measure.textContent = n.name; widths[n.name] = measure.getComputedTextLength(); });\nsvg.removeChild(measure);\n\n// Render edges\nedges.forEach(e => {\n if (!e.source || !e.target) {\n return;\n }\n const sw = (widths[e.source.name]||80)/2 + 12;\n const tw = (widths[e.target.name]||80)/2 + 12;\n const dx = e.target.x - e.source.x, dy = e.target.y - e.source.y;\n const d = Math.sqrt(dx*dx+dy*dy)||1;\n const x1 = e.source.x + dx/d*sw, y1 = e.source.y + dy/d*14;\n const x2 = e.target.x - dx/d*tw, y2 = e.target.y - dy/d*14;\n const line = document.createElementNS('http://www.w3.org/2000/svg','line');\n line.setAttribute('x1',x1); line.setAttribute('y1',y1);\n line.setAttribute('x2',x2); line.setAttribute('y2',y2);\n line.setAttribute('class','edge');\n const edgeColors = { implicit: '#475569', devDependency: '#888888', peerDependency: '#CC8800' };\n line.setAttribute('stroke', edgeColors[e.type] || '#64748b');\n line.setAttribute('stroke-width', '1.5');\n if (e.type === 'implicit' || e.type === 'peerDependency') {\n line.setAttribute('stroke-dasharray', '6,4');\n }\n if (e.type === 'devDependency') {\n line.setAttribute('stroke-dasharray', '3,3');\n }\n svg.appendChild(line);\n});\n\n// Render nodes\nnodes.forEach(n => {\n const w = (widths[n.name]||80) + 24;\n const h = 32;\n const isApp = n.type === 'application';\n const fill = isApp ? '#fbbf24' : '#38bdf8';\n const textFill = '#0f172a';\n const stroke = isApp ? '#f59e0b' : '#0284c7';\n\n const g = document.createElementNS('http://www.w3.org/2000/svg','g');\n g.setAttribute('class','node');\n g.setAttribute('transform','translate('+(n.x - w/2)+','+(n.y - h/2)+')');\n const rect = document.createElementNS('http://www.w3.org/2000/svg','rect');\n rect.setAttribute('width', w); rect.setAttribute('height', h);\n rect.setAttribute('fill', fill); rect.setAttribute('stroke', stroke); rect.setAttribute('stroke-width','1.5');\n g.appendChild(rect);\n const text = document.createElementNS('http://www.w3.org/2000/svg','text');\n text.setAttribute('x', w/2); text.setAttribute('y', h/2 + 4.5);\n text.setAttribute('text-anchor','middle'); text.setAttribute('fill', textFill);\n text.textContent = n.name;\n g.appendChild(text);\n\n g.addEventListener('mouseenter', (ev) => {\n const deps = depMap[n.name] || [];\n const rdeps = rdepMap[n.name] || [];\n\n // Build tooltip using safe DOM methods\n tooltip.textContent = '';\n\n const heading = document.createElement('h3');\n heading.textContent = n.name;\n const badge = document.createElement('span');\n badge.className = 'type-badge';\n badge.style.background = fill;\n badge.style.color = '#0f172a';\n badge.textContent = n.type;\n heading.appendChild(badge);\n tooltip.appendChild(heading);\n\n if (deps.length) {\n const label = document.createElement('div');\n label.className = 'dep-section';\n label.textContent = 'Depends on:';\n tooltip.appendChild(label);\n const ul = document.createElement('ul');\n deps.forEach(d => { const li = document.createElement('li'); li.textContent = d; ul.appendChild(li); });\n tooltip.appendChild(ul);\n }\n if (rdeps.length) {\n const label = document.createElement('div');\n label.className = 'dep-section';\n label.textContent = 'Required by:';\n tooltip.appendChild(label);\n const ul = document.createElement('ul');\n rdeps.forEach(d => { const li = document.createElement('li'); li.textContent = d; ul.appendChild(li); });\n tooltip.appendChild(ul);\n }\n if (!deps.length && !rdeps.length) {\n const empty = document.createElement('div');\n empty.style.marginTop = '6px';\n empty.style.color = '#64748b';\n empty.textContent = 'No dependencies';\n tooltip.appendChild(empty);\n }\n\n tooltip.style.display = 'block';\n const rect = tooltip.getBoundingClientRect();\n tooltip.style.left = Math.min(ev.clientX + 12, W - rect.width - 12) + 'px';\n tooltip.style.top = Math.min(ev.clientY + 12, H - rect.height - 12) + 'px';\n });\n g.addEventListener('mouseleave', () => { tooltip.style.display = 'none'; });\n svg.appendChild(g);\n});\n<\/script>\n</body>\n</html>"], ['<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="UTF-8">\n<title>Project Dependency Graph</title>\n<style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n body { font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #e2e8f0; overflow: hidden; }\n svg { width: 100vw; height: 100vh; }\n .edge { fill: none; marker-end: url(#arrow); }\n .node rect { rx: 8; ry: 8; cursor: pointer; transition: stroke-width 0.15s; }\n .node text { font-size: 12px; font-weight: 600; pointer-events: none; }\n .node:hover rect { stroke-width: 2.5; stroke: #fff; }\n #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); }\n #info b { font-variant-numeric: tabular-nums; }\n .app-count { color: #fbbf24; }\n .lib-count { color: #38bdf8; }\n .dep-count { color: #a78bfa; }\n #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; }\n .legend-dot { width: 12px; height: 12px; border-radius: 3px; display: inline-block; vertical-align: middle; margin-right: 6px; }\n #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; }\n #tooltip h3 { font-size: 14px; margin-bottom: 6px; }\n #tooltip .type-badge { display: inline-block; padding: 1px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; margin-left: 8px; }\n #tooltip .dep-section { margin-top: 8px; color: #94a3b8; }\n #tooltip ul { list-style: none; padding-left: 0; margin-top: 4px; }\n #tooltip li { padding: 1px 0; color: #cbd5e1; }\n #tooltip li::before { content: "\\2192 "; color: #64748b; }\n</style>\n</head>\n<body>\n<div id="info">\n <b class="app-count">', '</b> apps &middot;\n <b class="lib-count">', '</b> libraries &middot;\n <b class="dep-count">', '</b> dependencies\n</div>\n<div id="legend">\n <span><span class="legend-dot" style="background:#fbbf24"></span>Application</span>\n <span><span class="legend-dot" style="background:#38bdf8"></span>Library</span>\n <span style="color:#64748b">&mdash; solid = static &nbsp; - - - = implicit</span>\n</div>\n<div id="tooltip"></div>\n<svg id="graph">\n <defs>\n <marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto">\n <path d="M 0 0 L 10 5 L 0 10 z" fill="#64748b"/>\n </marker>\n </defs>\n</svg>\n<script>\nconst data = ', ";\nconst svg = document.getElementById('graph');\nconst tooltip = document.getElementById('tooltip');\nconst W = window.innerWidth, H = window.innerHeight;\n\n// Build adjacency\nconst depMap = {}, rdepMap = {};\ndata.nodes.forEach(n => { depMap[n.name] = []; rdepMap[n.name] = []; });\ndata.edges.forEach(e => { depMap[e.source]?.push(e.target); rdepMap[e.target]?.push(e.source); });\n\n// Escape text for safe DOM insertion\nfunction esc(s) { const d = document.createElement('div'); d.textContent = s; return d.textContent; }\n\n// Force-directed layout\nconst repulsion = 5000 + data.nodes.length * 150;\nconst nodes = data.nodes.map(n => ({\n ...n, x: W/2 + (Math.random()-0.5)*Math.min(W*0.6, 600),\n y: H/2 + (Math.random()-0.5)*Math.min(H*0.6, 400), vx: 0, vy: 0\n}));\nconst nodeMap = new Map(nodes.map(n => [n.name, n]));\nconst edges = data.edges.map(e => ({\n source: nodeMap.get(e.source), target: nodeMap.get(e.target), type: e.type\n}));\n\nfor (let iter = 0; iter < 400; iter++) {\n for (let i = 0; i < nodes.length; i++) {\n for (let j = i+1; j < nodes.length; j++) {\n let dx = nodes[j].x - nodes[i].x, dy = nodes[j].y - nodes[i].y;\n let d = Math.sqrt(dx*dx + dy*dy) || 1;\n let f = repulsion / (d * d);\n nodes[i].vx -= dx/d * f; nodes[i].vy -= dy/d * f;\n nodes[j].vx += dx/d * f; nodes[j].vy += dy/d * f;\n }\n }\n edges.forEach(e => {\n if (!e.source || !e.target) {\n return;\n }\n let dx = e.target.x - e.source.x, dy = e.target.y - e.source.y;\n let d = Math.sqrt(dx*dx + dy*dy) || 1;\n let f = (d - 180) * 0.008;\n e.source.vx += dx/d * f; e.source.vy += dy/d * f;\n e.target.vx -= dx/d * f; e.target.vy -= dy/d * f;\n });\n nodes.forEach(n => {\n n.vx += (W/2 - n.x) * 0.001; n.vy += (H/2 - n.y) * 0.001;\n n.x += n.vx * 0.3; n.y += n.vy * 0.3;\n n.vx *= 0.75; n.vy *= 0.75;\n n.x = Math.max(80, Math.min(W-80, n.x));\n n.y = Math.max(40, Math.min(H-40, n.y));\n });\n}\n\n// Measure text widths\nconst measure = document.createElementNS('http://www.w3.org/2000/svg','text');\nmeasure.setAttribute('font-size','12'); measure.setAttribute('font-weight','600');\nmeasure.setAttribute('font-family','system-ui');\nsvg.appendChild(measure);\nconst widths = {};\nnodes.forEach(n => { measure.textContent = n.name; widths[n.name] = measure.getComputedTextLength(); });\nsvg.removeChild(measure);\n\n// Render edges\nedges.forEach(e => {\n if (!e.source || !e.target) {\n return;\n }\n const sw = (widths[e.source.name]||80)/2 + 12;\n const tw = (widths[e.target.name]||80)/2 + 12;\n const dx = e.target.x - e.source.x, dy = e.target.y - e.source.y;\n const d = Math.sqrt(dx*dx+dy*dy)||1;\n const x1 = e.source.x + dx/d*sw, y1 = e.source.y + dy/d*14;\n const x2 = e.target.x - dx/d*tw, y2 = e.target.y - dy/d*14;\n const line = document.createElementNS('http://www.w3.org/2000/svg','line');\n line.setAttribute('x1',x1); line.setAttribute('y1',y1);\n line.setAttribute('x2',x2); line.setAttribute('y2',y2);\n line.setAttribute('class','edge');\n const edgeColors = { implicit: '#475569', devDependency: '#888888', peerDependency: '#CC8800' };\n line.setAttribute('stroke', edgeColors[e.type] || '#64748b');\n line.setAttribute('stroke-width', '1.5');\n if (e.type === 'implicit' || e.type === 'peerDependency') {\n line.setAttribute('stroke-dasharray', '6,4');\n }\n if (e.type === 'devDependency') {\n line.setAttribute('stroke-dasharray', '3,3');\n }\n svg.appendChild(line);\n});\n\n// Render nodes\nnodes.forEach(n => {\n const w = (widths[n.name]||80) + 24;\n const h = 32;\n const isApp = n.type === 'application';\n const fill = isApp ? '#fbbf24' : '#38bdf8';\n const textFill = '#0f172a';\n const stroke = isApp ? '#f59e0b' : '#0284c7';\n\n const g = document.createElementNS('http://www.w3.org/2000/svg','g');\n g.setAttribute('class','node');\n g.setAttribute('transform','translate('+(n.x - w/2)+','+(n.y - h/2)+')');\n const rect = document.createElementNS('http://www.w3.org/2000/svg','rect');\n rect.setAttribute('width', w); rect.setAttribute('height', h);\n rect.setAttribute('fill', fill); rect.setAttribute('stroke', stroke); rect.setAttribute('stroke-width','1.5');\n g.appendChild(rect);\n const text = document.createElementNS('http://www.w3.org/2000/svg','text');\n text.setAttribute('x', w/2); text.setAttribute('y', h/2 + 4.5);\n text.setAttribute('text-anchor','middle'); text.setAttribute('fill', textFill);\n text.textContent = n.name;\n g.appendChild(text);\n\n g.addEventListener('mouseenter', (ev) => {\n const deps = depMap[n.name] || [];\n const rdeps = rdepMap[n.name] || [];\n\n // Build tooltip using safe DOM methods\n tooltip.textContent = '';\n\n const heading = document.createElement('h3');\n heading.textContent = n.name;\n const badge = document.createElement('span');\n badge.className = 'type-badge';\n badge.style.background = fill;\n badge.style.color = '#0f172a';\n badge.textContent = n.type;\n heading.appendChild(badge);\n tooltip.appendChild(heading);\n\n if (deps.length) {\n const label = document.createElement('div');\n label.className = 'dep-section';\n label.textContent = 'Depends on:';\n tooltip.appendChild(label);\n const ul = document.createElement('ul');\n deps.forEach(d => { const li = document.createElement('li'); li.textContent = d; ul.appendChild(li); });\n tooltip.appendChild(ul);\n }\n if (rdeps.length) {\n const label = document.createElement('div');\n label.className = 'dep-section';\n label.textContent = 'Required by:';\n tooltip.appendChild(label);\n const ul = document.createElement('ul');\n rdeps.forEach(d => { const li = document.createElement('li'); li.textContent = d; ul.appendChild(li); });\n tooltip.appendChild(ul);\n }\n if (!deps.length && !rdeps.length) {\n const empty = document.createElement('div');\n empty.style.marginTop = '6px';\n empty.style.color = '#64748b';\n empty.textContent = 'No dependencies';\n tooltip.appendChild(empty);\n }\n\n tooltip.style.display = 'block';\n const rect = tooltip.getBoundingClientRect();\n tooltip.style.left = Math.min(ev.clientX + 12, W - rect.width - 12) + 'px';\n tooltip.style.top = Math.min(ev.clientY + 12, H - rect.height - 12) + 'px';\n });\n g.addEventListener('mouseleave', () => { tooltip.style.display = 'none'; });\n svg.appendChild(g);\n});\n<\/script>\n</body>\n</html>"])), graphData.apps, graphData.libs, graphData.edges.length, JSON.stringify(graphData).replaceAll("</", String.raw`<\/`));
927
+ };
928
+ const execute = async ({ logger, options, visConfig, workspaceRoot: wsRoot }) => {
929
+ if (!wsRoot) {
930
+ throw new Error("Could not determine workspace root. Run this command inside a monorepo.");
931
+ }
932
+ const workspaceRoot = wsRoot;
933
+ const { packageJsons, workspace } = discoverWorkspace(workspaceRoot, visConfig);
934
+ const projectGraph = buildProjectGraph(workspaceRoot, workspace, packageJsons);
935
+ const isTTY = Boolean(process.stdout.isTTY) && !isInCi;
936
+ const format = options.format ?? (isTTY ? "tui" : "ascii");
937
+ const outputFile = options.output;
938
+ const maxDepth = options.depth ?? Infinity;
939
+ let output;
940
+ switch (format) {
941
+ case "dot": {
942
+ output = projectGraphToDot(projectGraph);
943
+ break;
944
+ }
945
+ case "html": {
946
+ output = projectGraphToHtml(projectGraph);
947
+ break;
948
+ }
949
+ case "json": {
950
+ output = JSON.stringify(projectGraphToJson(projectGraph), void 0, 2);
951
+ break;
952
+ }
953
+ case "tui": {
954
+ if (!isTTY) {
955
+ output = projectGraphToAscii(projectGraph, maxDepth);
956
+ break;
957
+ }
958
+ const autoExitSeconds = visConfig?.tui?.autoExit === true ? 3 : typeof visConfig?.tui?.autoExit === "number" ? visConfig.tui.autoExit : 0;
959
+ if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {
960
+ process.stdin.setRawMode(true);
961
+ process.stdin.ref();
962
+ process.stdin.resume();
963
+ }
964
+ const keepAlive = setInterval(() => {
965
+ }, 1e3);
966
+ const store = new GraphStore(projectGraph);
967
+ const instance = render(React.createElement(VisGraphApp, { autoExitSeconds, store }), {
968
+ alternateScreen: true,
969
+ exitOnCtrlC: false,
970
+ interactive: true,
971
+ patchConsole: true
972
+ });
973
+ await instance.waitUntilExit();
974
+ clearInterval(keepAlive);
975
+ return;
976
+ }
977
+ default: {
978
+ output = projectGraphToAscii(projectGraph, maxDepth);
979
+ }
980
+ }
981
+ if (outputFile) {
982
+ writeFileSync(outputFile, output, "utf8");
983
+ logger.info(`Graph written to ${outputFile}`);
984
+ } else {
985
+ logger.info(output);
986
+ }
987
+ };
988
+
989
+ export { execute as default };