@visulima/vis 0.0.1 → 1.0.0-alpha.10

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 (86) hide show
  1. package/CHANGELOG.md +360 -0
  2. package/LICENSE.md +91 -0
  3. package/README.md +364 -29
  4. package/dist/bin.js +2 -0
  5. package/dist/errors/index.d.ts +26 -0
  6. package/dist/errors/index.js +1 -0
  7. package/dist/generate/index.d.ts +157 -0
  8. package/dist/generate/index.js +1 -0
  9. package/dist/packem_chunks/bin.js +87 -0
  10. package/dist/packem_chunks/config.js +2 -0
  11. package/dist/packem_chunks/fix.js +53 -0
  12. package/dist/packem_chunks/handler.js +1 -0
  13. package/dist/packem_chunks/handler10.js +1 -0
  14. package/dist/packem_chunks/handler11.js +1 -0
  15. package/dist/packem_chunks/handler12.js +2 -0
  16. package/dist/packem_chunks/handler13.js +1 -0
  17. package/dist/packem_chunks/handler14.js +5 -0
  18. package/dist/packem_chunks/handler15.js +1 -0
  19. package/dist/packem_chunks/handler16.js +20 -0
  20. package/dist/packem_chunks/handler17.js +1 -0
  21. package/dist/packem_chunks/handler18.js +1 -0
  22. package/dist/packem_chunks/handler19.js +1 -0
  23. package/dist/packem_chunks/handler2.js +1 -0
  24. package/dist/packem_chunks/handler20.js +1 -0
  25. package/dist/packem_chunks/handler21.js +1 -0
  26. package/dist/packem_chunks/handler22.js +5 -0
  27. package/dist/packem_chunks/handler23.js +1 -0
  28. package/dist/packem_chunks/handler24.js +1 -0
  29. package/dist/packem_chunks/handler25.js +5 -0
  30. package/dist/packem_chunks/handler26.js +1 -0
  31. package/dist/packem_chunks/handler27.js +3 -0
  32. package/dist/packem_chunks/handler28.js +1 -0
  33. package/dist/packem_chunks/handler29.js +7 -0
  34. package/dist/packem_chunks/handler3.js +2 -0
  35. package/dist/packem_chunks/handler30.js +23 -0
  36. package/dist/packem_chunks/handler31.js +3 -0
  37. package/dist/packem_chunks/handler32.js +2 -0
  38. package/dist/packem_chunks/handler33.js +24 -0
  39. package/dist/packem_chunks/handler34.js +2 -0
  40. package/dist/packem_chunks/handler35.js +19 -0
  41. package/dist/packem_chunks/handler36.js +428 -0
  42. package/dist/packem_chunks/handler37.js +22 -0
  43. package/dist/packem_chunks/handler38.js +22 -0
  44. package/dist/packem_chunks/handler39.js +22 -0
  45. package/dist/packem_chunks/handler4.js +4 -0
  46. package/dist/packem_chunks/handler40.js +3 -0
  47. package/dist/packem_chunks/handler41.js +10 -0
  48. package/dist/packem_chunks/handler42.js +153 -0
  49. package/dist/packem_chunks/handler43.js +42 -0
  50. package/dist/packem_chunks/handler44.js +3 -0
  51. package/dist/packem_chunks/handler45.js +27 -0
  52. package/dist/packem_chunks/handler5.js +2 -0
  53. package/dist/packem_chunks/handler6.js +13 -0
  54. package/dist/packem_chunks/handler7.js +8 -0
  55. package/dist/packem_chunks/handler8.js +1 -0
  56. package/dist/packem_chunks/handler9.js +1 -0
  57. package/dist/packem_chunks/index.js +7 -0
  58. package/dist/packem_chunks/loader.js +1 -0
  59. package/dist/packem_shared/VisConfigCycleError-CAYNC7d-.js +1 -0
  60. package/dist/packem_shared/VisConfigError-B5LP1zRf.js +1 -0
  61. package/dist/packem_shared/VisConfigLoadError-CeqBSd2Z.js +2 -0
  62. package/dist/packem_shared/VisConfigNotFoundError-DZ9KC527.js +5 -0
  63. package/dist/packem_shared/VisUpdateApp-D-L4_-Iu.js +1 -0
  64. package/dist/packem_shared/_commonjsHelpers-D6W6KoPK.js +1 -0
  65. package/dist/packem_shared/ai-analysis-CGuy7dfE.js +67 -0
  66. package/dist/packem_shared/ai-cache-Bynt6Y9x.js +1 -0
  67. package/dist/packem_shared/cache-directory-D72ZEag2.js +1 -0
  68. package/dist/packem_shared/catalog-BVPerCwG.js +12 -0
  69. package/dist/packem_shared/dependency-scan-Du0tBu64.js +2 -0
  70. package/dist/packem_shared/docker-BcfqH4Av.js +2 -0
  71. package/dist/packem_shared/failure-log-DqYen0LC.js +2 -0
  72. package/dist/packem_shared/flakiness-DSIHZGBT.js +1 -0
  73. package/dist/packem_shared/run-summary-utils-C24Aaf9E.js +1 -0
  74. package/dist/packem_shared/runtime-check-CGHal8SO.js +1 -0
  75. package/dist/packem_shared/selectors-CfH9ZY08.js +3 -0
  76. package/dist/packem_shared/symbols-CQmER5MT.js +1 -0
  77. package/dist/packem_shared/target-merge-DNa-6eWu.js +1 -0
  78. package/dist/packem_shared/toolchain-DQfTQY8E.js +5 -0
  79. package/dist/packem_shared/typosquats-DOR8izpX.js +1 -0
  80. package/dist/packem_shared/use-measured-height-DjYgUOKk.js +1 -0
  81. package/dist/packem_shared/utils-DrNg0XTR.js +1 -0
  82. package/dist/packem_shared/xxh3-DrAUNq4n.js +1 -0
  83. package/index.js +601 -0
  84. package/package.json +124 -7
  85. package/schemas/project.schema.json +422 -0
  86. package/schemas/vis-config.schema.json +377 -0
@@ -0,0 +1,22 @@
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};
@@ -0,0 +1,22 @@
1
+ var ae=Object.defineProperty;var P=(r,e)=>ae(r,"name",{value:e,configurable:!0});import{createRequire as le}from"node:module";import{getManifestData as me}from"@socketsecurity/registry";import{isAccessibleSync as V,readFileSync as _,writeFileSync as F,readJsonSync as Z,glob as he}from"@visulima/fs";import{join as A,resolve as ue}from"@visulima/path";import{Box as p,Text as c,ScrollView as ge,ScrollBar as ye,useApp as ke,useWindowSize as ve,useInput as we,render as be}from"@visulima/tui";import{M as $e,D as xe,f as X,c as Se,p as m,g as Ce,d as Ne}from"./bin.js";import Oe from"module-replacements/manifests/micro-utilities.json"with{type:"json"};import je from"module-replacements/manifests/native.json"with{type:"json"};import Te from"module-replacements/manifests/preferred.json"with{type:"json"};import Ee,{useSyncExternalStore as Pe,useRef as Ae,useState as H,useCallback as De}from"react";import{coerce as Q}from"semver";import{readYamlSync as Ie}from"@visulima/fs/yaml";import{jsx as i,jsxs as d,Fragment as q}from"react/jsx-runtime";const de=le(import.meta.url),R=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,pe=P(r=>{if(typeof R<"u"&&R.versions&&R.versions.node){const[e,t]=R.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return R.getBuiltinModule(r)}return de(r)},"__cjs_getBuiltinModule"),{writeFileSync:fe}=pe("node:fs");var Re=Object.defineProperty,T=P((r,e)=>Re(r,"name",{value:e,configurable:!0}),"c$1");const Fe=["dependencies","devDependencies","peerDependencies","peerDependenciesMeta","optionalDependencies","bundleDependencies"],Me=["overrides","pnpm","resolutions"],_e=["engines","files"],ze=T(r=>{const e=Q(r)?.major;return e!==void 0&&e>=10},"isPnpmV10Plus"),Le=T(r=>{const e=A(r,"pnpm-workspace.yaml");if(!V(e))return{overrides:{},source:"pnpm-workspace.yaml"};try{return{overrides:Ie(e)?.overrides??{},source:"pnpm-workspace.yaml"}}catch{return{overrides:{},source:"pnpm-workspace.yaml"}}},"readPnpmWorkspaceOverrides"),Je=T((r,e)=>{let t={};return e==="pnpm"?t=r.pnpm?.overrides??{}:e==="yarn"||e==="bun"?t=r.resolutions??{}:t=r.overrides??{},{overrides:t,source:"package.json"}},"readPkgJsonOverrides"),qe=T((r,e,t)=>t.name==="pnpm"&&ze(t.version)?Le(r):Je(e,t.name),"readOverrides"),W=T((r,e)=>{const t=e;for(const a of Me){const o=r.indexOf(a);if(o!==-1&&a!==t)return t==="overrides"?o:o+1}let n=-1;for(const a of Fe){const o=r.indexOf(a);o>n&&(n=o)}if(n!==-1)return n+1;for(const a of _e){const o=r.indexOf(a);if(o!==-1)return o}return r.length},"findInsertIndex"),Ge=T(r=>/\n(\s+)/.exec(r)?.[1]??" ","detectIndent"),Be=T((r,e)=>{const t=A(r,"pnpm-workspace.yaml");if(!V(t))throw new Error(`pnpm-workspace.yaml not found at ${t}. Cannot write overrides for pnpm v10+.`);let n=_(t);const a=`overrides:
2
+ ${Object.entries(e).map(([o,s])=>` '${o}': '${s}'`).join(`
3
+ `)}
4
+ `;n=/^overrides:\s*$/m.test(n)||/^overrides:\s*\n/m.test(n)?n.replace(/^overrides:\s*\n(?:(?:[ \t].*)?\n)*/m,a):`${n.trimEnd()}
5
+
6
+ ${a}`,F(t,n)},"writePnpmWorkspaceOverrides"),Ue=T((r,e,t,n)=>{const a=_(r),o=Ge(a);if(n==="pnpm"){const s=e.pnpm??{};if(s.overrides=t,e.pnpm)e.pnpm=s,F(r,`${JSON.stringify(e,null,o)}
7
+ `);else{const y=Object.keys(e),f=W(y,"pnpm"),u=Object.entries(e);u.splice(f,0,["pnpm",s]),F(r,`${JSON.stringify(Object.fromEntries(u),null,o)}
8
+ `)}}else{const s=n==="yarn"||n==="bun"?"resolutions":"overrides";if(e[s])e[s]=t,F(r,`${JSON.stringify(e,null,o)}
9
+ `);else{const y=Object.keys(e),f=W(y,s),u=Object.entries(e);u.splice(f,0,[s,t]),F(r,`${JSON.stringify(Object.fromEntries(u),null,o)}
10
+ `)}}},"writePkgJsonOverrides"),Ve=T((r,e,t,n)=>{const a=_(e),o=JSON.parse(a),{overrides:s,source:y}=qe(r,o,n),f=[],u=[],S=new Set;if(n.name==="npm")for(const g of["dependencies","devDependencies"]){const w=o[g];if(w)for(const k of Object.keys(w))S.add(k)}for(const g of t){const w=s[g.original];if(typeof w=="object")continue;let k=g.spec;n.name==="npm"&&S.has(g.original)&&(k=`$${g.original}`),w!==k&&(w?u.push(g.original):f.push(g.original),s[g.original]=k)}if(f.length===0&&u.length===0)return{added:f,updated:u};const x=Object.fromEntries(Object.entries(s).sort(([g],[w])=>g.localeCompare(w)));return y==="pnpm-workspace.yaml"?Be(r,x):Ue(e,o,x,n.name),{added:f,updated:u}},"applyOverrides"),Xe=T((r,e)=>{const t={bun:["bun.lock"],npm:["npm-shrinkwrap.json","package-lock.json"],pnpm:["pnpm-lock.yaml"],yarn:["yarn.lock"]};for(const n of t[e]??[]){const a=A(r,n);try{return _(a)}catch{continue}}return""},"readLockfileText"),He=T((r,e,t)=>{if(!r)return!1;const n=e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);switch(t){case"bun":return r.includes(`"${e}":`)||new RegExp(String.raw`(^|\s|[",])${n}@`,"m").test(r);case"npm":return r.includes(`"${e}":`)||r.includes(`"node_modules/${e}":`);case"pnpm":return new RegExp(String.raw`(^|\s|['"/])${n}(@|['"]?:)`,"m").test(r);case"yarn":return new RegExp(String.raw`(^|\s|[",])${n}@`,"m").test(r);default:return!1}},"lockfileContainsPackage");var We=Object.defineProperty,M=P((r,e)=>We(r,"name",{value:e,configurable:!0}),"s");const Ye=M((r,e,t)=>{let n=r;if(e!=="all"&&(n=n.filter(a=>a.category===e)),t){const a=t.toLowerCase();n=n.filter(o=>o.packageName.toLowerCase().includes(a))}return n},"filterEntries");class Ke{static{P(this,"h")}static{M(this,"OptimizeStore")}#e;#t=new Set;constructor(e){this.#e={applyProgress:null,checkedEntries:new Set,entries:e,error:null,filterActive:!1,filterText:"",filterType:"all",focusedPanel:"list",phase:"browsing",selectedIndex:0}}getSnapshot=M(()=>this.#e,"getSnapshot");subscribe=M(e=>(this.#t.add(e),()=>{this.#t.delete(e)}),"subscribe");getFilteredEntries=M(()=>Ye(this.#e.entries,this.#e.filterType,this.#e.filterText),"getFilteredEntries");#r(){this.#e={...this.#e};for(const e of this.#t)e()}select(e){const t=this.getFilteredEntries();this.#e.selectedIndex=t.length===0?-1:Math.max(0,Math.min(e,t.length-1)),this.#r()}toggleCheck(e){const t=new Set(this.#e.checkedEntries);t.has(e)?t.delete(e):t.add(e),this.#e.checkedEntries=t,this.#r()}toggleAll(){const e=this.getFilteredEntries(),t=new Set(this.#e.checkedEntries);if(e.every(n=>t.has(n.packageName)))for(const n of e)t.delete(n.packageName);else for(const n of e)t.add(n.packageName);this.#e.checkedEntries=t,this.#r()}setFilter(e){this.#e.filterType=e,this.#e.selectedIndex=0,this.#r()}setFilterText(e){this.#e.filterText=e,this.#e.selectedIndex=0,this.#r()}setFilterActive(e){this.#e.filterActive=e,this.#r()}setFocusedPanel(e){this.#e.focusedPanel=e,this.#r()}setPhase(e){this.#e.phase=e,this.#r()}setProgress(e,t){this.#e.applyProgress={current:e,total:t},this.#r()}setError(e){this.#e.error=e,this.#e.phase="error",this.#r()}getCheckedEntries(){return this.#e.entries.filter(e=>this.#e.checkedEntries.has(e.packageName))}}const ee={"micro-utility":"gray",native:"green",preferred:"yellow",socket:"cyan"},Ze={"micro-utility":"MICRO",native:"NATIVE",preferred:"PREF",socket:"SOCKET"},Qe={"micro-utility":"Trivial utility package that can be replaced with inline code.",native:"Polyfill for a native JS/Node.js API. Use the built-in instead.",preferred:"A lighter or faster alternative package exists.",socket:"Security-hardened replacement from Socket.dev's @socketregistry."};var er=Object.defineProperty,rr=P((r,e)=>er(r,"name",{value:e,configurable:!0}),"d");const tr=rr(({entry:r,focused:e,scrollRef:t})=>{const n=e?"white":"gray";if(!r)return i(p,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:i(c,{dimColor:!0,children:"No entry selected"})});const a=ee[r.category]??"gray";return d(p,{borderColor:n,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[i(p,{flexShrink:0,paddingTop:1,paddingX:2,children:i(c,{bold:!0,color:"white",children:r.packageName})}),d(ge,{flexGrow:1,flexShrink:1,paddingX:2,ref:t,scrollbar:!0,scrollbarColor:"gray",children:[i(c,{}),d(p,{children:[i(p,{width:14,children:i(c,{dimColor:!0,children:"Category:"})}),i(c,{bold:!0,color:a,children:r.category})]}),d(p,{children:[i(p,{width:14,children:i(c,{dimColor:!0,children:"Replace with:"})}),i(c,{children:r.replacement})]}),r.overrideSpec&&d(p,{children:[i(p,{width:14,children:i(c,{dimColor:!0,children:"Override:"})}),i(c,{color:"cyan",children:r.overrideSpec})]}),d(p,{children:[i(p,{width:14,children:i(c,{dimColor:!0,children:"Codemod:"})}),i(c,{color:r.hasCodemod?"green":"gray",children:r.hasCodemod?"available ⚙":"not available"})]}),d(p,{flexDirection:"column",marginTop:1,children:[i(c,{dimColor:!0,children:"── "}),i(c,{bold:!0,color:"white",children:"DESCRIPTION"}),i(p,{marginTop:1,paddingLeft:2,children:i(c,{children:Qe[r.category]??""})})]}),r.category==="native"&&d(p,{flexDirection:"column",marginTop:1,children:[i(c,{dimColor:!0,children:"── "}),i(c,{bold:!0,color:"green",children:"ACTION"}),i(p,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.hasCodemod?d(q,{children:[d(c,{color:"green",children:["✓"," ","Codemod will rewrite imports to use native API."]}),i(c,{dimColor:!0,children:" The package can then be removed from dependencies."})]}):d(q,{children:[d(c,{color:"yellow",children:["ℹ"," ","No automated codemod available."]}),i(c,{dimColor:!0,children:" Manual migration required — replace usage with native equivalent."})]})})]}),r.category==="socket"&&d(p,{flexDirection:"column",marginTop:1,children:[i(c,{dimColor:!0,children:"── "}),i(c,{bold:!0,color:"cyan",children:"ACTION"}),d(p,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[d(c,{color:"cyan",children:["✓"," ","Override will redirect resolution to the hardened package."]}),i(c,{dimColor:!0,children:" No source code changes needed — drop-in replacement."})]})]}),(r.category==="preferred"||r.category==="micro-utility")&&d(p,{flexDirection:"column",marginTop:1,children:[i(c,{dimColor:!0,children:"── "}),i(c,{bold:!0,color:"yellow",children:"ACTION"}),i(p,{flexDirection:"column",marginTop:1,paddingLeft:2,children:r.hasCodemod?d(q,{children:[d(c,{color:"green",children:["✓"," ","Codemod will rewrite imports to the recommended alternative."]}),i(c,{dimColor:!0,children:" The original package can then be removed from dependencies."})]}):d(q,{children:[d(c,{color:"yellow",children:["ℹ"," ","Manual migration required."]}),r.docUrl?i(c,{dimColor:!0,children:" Open the migration guide below for the recommended alternative and steps."}):i(c,{dimColor:!0,children:" Consult the package's docs or the e18e module-replacements guide for an alternative."})]})})]}),d(p,{flexDirection:"column",marginTop:1,children:[i(c,{dimColor:!0,children:"── "}),i(c,{bold:!0,color:"white",children:"LINKS"}),d(p,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[d(c,{color:"cyan",underline:!0,children:["https://npmx.dev/",r.packageName]}),r.docUrl&&i(c,{color:"cyan",underline:!0,children:r.docUrl})]})]})]})]})},"OptimizeDetailPanel");var nr=Object.defineProperty,re=P((r,e)=>nr(r,"name",{value:e,configurable:!0}),"b$1");const ir=[{key:"all",label:"All",shortcut:"1"},{key:"native",label:"Native",shortcut:"2"},{key:"preferred",label:"Preferred",shortcut:"3"},{key:"micro-utility",label:"Micro",shortcut:"4"},{key:"socket",label:"Socket",shortcut:"5"}],or=re(({checked:r,entry:e,isSelected:t})=>{const n=ee[e.category]??"white",a=Ze[e.category]??e.category,o=r?"☑":"☐",s=e.hasCodemod?"⚙":" ";return d(p,{flexShrink:0,height:1,children:[i(c,{children:t?">":" "}),d(c,{color:r?"white":"gray",children:[" ",o," "]}),i(c,{bold:!0,color:n,children:`[${a}]`.padEnd(9)}),d(c,{children:[" ",s," "]}),i(p,{flexGrow:1,children:i(c,{bold:t,inverse:t,wrap:"truncate",children:e.packageName})}),i(c,{dimColor:!0,children:" → "}),i(c,{wrap:"truncate",children:e.replacement})]})},"EntryRow"),cr=re(({checkedEntries:r,entries:e,filterActive:t,filterText:n,filterType:a,focused:o,isDryRun:s,scrollOffset:y,selectedIndex:f,totalEntries:u,viewportHeight:S})=>{const x=o?"white":"gray";let g=0,w=0,k=0,N=0;for(const O of e)switch(O.category){case"micro-utility":{k++;break}case"native":{g++;break}case"preferred":{w++;break}case"socket":{N++;break}}const h=[];g>0&&h.push(`${g} native`),w>0&&h.push(`${w} preferred`),k>0&&h.push(`${k} micro`),N>0&&h.push(`${N} socket`);const b=h.length>0?` (${h.join(", ")})`:"",C=r.size,D=[];for(const[O,$]of e.entries())D.push(i(or,{checked:r.has($.packageName),entry:$,isSelected:O===f},$.packageName));const I=e.length,l=I>S&&S>0;return d(p,{borderColor:x,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[d(p,{flexShrink:0,gap:1,paddingX:1,children:[i(c,{bold:!0,inverse:!0,children:" VIS OPTIMIZE "}),d(c,{wrap:"truncate",children:[u," ","optimizations",b]}),!s&&C>0&&d(c,{dimColor:!0,children:[" ","—",C," ","selected"]})]}),i(p,{flexShrink:0,gap:1,paddingX:1,paddingY:1,children:ir.map(O=>{const $=a===O.key;return d(p,{children:[i(c,{dimColor:!$,children:"["}),i(c,{bold:$,color:$?"cyan":"gray",children:O.shortcut}),i(c,{dimColor:!$,children:"]"}),d(c,{color:$?"white":"gray",children:[" ",O.label]})]},O.key)})}),t&&d(p,{flexShrink:0,paddingX:1,children:[i(c,{bold:!0,color:"white",children:"/ "}),i(c,{children:n}),i(c,{inverse:!0,children:" "})]}),d(p,{flexDirection:"row",flexGrow:1,overflow:"hidden",children:[i(p,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:i(p,{flexDirection:"column",marginTop:-y,children:D})}),l&&i(p,{flexShrink:0,marginLeft:1,marginRight:1,children:i(ye,{contentHeight:I,placement:"inset",scrollOffset:y,style:"block",viewportHeight:S})})]})]})},"OptimizeListPanel");var sr=Object.defineProperty,ar=P((r,e)=>sr(r,"name",{value:e,configurable:!0}),"S");const lr=100,Y=10,K={1:"all",2:"native",3:"preferred",4:"micro-utility",5:"socket"},dr=ar(({isDryRun:r,store:e})=>{const{exit:t}=ke(),{columns:n,rows:a}=ve(),o=Pe(e.subscribe,e.getSnapshot),s=Ae(null),[y,f]=H(0),[u,S]=H(!1),x=e.getFilteredEntries(),g=x[o.selectedIndex]??null,w=n>=lr,k=Math.max(0,a-5),N=De(h=>{t(h)},[t]);return we((h,b)=>{if(u){h==="y"||h==="Y"?N():S(!1);return}if(o.filterActive){b.escape?(e.setFilterActive(!1),e.setFilterText("")):b.return?e.setFilterActive(!1):b.backspace||b.delete?e.setFilterText(o.filterText.slice(0,-1)):h&&!b.ctrl&&!b.meta&&e.setFilterText(o.filterText+h);return}if(h==="q"){!r&&o.checkedEntries.size>0?S(!0):N();return}if(h==="/"){e.setFilterActive(!0);return}if(K[h]){e.setFilter(K[h]);return}if(b.tab){e.setFocusedPanel(o.focusedPanel==="list"?"detail":"list");return}if(o.focusedPanel==="list")if(b.upArrow||h==="k"){const C=Math.max(0,o.selectedIndex-1);e.select(C),C<y&&f(C)}else if(b.downArrow||h==="j"){const C=Math.min(x.length-1,o.selectedIndex+1);e.select(C),C>=y+k&&f(C-k+1)}else h===" "?g&&e.toggleCheck(g.packageName):h==="a"?e.toggleAll():b.return&&!r&&o.checkedEntries.size>0&&N(e.getCheckedEntries());else o.focusedPanel==="detail"&&(b.upArrow||h==="k"?s.current?.scrollBy(-1):(b.downArrow||h==="j")&&s.current?.scrollBy(1))},{isActive:o.phase==="browsing"}),a<Y?i(p,{alignItems:"center",justifyContent:"center",children:d(c,{color:"yellow",children:["Terminal too small. Resize to at least",Y," ","rows."]})}):d(p,{flexDirection:"column",height:a,width:n,children:[d(p,{flexDirection:w?"row":"column",flexGrow:1,children:[i(p,{flexBasis:w?"50%":void 0,flexGrow:1,children:i(cr,{checkedEntries:o.checkedEntries,entries:x,filterActive:o.filterActive,filterText:o.filterText,filterType:o.filterType,focused:o.focusedPanel==="list",isDryRun:r,scrollOffset:y,selectedIndex:o.selectedIndex,totalEntries:o.entries.length,viewportHeight:k})}),i(p,{flexBasis:w?"50%":void 0,flexGrow:1,children:i(tr,{entry:g,focused:o.focusedPanel==="detail",scrollRef:s})})]}),i(p,{flexShrink:0,paddingX:1,children:d(c,{dimColor:!0,children:[r?"Preview mode":"space:toggle a:all enter:apply"," ","| tab:switch panel /: filter q:quit |","⚙","=codemod available"]})}),i($e,{autoExitSeconds:3,onCancel:P(()=>{S(!1)},"onCancel"),visible:u})]})},"VisOptimizeApp");var pr=Object.defineProperty,j=P((r,e)=>pr(r,"name",{value:e,configurable:!0}),"p");const U=j((r,e)=>{const t=new Set;try{const n=Z(r),a=e?[n.dependencies,n.optionalDependencies]:[n.dependencies,n.devDependencies,n.peerDependencies,n.optionalDependencies];for(const o of a)if(o)for(const s of Object.keys(o))t.add(s)}catch{}return t},"collectDepsFromPkgJson"),te=j(r=>{const e=xe(r);if(e)return X(r,e);const t=A(r,"package.json");if(!V(t))return[];try{const n=Z(t),a=Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages;return a?X(r,a):[]}catch{return[]}},"discoverWorkspacePackages"),fr="https://github.com/es-tooling/module-replacements/blob/main/docs/modules",mr=j(r=>`${fr}/${r}.md`,"buildE18eDocUrl"),hr=j(r=>{if(r.type==="simple"&&r.replacement)return r.replacement;if(r.type==="native"){const e=r.nodeVersion?` (Node ${r.nodeVersion}+)`:"";return r.replacement?`${r.replacement}${e}`:`Native API${e}`}return r.type==="documented"&&r.docPath?"see migration guide":""},"e18eReplacementHint"),ne=j(r=>{const e=[],t=j((n,a)=>{const o=n.moduleReplacements;if(Array.isArray(o))for(const s of o)r.has(s.moduleName)&&e.push({category:a,docUrl:s.type==="documented"&&s.docPath?mr(s.docPath):void 0,hasCodemod:!1,overrideSpec:void 0,packageName:s.moduleName,replacement:hr(s)})},"scanManifest");return t(je,"native"),t(Te,"preferred"),t(Oe,"micro-utility"),e},"buildE18eEntries"),ie=j((r,e,t,n)=>{const a=me("npm")??[],o=[];for(const[,s]of a){if(s.deprecated)continue;const y=r.has(s.package),f=e?He(e,s.package,t.name):!1;if(!y&&!f)continue;const u=Q(s.version)?.major;if(u===void 0)continue;const S=n?`npm:${s.name}@${s.version}`:`npm:${s.name}@^${String(u)}`;o.push({category:"socket",hasCodemod:!1,overrideSpec:S,packageName:s.package,replacement:s.name})}return o},"buildSocketEntries");let G;const oe=j(async()=>{if(G)return G;try{return G=(await import("module-replacements-codemods")).codemods,G}catch{return{}}},"loadCodemods"),ce=j(async r=>{try{const e=await oe();for(const t of r)t.category!=="socket"&&e[t.packageName]&&(t.hasCodemod=!0)}catch{}},"markCodemodAvailability"),se=j(async(r,e)=>{let t=0;try{const n=(await oe())[e];if(!n)return{filesChanged:0,packageName:e};const a=n({}),o=await ur(r);for(const s of o){const y=_(s);if(y.includes(e))try{const f=await a.transform({file:{filename:s,source:y}});f!==y&&(fe(s,f,"utf8"),t++)}catch(f){process.stderr.write(`warn: codemod transform failed for ${s}: ${f instanceof Error?f.message:String(f)}
11
+ `)}}}catch{}return{filesChanged:t,packageName:e}},"runCodemod"),ur=j(async r=>he("**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}",{absolute:!0,cwd:r,ignore:["**/.*/**","**/.*","**/node_modules/**","**/dist/**","**/coverage/**","**/.git/**","**/.next/**","**/.nuxt/**"]}),"collectSourceFiles"),gr=j(async({logger:r,options:e,workspaceRoot:t})=>{if(!t)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const n=Se(t),a=!!e.dryRun,o=!!e.prod,s=!!e.pin;m.info(`Detected ${n.name} v${n.version}.`);const y=U(A(t,"package.json"),o),f=te(t),u=new Set(y);for(const l of f){const O=U(A(ue(t,l),"package.json"),o);for(const $ of O)u.add($)}f.length>0&&m.info(`Scanned ${String(f.length)} workspace package${f.length===1?"":"s"}.`),m.info(`Scanning dependencies...
12
+ `);const S=Xe(t,n.name),x=ne(u),g=ie(u,S,n,s),w=new Set(x.map(l=>l.packageName)),k=g.filter(l=>!w.has(l.packageName)),N=[...x,...k];if(await ce(N),N.length===0){m.info("No optimizations found for your dependencies.");return}const h=!!process.stdout.isTTY&&!Ne,b=e.format==="json"||!!e.json;if(h&&!a&&!b){const l=new Ke(N),O=await be(Ee.createElement(dr,{isDryRun:!1,store:l}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0}).waitUntilExit(),$=Array.isArray(O)?O:[];if($.length===0){m.info("No optimizations selected.");return}const z=$.filter(v=>v.category!=="socket"&&v.hasCodemod),L=$.filter(v=>v.category!=="socket"&&!v.hasCodemod),B=$.filter(v=>v.category==="socket");if(z.length>0){m.info(`
13
+ Running ${String(z.length)} codemod${z.length===1?"":"s"}...
14
+ `);for(const v of z){const E=await se(t,v.packageName);E.filesChanged>0?m.success(` ${v.packageName}: ${String(E.filesChanged)} file${E.filesChanged===1?"":"s"} updated`):m.info(` ${v.packageName}: no files changed`)}}if(L.length>0){m.warn(`
15
+ ${String(L.length)} selected replacement${L.length===1?"":"s"} require manual migration (no codemod available):`);for(const v of L)m.info(` ${v.packageName} → ${v.replacement}`);m.notice(" Replace usage in your source code, then remove from dependencies.")}if(B.length>0){const v=B.filter(J=>J.overrideSpec).map(J=>({original:J.packageName,spec:J.overrideSpec})),E=Ve(t,A(t,"package.json"),v,n);E.added.length>0&&m.success(`
16
+ Added ${String(E.added.length)} override${E.added.length===1?"":"s"}.`),E.updated.length>0&&m.success(`Updated ${String(E.updated.length)} override${E.updated.length===1?"":"s"}.`)}if(B.length>0&&!e.noInstall){m.info(`
17
+ Running ${n.name} install to update lockfile...`);const v=Ce(n,{dev:!1,filter:[],force:!1,frozenLockfile:!1,ignoreScripts:!1,lockfileOnly:!1,noOptional:!1,offline:!1,prod:!1,recursive:!1,silent:!1,workspaceRoot:!1},t,r);v!==0&&m.warn(`${n.name} install exited with code ${String(v)}. Run it manually.`)}m.info(""),m.success("Optimization complete.");return}if(b){process.stdout.write(`${JSON.stringify({e18e:x.map(l=>({category:l.category,hasCodemod:l.hasCodemod,packageName:l.packageName,replacement:l.replacement})),packageManager:n.name,socket:k.map(l=>({overrideSpec:l.overrideSpec,packageName:l.packageName,replacement:l.replacement})),total:N.length,workspaces:f.length},void 0,2)}
18
+ `);return}const C=x.filter(l=>l.category==="native"),D=x.filter(l=>l.category==="preferred"),I=x.filter(l=>l.category==="micro-utility");if(C.length>0){m.info(`Native replacements (${String(C.length)}):`);for(const l of C)m.info(` ${l.hasCodemod?"⚙":" "} ${l.packageName} → ${l.replacement}`)}if(D.length>0){m.info(`
19
+ Preferred alternatives (${String(D.length)}):`);for(const l of D)m.info(` ${l.hasCodemod?"⚙":" "} ${l.packageName} → ${l.replacement}`)}if(I.length>0){m.info(`
20
+ Micro-utilities (${String(I.length)}):`);for(const l of I)m.info(` ${l.hasCodemod?"⚙":" "} ${l.packageName} → ${l.replacement}`)}if(k.length>0){m.info(`
21
+ Socket.dev overrides (${String(k.length)}):`);for(const l of k)m.info(` ${l.packageName} → ${l.overrideSpec}`)}m.info(`
22
+ Total: ${String(N.length)} optimizations available (⚙ = codemod available).`),a&&m.notice("Run without --dry-run for interactive selection.")},"execute"),Pr=Object.defineProperty({__proto__:null,buildE18eEntries:ne,buildSocketEntries:ie,collectDepsFromPkgJson:U,default:gr,discoverWorkspacePackages:te,markCodemodAvailability:ce,runCodemod:se},Symbol.toStringTag,{value:"Module"});export{te as A,ce as B,ne as F,se as I,ie as T,Xe as a,Ve as b,Pr as h,U as x};
@@ -0,0 +1,4 @@
1
+ var x=Object.defineProperty;var h=(n,t)=>x(n,"name",{value:t,configurable:!0});import{findPackageManagerSync as N}from"@visulima/package";import{z as P,e as U,Z as j}from"../packem_shared/ai-analysis-CGuy7dfE.js";import{V as z,U as M}from"./bin.js";import{a as O,f as T,b,n as S,_ as V,m as q}from"../packem_shared/catalog-BVPerCwG.js";var A=Object.defineProperty,F=h((n,t)=>A(n,"name",{value:t,configurable:!0}),"x");const J=/^[\^~>=<]+/,G=F(async({argument:n,logger:t,options:f,visConfig:u,workspaceRoot:g})=>{if(!g)throw new Error("Could not determine workspace root. Run this command inside a monorepo.");const m=n,e=m[0];if(!e)throw new Error("Package name is required. Usage: vis analyze <package> [version]");const p=m[1],{packageManager:E}=N(g);let a,w="default";const C=O(g,E);for(const[o,s]of C){const i=s.get(e);if(i){a=i,w=o;break}}if(!a)throw new Error(`Package "${e}" not found in any catalog or package.json. Make sure it exists in your workspace dependencies.`);let r;if(p)r=p;else{t.info(`Fetching latest version for ${e}...
2
+ `);const o=await T(e);if(!o.latest)throw new Error(`Could not determine latest version for "${e}".`);r=o.latest}const d=b(a),k=b(r);if(!d||!k)throw new Error(`Could not parse versions: current="${a}", target="${r}".`);const v=S(d,k);if(v==="none"){t.info(`${e} is already at ${r}. Nothing to analyze.`);return}const R=V(a),l={catalogName:w,currentRange:a,newRange:`${R}${r}`,packageName:e,targetVersion:r,updateType:v},y=P(f.aiType??"impact");if(y==="security"||f.security){t.info(`Checking for known vulnerabilities...
3
+ `);const o=a.replace(J,""),s=(await q([{name:e,version:o}])).get(e);s&&s.length>0&&(l.vulnerabilities=s);const i=z(u?.security?.socket);if(i){const c=(await M([{name:e,version:o}],i)).get(`${e}@${o}`);c&&(l.socketReport={alerts:c.alerts,license:c.license,score:c.score})}}const $=await U([l],t,u?.ai,y);(f.format??"table")==="json"?process.stdout.write(`${JSON.stringify($,void 0,2)}
4
+ `):t.info(j($))},"execute");export{G as default};
@@ -0,0 +1,3 @@
1
+ var ue=Object.defineProperty;var g=(e,n)=>ue(e,"name",{value:n,configurable:!0});import{createRequire as me}from"node:module";import{readJsonSync as te,readFileSync as ge,ensureDirSync as ye}from"@visulima/fs";import{join as w,resolve as ve,dirname as be}from"@visulima/path";import{r as _e,s as $e,p as Q}from"./bin.js";import{toXML as ke}from"jstoxml";import{r as we}from"../packem_shared/docker-BcfqH4Av.js";import{parseLockFileContent as Se}from"@visulima/package";import je from"semver";const fe=me(import.meta.url),M=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ne=g(e=>{if(typeof M<"u"&&M.versions&&M.versions.node){const[n,t]=M.versions.node.split(".").map(Number);if(n>22||n===22&&t>=3||n===20&&t>=16)return M.getBuiltinModule(e)}return fe(e)},"__cjs_getBuiltinModule"),{readdirSync:de,writeFileSync:he}=ne("node:fs"),{randomUUID:Pe}=ne("node:crypto");var xe=Object.defineProperty,L=g((e,n)=>xe(e,"name",{value:n,configurable:!0}),"r$1");const q=L(e=>{try{return te(e)}catch{return}},"readJsonSafe"),Le=L(e=>{if(e.length===0||e.includes("..")||e.startsWith(".")||e.includes("\0")||e.includes("\\"))return!1;if(e.startsWith("@")){const n=e.indexOf("/");return n>1&&!e.includes("/",n+1)}return!e.includes("/")},"isSafePackageName"),Ce=L(e=>e.length>0&&!e.includes("/")&&!e.includes("\\")&&!e.includes("..")&&!e.includes("\0"),"isSafeVersion"),De=L((e,n,t)=>{const o=`${n.replaceAll("/","+")}@${t}`,c=w(e,"node_modules",".pnpm"),l=q(w(c,o,"node_modules",n,"package.json"));if(l)return l;let y;try{y=de(c)}catch{return}const _=`${o}_`;for(const f of y){if(!f.startsWith(_))continue;const d=q(w(c,f,"node_modules",n,"package.json"));if(d)return d}},"readPnpmVirtualStore"),Oe=L((e,n,t)=>{const o=q(w(e,"node_modules",n,"package.json"));return o?.version===t?o:void 0},"readHoistedCopy"),Me=L((e,n,t)=>{if(!(!Le(n)||!Ce(t)))return De(e,n,t)??Oe(e,n,t)},"readInstalledPackageMetadata");var Be=Object.defineProperty,oe=g((e,n)=>Be(e,"name",{value:n,configurable:!0}),"i");const se=new Set(["0BSD","AGPL-3.0","AGPL-3.0-only","AGPL-3.0-or-later","Apache-1.1","Apache-2.0","Artistic-2.0","BlueOak-1.0.0","BSD-2-Clause","BSD-3-Clause","BSL-1.0","CC0-1.0","CC-BY-3.0","CC-BY-4.0","CDDL-1.0","CDDL-1.1","EPL-1.0","EPL-2.0","GPL-2.0","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0","GPL-3.0-only","GPL-3.0-or-later","ISC","LGPL-2.0","LGPL-2.1","LGPL-3.0","MIT","MIT-0","MPL-1.1","MPL-2.0","Python-2.0","Unlicense","WTFPL","Zlib"]),Ae={apache2:"Apache-2.0","apache 2.0":"Apache-2.0",bsd:"BSD-3-Clause","bsd-2":"BSD-2-Clause","bsd-3":"BSD-3-Clause",mit:"MIT",public:"Unlicense","public domain":"Unlicense"},Re=(()=>{const e=new Map;for(const n of se)e.set(n.toLowerCase(),n);for(const[n,t]of Object.entries(Ae))e.set(n,t);return e})(),Te=oe(e=>{const n=e.trim();if(n.length!==0)return se.has(n)?n:Re.get(n.toLowerCase())},"normalizeSpdxId"),Ge=oe(e=>{let n;if(typeof e.license=="string")n=e.license;else if(e.license&&typeof e.license=="object"&&typeof e.license.type=="string")n=e.license.type;else if(Array.isArray(e.licenses)&&e.licenses.length>0){const c=e.licenses[0];c&&typeof c.type=="string"&&(n=c.type)}if(!n)return;const t=n.trim();if(t.length===0)return;if(/[()]|\b(and|or|with)\b/i.test(t))return[{expression:t}];const o=Te(t);return o?[{license:{id:o}}]:[{license:{name:t}}]},"extractLicenseChoice");var Ie=Object.defineProperty,re=g((e,n)=>Ie(e,"name",{value:n,configurable:!0}),"t");const Ee={sha256:"SHA-256",sha384:"SHA-384",sha512:"SHA-512"},Ne={sha256:64,sha384:96,sha512:128},Ue=re(e=>{const n={name:e.name,version:e.version},{integrity:t}=e;return t&&t.hex.length===Ne[t.algorithm]&&(n.hash={alg:Ee[t.algorithm],content:t.hex}),e.dependencies&&(n.dependencies=e.dependencies),e.peerDependencies&&(n.peerDependencies=e.peerDependencies),e.optionalDependencies&&(n.optionalDependencies=e.optionalDependencies),n},"toResolvedPackage"),Fe=[{file:"pnpm-lock.yaml",type:"pnpm"},{file:"package-lock.json",type:"npm"},{file:"yarn.lock",type:"yarn"},{file:"bun.lock",type:"bun"}],Xe=re(e=>{for(const{file:n,type:t}of Fe){let o;try{o=ge(w(e,n))}catch{continue}const c=new Map;for(const l of Se(o,t))c.set(`${l.name}@${l.version}`,Ue(l));return{packages:c,type:t}}},"readLockfilePackages");var qe=Object.defineProperty,ce=g((e,n)=>qe(e,"name",{value:n,configurable:!0}),"r");const B=ce(e=>e.replaceAll(/[^\w.~-]/g,n=>`%${(n.codePointAt(0)??0).toString(16).toUpperCase().padStart(2,"0")}`),"encodeSegment"),k=ce((e,n)=>{const t=e.toLowerCase();if(t.startsWith("@")){const o=t.indexOf("/");if(o>0){const c=t.slice(0,o),l=t.slice(o+1);return`pkg:npm/${B(c)}/${B(l)}@${B(n)}`}}return`pkg:npm/${B(t)}@${B(n)}`},"toNpmPurl");var ze=Object.defineProperty,ie=g((e,n)=>ze(e,"name",{value:n,configurable:!0}),"s");const Je=ie(e=>{const n=e.indexOf(":");return n<=0?e:e.slice(0,n)==="npm"?e.slice(n+1):e},"stripProtocolPrefix"),F=ie((e,n,t)=>{const o=t.get(e);if(!o||o.size===0)return;if(o.has(n))return n;const c=Je(n);if(c!==n&&o.has(c))return c;const l=[...o];return je.maxSatisfying(l,c,{includePrerelease:!0})||l[0]},"resolveSpecifier");var We=Object.defineProperty,m=g((e,n)=>We(e,"name",{value:n,configurable:!0}),"p");const He="1.6",Ve="CycloneDX",Ye="http://cyclonedx.org/schema/bom-1.6.schema.json",Ze="@visulima/vis",ee=m(e=>{try{return te(e)}catch{return}},"readPackageJson"),Ke=m(e=>{if(e){if(typeof e=="string")return e;if(typeof e=="object"&&e.name)return e.email?`${e.name} <${e.email}>`:e.name}},"toAuthorString"),Qe=m(e=>{if(e)return typeof e=="string"?e:e.url},"toRepositoryUrl"),en=m(e=>{if(e)return typeof e=="string"?e:e.url},"toBugsUrl"),nn=m(e=>{const n=[];e.homepage&&n.push({type:"website",url:e.homepage});const t=Qe(e.repository);t&&n.push({type:"vcs",url:t});const o=en(e.bugs);return o&&n.push({type:"issue-tracker",url:o}),n.length>0?n:void 0},"buildExternalReferences"),X=m((e,n)=>{if(!n)return;n.description&&(e.description=n.description);const t=Ke(n.author);t&&(e.author=t);const o=Ge(n);o&&(e.licenses=o);const c=nn(n);c&&(e.externalReferences=c)},"decoratePackageComponent"),tn=m(e=>{const{focus:n,generatorVersion:t,includeDev:o=!1,now:c=new Date,projectGraph:l,serialNumber:y,workspace:_,workspaceRoot:f}=e,d=n&&n.length>0?[...we(n,l)].sort():Object.keys(_.projects).sort(),A=new Set(d),S=new Map;for(const r of d){const s=_.projects[r];s&&S.set(r,ee(w(f,s.root,"package.json")))}const v=[],C=new Map;for(const r of d){const s=_.projects[r];if(!s)continue;const a=S.get(r),i=a?.version??"0.0.0",p=k(r,i);C.set(r,p);const u={"bom-ref":p,name:r,purl:p,type:s.projectType==="application"?"application":"library",version:i};X(u,a),v.push(u)}const R=Xe(f),j=new Map,D=new Map;if(R)for(const r of R.packages.values()){j.set(`${r.name}@${r.version}`,r);let s=D.get(r.name);s||(s=new Set,D.set(r.name,s)),s.add(r.version)}const J=[],I=[],W=new Map;for(const r of d){const s=S.get(r);if(!s)continue;const a=[s.dependencies,s.peerDependencies];o&&a.push(s.devDependencies);const i=new Set,p=m((u,$)=>{if($)for(const[P,b]of Object.entries($)){if(A.has(P)){const x=C.get(P);x&&i.add(x);continue}const h=F(P,b,D);h&&(i.add(k(P,h)),u.push(`${P}@${h}`))}},"seedRef");for(const u of a)p(J,u);p(I,s.optionalDependencies),W.set(r,i)}const T=new Map,E=new Map,H=m((r,s)=>{const a=[...r];for(;a.length>0;){const i=a.pop(),p=T.get(i);if(p==="required"||p==="optional"&&s==="optional")continue;T.set(i,s);const u=j.get(i);if(!u)continue;const $=E.get(i)??new Set,P=[u.dependencies,u.peerDependencies];for(const b of P)if(b)for(const[h,x]of Object.entries(b))for(const O of x){const U=F(h,O,D);U&&($.add(k(h,U)),a.push(`${h}@${U}`))}if(u.optionalDependencies)for(const[b,h]of Object.entries(u.optionalDependencies))for(const x of h){const O=F(b,x,D);O&&($.add(k(b,O)),I.push(`${b}@${O}`))}$.size>0&&E.set(i,$)}},"walk");H(J,"required"),H(I,"optional");const V=[],Y=[...T.keys()].sort();for(const r of Y){const s=j.get(r);if(!s)continue;const a=k(s.name,s.version),i={"bom-ref":a,name:s.name,purl:a,scope:T.get(r)??"required",type:"library",version:s.version};s.hash&&(i.hashes=[s.hash]),X(i,Me(f,s.name,s.version)),V.push(i)}const G=[];for(const[r,s]of W){const a=C.get(r);if(!a)continue;const i=[...s].sort();G.push(i.length>0?{dependsOn:i,ref:a}:{ref:a})}for(const r of Y){const s=j.get(r);if(!s)continue;const a=k(s.name,s.version),i=E.get(r),p=i?[...i].sort():[];G.push(p.length>0?{dependsOn:p,ref:a}:{ref:a})}G.sort((r,s)=>r.ref.localeCompare(s.ref));const N=ee(w(f,"package.json")),Z=(()=>{if(n?.length===1){const p=v.find(u=>u.name===n[0]);if(p)return{"bom-ref":p["bom-ref"],name:p.name,purl:p.purl,type:p.type,version:p.version}}const r=N?.name??"workspace",s=N?.version??"0.0.0",a=k(r,s),i={"bom-ref":a,name:r,purl:a,type:"application",version:s};return X(i,N),i})(),K=Z["bom-ref"],le=K?v.filter(r=>r["bom-ref"]!==K):v;return{$schema:Ye,bomFormat:Ve,components:[...le,...V],dependencies:G,metadata:{component:Z,lifecycles:[{phase:"build"}],timestamp:c.toISOString(),tools:{components:[{name:Ze,type:"application",...t?{version:t}:{}}]}},serialNumber:y??`urn:uuid:${Pe()}`,specVersion:He,version:1}},"buildCycloneDxBom"),on=m(e=>{const n={version:e.version??1,xmlns:"http://cyclonedx.org/schema/bom/1.6"};e.serialNumber&&(n.serialNumber=e.serialNumber);const t=[];return e.metadata&&t.push(sn(e.metadata)),e.components&&e.components.length>0&&t.push({_content:e.components.map(z),_name:"components"}),e.dependencies&&e.dependencies.length>0&&t.push({_content:e.dependencies.map(cn),_name:"dependencies"}),`${ke({_attrs:n,_content:t,_name:"bom"},{header:!0,indent:" ",selfCloseTags:!0})}
2
+ `},"serializeBomToXml"),sn=m(e=>{const n=[];return e.timestamp&&n.push({timestamp:e.timestamp}),e.lifecycles&&e.lifecycles.length>0&&n.push({_content:e.lifecycles.map(t=>{const o=[];return t.phase&&o.push({phase:t.phase}),t.name&&o.push({name:t.name}),t.description&&o.push({description:t.description}),{_content:o,_name:"lifecycle"}}),_name:"lifecycles"}),e.tools?.components&&n.push({_content:[{_content:e.tools.components.map(z),_name:"components"}],_name:"tools"}),e.component&&n.push(z(e.component)),{_content:n,_name:"metadata"}},"metadataToXmlElement"),z=m(e=>{const n={type:e.type};e["bom-ref"]&&(n["bom-ref"]=e["bom-ref"]);const t=[];e.group&&t.push({group:e.group}),t.push({name:e.name}),e.version&&t.push({version:e.version}),e.description&&t.push({description:e.description}),e.author&&t.push({author:e.author}),e.hashes&&e.hashes.length>0&&t.push({_content:e.hashes.map(c=>({_attrs:{alg:c.alg},_content:c.content,_name:"hash"})),_name:"hashes"});const o=rn(e.licenses);return o&&t.push(o),e.purl&&t.push({purl:e.purl}),e.scope&&t.push({scope:e.scope}),e.externalReferences&&e.externalReferences.length>0&&t.push({_content:e.externalReferences.map(c=>({_attrs:{type:c.type},_content:[{url:c.url}],_name:"reference"})),_name:"externalReferences"}),{_attrs:n,_content:t,_name:"component"}},"componentToXmlElement"),rn=m(e=>{if(!e||e.length===0)return;const n=[];for(const t of e){if("expression"in t){n.push({expression:t.expression});continue}const o=[];"id"in t.license&&t.license.id?o.push({id:t.license.id}):"name"in t.license&&t.license.name&&o.push({name:t.license.name}),n.push({_content:o,_name:"license"})}return{_content:n,_name:"licenses"}},"licensesToXmlElement"),cn=m(e=>e.dependsOn&&e.dependsOn.length>0?{_attrs:{ref:e.ref},_content:e.dependsOn.map(n=>({_attrs:{ref:n},_name:"dependency"})),_name:"dependency"}:{_attrs:{ref:e.ref},_name:"dependency"},"dependencyToXmlElement");var an=Object.defineProperty,ae=g((e,n)=>an(e,"name",{value:n,configurable:!0}),"m");const pe=["json","xml"],pn=ae(e=>pe.includes(e),"isSbomFormat"),bn=ae(async({options:e,visConfig:n,workspaceRoot:t})=>{if(!t)throw new Error("Could not determine workspace root. Run inside a monorepo.");const{packageJsons:o,workspace:c}=_e(t,n),l=$e(t,c,o),y=e.focus,_=y?y.split(",").map(j=>j.trim()).filter(Boolean):void 0,f=(e.format??"json").toLowerCase();if(!pn(f))throw new Error(`Unknown --format: "${f}". Expected one of: ${pe.join(", ")}.`);const d=tn({focus:_,includeDev:!!e.includeDev,projectGraph:l,workspace:c,workspaceRoot:t}),A=f==="xml"?on(d):`${JSON.stringify(d,void 0,2)}
3
+ `,S=e.output??(f==="xml"?"sbom.cdx.xml":"sbom.cdx.json");if(S==="-"){process.stdout.write(A);return}const v=ve(t,S);ye(be(v)),he(v,A,"utf8");const C=d.components?.length??0,R=d.dependencies?.length??0;Q.success(`SBOM written to ${v}`),Q.notice(`${C} components, ${R} dependency edges`)},"execute");export{bn as default};
@@ -0,0 +1,10 @@
1
+ var Tt=Object.defineProperty;var N=(e,t)=>Tt(e,"name",{value:t,configurable:!0});import{createRequire as At}from"node:module";import{green as ke,yellow as Fe,dim as S,red as Re,bold as se,cyan as Te}from"@visulima/colorize";import{findPackageManagerSync as st}from"@visulima/package";import{join as le,resolve as Pt}from"@visulima/path";import{Box as h,Text as n,ScrollView as Dt,Spinner as lt,Tabs as Ot,Tab as Nt,ScrollBar as Mt,useApp as Ft,useWindowSize as zt,useInput as jt,Dialog as Et,render as Bt}from"@visulima/tui";import{B as Ke,M as Je,b as Be,c as at,V as ct,U as Lt,p as u,j,d as _t,g as Vt}from"./bin.js";import Ut,{useSyncExternalStore as Ht,useState as xe,useEffect as Ee,useRef as qe,useMemo as Pe,useCallback as Xe}from"react";import{X as qt}from"../packem_shared/xxh3-DrAUNq4n.js";import{isAccessibleSync as Xt,readJsonSync as Wt,ensureDirSync as Qt}from"@visulima/fs";import{findVisConfigFile as Zt}from"./config.js";import{x as Qe,A as dt,a as ei,F as ti,T as ii,B as ri,b as ni,I as oi}from"./handler39.js";import{c as si}from"../packem_shared/runtime-check-CGHal8SO.js";import{f as li,l as ai,s as ci}from"../packem_shared/dependency-scan-Du0tBu64.js";import{jsxs as a,jsx as r,Fragment as di}from"react/jsx-runtime";import{u as ui}from"../packem_shared/use-measured-height-DjYgUOKk.js";import{o as hi,a as ht,w as pi,m as gi}from"../packem_shared/catalog-BVPerCwG.js";const It=At(import.meta.url),Ce=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,_e=N(e=>{if(typeof Ce<"u"&&Ce.versions&&Ce.versions.node){const[t,i]=Ce.versions.node.split(".").map(Number);if(t>22||t===22&&i>=3||t===20&&i>=16)return Ce.getBuiltinModule(e)}return It(e)},"__cjs_getBuiltinModule"),{statSync:Gt,rmSync:We,writeFileSync:Yt,readFileSync:Kt}=_e("node:fs"),{homedir:Jt}=_e("node:os"),{spawnSync:ut}=_e("node:child_process");var fi=Object.defineProperty,Ae=N((e,t)=>fi(e,"name",{value:t,configurable:!0}),"r$2");const Le=Ae(()=>le(Jt(),".vis","cache","doctor"),"getCacheDirectory"),mi=1800*1e3,Ze=Ae(e=>{if(!e)return"";try{return String(Gt(e).mtimeMs)}catch{return""}},"safeMtime"),yi=2,ki=Ae(e=>{const t=JSON.stringify({configMtime:Ze(e.configPath),lockfileMtime:Ze(e.lockfilePath),schema:yi,sections:[...e.sections].toSorted(),socketEnabled:e.socketEnabled,workspaceRoot:e.workspaceRoot});return qt(Buffer.from(t))},"buildDoctorCacheKey"),wi=Ae(e=>{const t=le(Le(),`${e}.json`);if(Xt(t))try{const i=Wt(t);if(Date.now()-i.createdAt>i.ttlMs){We(t,{force:!0});return}return{...i.results,sections:new Set(i.results.sections)}}catch{We(t,{force:!0});return}},"readDoctorCache"),vi=Ae((e,t,i=mi)=>{Qt(Le());const s={createdAt:Date.now(),results:{...t,sections:[...t.sections]},ttlMs:i};Yt(le(Le(),`${e}.json`),JSON.stringify(s,void 0,2),"utf8")},"writeDoctorCache");var bi=Object.defineProperty,_=N((e,t)=>bi(e,"name",{value:t,configurable:!0}),"i$2");const Oe="orphans",Si=_(()=>{if(process.platform!=="linux")return{id:"inotify",message:"inotify capacity check skipped (not Linux).",status:"skip"};let e;try{const t=Kt("/proc/sys/fs/inotify/max_user_watches","utf8").trim(),i=Number.parseInt(t,10);Number.isFinite(i)&&i>0&&(e=i)}catch{return{id:"inotify",message:"Could not read /proc/sys/fs/inotify/max_user_watches.",status:"warn"}}return e===void 0?{id:"inotify",message:"inotify max_user_watches reported a non-numeric value.",status:"warn"}:e<65536?{detail:{maxWatches:e},id:"inotify",message:`inotify watcher limit is ${String(e)} — large monorepos can exhaust this. Bump now with \`sudo sysctl fs.inotify.max_user_watches=524288\` and persist via \`/etc/sysctl.d/99-vis.conf\` so it survives reboot.`,status:"warn"}:{detail:{maxWatches:e},id:"inotify",message:`inotify capacity OK (${String(e)} watches).`,status:"ok"}},"checkInotifyCapacity"),$i=_(()=>{const e=!!process.stdin.isTTY,t=!!process.stdout.isTTY;return e&&t?{id:"tty",message:"Interactive TTY available — watch keybinds enabled.",status:"ok"}:!e&&!t?{id:"tty",message:"No TTY on stdin/stdout — running in CI / piped mode (keybinds disabled).",status:"skip"}:{detail:{stdin:String(e),stdout:String(t)},id:"tty",message:e?"stdin is a TTY but stdout is not — output is being captured; keybinds still work.":"stdout is a TTY but stdin is not — keybinds disabled (input is piped).",status:"skip"}},"checkTtyAvailability"),Ci=_(()=>{const e=process.pid;try{return process.platform==="win32"?ft(e):gt(e)}catch{return[]}},"listOrphanPids"),xi=_(()=>{const e=process.pid;let t;try{t=process.platform==="win32"?ft(e):gt(e)}catch{return{id:Oe,message:"Could not enumerate processes (ps/tasklist failed).",status:"warn"}}if(t.length===0)return{id:Oe,message:"No orphaned vis/task-runner processes detected.",status:"ok"};if(t.length<=2)return{detail:{count:t.length,pids:t.join(",")},id:Oe,message:`${String(t.length)} possibly orphaned process(es) detected (PIDs: ${t.join(", ")}). Likely benign.`,status:"skip"};const i=process.platform==="win32"?t.map(s=>`taskkill /F /PID ${String(s)}`).join(" & "):`kill ${t.join(" ")}`;return{detail:{count:t.length,pids:t.join(",")},id:"orphans",message:`${String(t.length)} possibly orphaned vis/task-runner processes — run \`vis doctor --fix\` to clean them up, or kill them manually: ${i}`,status:"warn"}},"checkOrphanedRunners"),Ri=_((e={})=>{const t=e.enumerate??Ci,i=e.force===!0?"SIGKILL":"SIGTERM",s=e.kill??Di,o=t(),l=[],d=[];for(const p of o)try{s(p,i),l.push(p)}catch(c){const $=c.code??c.message;if($==="ESRCH"){l.push(p);continue}d.push({pid:p,reason:$})}return{failed:d,killed:l}},"killOrphanedRunners"),Ti=_(e=>ut("taskkill",e,{encoding:"utf8"}),"defaultTaskkillRunner"),Ai=_((e,t)=>{process.kill(e,t)},"defaultProcessKill"),Ii=_((e,t,i=Ti)=>{const s=t==="SIGKILL"?["/F","/PID",String(e)]:["/PID",String(e)],o=i(s);if(o.error)throw o.error;if(typeof o.status=="number"&&o.status!==0){const l=o.status===128?"ESRCH":`taskkill exited with code ${String(o.status)}`,d=new Error(l);throw d.code=l,d}},"killViaTaskkill"),Pi=_((e,t,i=Ai)=>{i(e,t)},"killViaSignal"),Di=_((e,t)=>{if(process.platform==="win32"){Ii(e,t);return}Pi(e,t)},"defaultKill"),pt=_((e,t)=>{const i=ut(e,t,{encoding:"utf8"});if(i.error)throw i.error;if(typeof i.status=="number"&&i.status!==0)throw new Error(`${e} exited with code ${String(i.status)}`);return typeof i.stdout=="string"?i.stdout:""},"runProcessListing"),gt=_(e=>{const t=pt("ps",["-Ao","pid=,command="]),i=[];for(const s of t.split(`
2
+ `)){if(s.length===0)continue;const o=/^\s*(\d+)\s+(.+)$/.exec(s);if(!o)continue;const l=Number.parseInt(o[1]??"",10),d=(o[2]??"").toLowerCase();!Number.isFinite(l)||l===e||(/(?:^|[ /])vis-native(?:\s|$|[-.])/.test(d)||/(?:^|[ /])vis\s+run\b/.test(d)||/(?:^|[ /])task-runner(?:\s|$|[-.])/.test(d))&&i.push(l)}return i},"listOrphansUnix"),ft=_(e=>{const t=pt("tasklist",["/FO","CSV","/NH"]),i=[];for(const s of t.split(/\r?\n/)){if(s.length===0)continue;const o=s.split(/","/).map(p=>p.replaceAll(/^"|"$/g,"")),l=(o[0]??"").toLowerCase(),d=Number.parseInt(o[1]??"",10);!Number.isFinite(d)||d===e||(l==="vis.exe"||l.startsWith("vis-native")||l.includes("task-runner"))&&i.push(d)}return i},"listOrphansWindows"),Oi=_(()=>[Si(),$i(),xi()],"runRuntimeDiagnostics");var Ni=Object.defineProperty,ye=N((e,t)=>Ni(e,"name",{value:t,configurable:!0}),"s$2");const me=[{id:"dependencies",label:"Deps"},{id:"security",label:"Security"},{id:"optimization",label:"Optimize"},{id:"runtime",label:"Runtime"}],Me=["dependencies","security","optimization","runtime"],ge=ye(e=>{const t=new Map;for(const i of Me)t.set(i,[]);for(const i of e)t.get(i.section).push(i);for(const[i,s]of t)s.length===0&&t.delete(i);return t},"groupBySection"),fe=ye((e,t,i,s)=>{let o=e.filter(l=>l.section===t);if(s&&(o=o.filter(l=>l.severity===s)),i){const l=i.toLowerCase();o=o.filter(d=>d.title.toLowerCase().includes(l))}return[...o]},"filterFindings"),Mi=ye(e=>{const t={dependencies:"idle",optimization:"idle",runtime:"idle",security:"idle"};for(const i of Me)e.has(i)&&(t[i]="idle");return t},"initialStatus");class et{static{N(this,"DoctorStore")}static{ye(this,"DoctorStore")}#e;#i=new Set;constructor(t=[]){const i=Array.isArray(t)?{findings:t}:t,s=i.findings??[],o=i.activeSections??new Set(Me),l=Me.find(c=>o.has(c))??"dependencies",d=fe(s,l,"",void 0),p=Mi(o);if(s.length>0)for(const c of s)p[c.section]="done";this.#e={all:s,entries:d,filterActive:!1,filterText:"",filterType:l,focusedPanel:"list",grouped:ge(d),pendingAction:void 0,sectionError:{},sectionMessage:{},sectionStatus:p,selectedIndex:0,severityFilter:void 0}}getSnapshot=ye(()=>this.#e,"getSnapshot");subscribe=ye(t=>(this.#i.add(t),()=>{this.#i.delete(t)}),"subscribe");setSelectedIndex(t){const i=Math.max(0,Math.min(t,this.#e.entries.length-1));i!==this.#e.selectedIndex&&this.#t({...this.#e,selectedIndex:i})}setFocusedPanel(t){t!==this.#e.focusedPanel&&this.#t({...this.#e,focusedPanel:t})}setFilterType(t){if(t===this.#e.filterType)return;const i=fe(this.#e.all,t,this.#e.filterText,this.#e.severityFilter);this.#t({...this.#e,entries:i,filterType:t,grouped:ge(i),selectedIndex:0})}setFilter(t){const i=fe(this.#e.all,this.#e.filterType,t,this.#e.severityFilter);this.#t({...this.#e,entries:i,filterText:t,grouped:ge(i),selectedIndex:0})}setFilterActive(t){if(t===this.#e.filterActive)return;if(t){this.#t({...this.#e,filterActive:!0});return}const i=fe(this.#e.all,this.#e.filterType,"",this.#e.severityFilter);this.#t({...this.#e,entries:i,filterActive:!1,filterText:"",grouped:ge(i),selectedIndex:0})}setPendingAction(t){this.#t({...this.#e,pendingAction:t})}setSeverityFilter(t){if(t===this.#e.severityFilter)return;const i=fe(this.#e.all,this.#e.filterType,this.#e.filterText,t);this.#t({...this.#e,entries:i,grouped:ge(i),selectedIndex:0,severityFilter:t})}startSection(t,i){this.#t({...this.#e,sectionMessage:{...this.#e.sectionMessage,[t]:i},sectionStatus:{...this.#e.sectionStatus,[t]:"running"}})}completeSection(t,i){const s=[...this.#e.all,...i],o=fe(s,this.#e.filterType,this.#e.filterText,this.#e.severityFilter),l={...this.#e.sectionMessage};delete l[t],this.#t({...this.#e,all:s,entries:o,grouped:ge(o),sectionMessage:l,sectionStatus:{...this.#e.sectionStatus,[t]:"done"}})}failSection(t,i){this.#t({...this.#e,sectionError:{...this.#e.sectionError,[t]:i},sectionStatus:{...this.#e.sectionStatus,[t]:"error"}})}#t(t){this.#e=t;for(const i of this.#i)try{i()}catch{}}}var Fi=Object.defineProperty,mt=N((e,t)=>Fi(e,"name",{value:t,configurable:!0}),"r$1");const tt={error:0,warn:1},zi=mt(e=>!!e.acceptedRisk,"isAcknowledged"),yt=mt(e=>{const t=[];if(e.sections.has("dependencies")){for(const i of e.outdated)t.push({entry:i,id:`outdated:${i.packageName}`,kind:"outdated",section:"dependencies",severity:"warn",subtitle:`${i.currentRange} → ${i.newRange} (${i.updateType})`,title:i.packageName});for(const i of e.duplicates)t.push({id:`duplicate:${i.name}`,kind:"duplicate",pkg:i,section:"dependencies",severity:"warn",subtitle:`${String(i.versions.length)} versions installed`,title:i.name})}if(e.sections.has("security"))for(const i of e.outdated){if(i.vulnerabilities&&i.vulnerabilities.length>0){const s=i.vulnerabilities[0],o=zi(i)?"warn":"error",l=i.vulnerabilities.length;t.push({entry:i,id:`vuln:${i.packageName}`,kind:"vulnerability",packageName:i.packageName,section:"security",severity:o,subtitle:l===1?`${s.severity} · ${s.id}`:`${String(l)} advisories · top: ${s.severity} ${s.id}`,title:i.packageName})}if(i.socketReport&&i.socketReport.alerts.length>0){const s=Math.round(i.socketReport.score.overall*100);t.push({entry:i,id:`socket:${i.packageName}`,kind:"socket",packageName:i.packageName,section:"security",severity:"warn",subtitle:`${String(i.socketReport.alerts.length)} alert${i.socketReport.alerts.length===1?"":"s"} · score ${String(s)}%`,title:i.packageName})}}if(e.sections.has("optimization"))for(const i of e.optimizations)t.push({entry:i,id:`opt:${i.packageName}`,kind:"optimization",section:"optimization",severity:"warn",subtitle:`${i.category} → ${i.replacement}`,title:i.packageName});if(e.sections.has("runtime"))for(const i of e.runtime)i.status==="warn"&&t.push({diagnostic:i,id:`runtime:${i.id}`,kind:"runtime",section:"runtime",severity:"warn",title:i.message});return t.sort((i,s)=>{if(i.section!==s.section){const o=["dependencies","security","optimization","runtime"];return o.indexOf(i.section)-o.indexOf(s.section)}return tt[i.severity]-tt[s.severity]}),t},"flattenFindings"),kt={dependencies:"Dependencies",optimization:"Optimization",runtime:"Runtime",security:"Security"};var ji=Object.defineProperty,Ei=N((e,t)=>ji(e,"name",{value:t,configurable:!0}),"i$1");const Bi={error:"red",warn:"yellow"},Li={error:"✖",warn:"⚠"},_i={error:" ERROR ",warn:" WARN "},Vi=Ei(({children:e,hint:t,message:i,severity:s,title:o})=>{const l=Bi[s];return a(h,{borderColor:l,borderStyle:"single",flexDirection:"column",flexShrink:0,paddingX:1,children:[a(h,{gap:1,children:[r(n,{backgroundColor:l,bold:!0,color:"black",children:_i[s]}),r(n,{bold:!0,color:l,children:Li[s]}),r(n,{bold:!0,wrap:"truncate-end",children:o})]}),r(n,{wrap:"truncate-end",children:i}),t?r(n,{dimColor:!0,wrap:"truncate-end",children:t}):null,e]})},"ConfigBanner");var Ui=Object.defineProperty,te=N((e,t)=>Ui(e,"name",{value:t,configurable:!0}),"d");const Hi={CRITICAL:"red",HIGH:"red",LOW:"gray",MODERATE:"yellow",UNKNOWN:"gray"},Gi={critical:"red",high:"red",low:"gray",medium:"yellow"},Yi={major:"red",minor:"yellow",patch:"green"},T=te(({children:e,label:t,width:i=14})=>a(h,{children:[r(h,{width:i,children:a(n,{dimColor:!0,children:[t,":"]})}),typeof e=="string"?r(n,{children:e}):e]}),"FieldRow"),oe=te(({children:e})=>r(h,{marginTop:1,children:r(n,{bold:!0,color:"white",children:e})}),"SectionTitle"),Ki=te(({finding:e})=>{const{entry:t}=e,i=Yi[t.updateType]??"white";return a(h,{flexDirection:"column",children:[r(T,{label:"Current",children:t.currentRange}),a(T,{label:"Target",children:[r(n,{children:t.newRange}),a(n,{bold:!0,color:i,children:[" (",t.updateType,")"]})]}),r(T,{label:"Catalog",children:t.catalogName}),t.acceptedRisk?r(T,{label:"Risk ack",children:r(n,{dimColor:!0,children:t.acceptedRisk.reason??"(no reason recorded)"})}):null,r(oe,{children:"Action"}),a(n,{dimColor:!0,children:["Run"," ",r(n,{bold:!0,color:"white",children:"vis update"})," ","to apply this change."]})]})},"OutdatedDetail"),Ji=te(({finding:e})=>a(h,{flexDirection:"column",children:[r(T,{label:"Versions",children:r(n,{children:String(e.pkg.versions.length)})}),r(oe,{children:"Installed versions"}),e.pkg.versions.map(t=>a(n,{children:[" · ",t]},t)),r(oe,{children:"Action"}),a(n,{dimColor:!0,children:["Run"," ",r(n,{bold:!0,color:"white",children:"vis dedupe"})," ","to consolidate to a single resolution."]})]}),"DuplicateDetail"),qi=te(({finding:e})=>{const t=e.entry.vulnerabilities??[];return a(h,{flexDirection:"column",children:[r(T,{label:"Package",children:e.packageName}),r(T,{label:"Current",children:e.entry.currentRange}),r(T,{label:"Advisories",children:String(t.length)}),e.entry.acceptedRisk?r(T,{label:"Risk ack",children:r(n,{dimColor:!0,children:e.entry.acceptedRisk.reason??"(no reason recorded)"})}):null,t.map(i=>{const s=Hi[i.severity]??"gray";return a(h,{flexDirection:"column",marginTop:1,children:[a(h,{children:[r(n,{bold:!0,color:s,children:i.severity}),r(n,{children:" "}),r(n,{children:i.id}),typeof i.cvssScore=="number"?a(n,{dimColor:!0,children:[" · CVSS ",i.cvssScore.toFixed(1)]}):null]}),r(n,{wrap:"wrap",children:i.summary}),i.fixedVersions.length>0?a(n,{dimColor:!0,children:["Fixed in: ",i.fixedVersions.join(", ")]}):null,i.aliases&&i.aliases.length>0?a(n,{dimColor:!0,children:["Aliases: ",i.aliases.join(", ")]}):null]},i.id)})]})},"VulnerabilityDetail"),Xi=te(({finding:e})=>{const t=e.entry.socketReport;if(!t)return r(n,{dimColor:!0,children:"No Socket report attached."});const i=Math.round(t.score.overall*100),s=Ke(t.score.overall);return a(h,{flexDirection:"column",children:[r(T,{label:"Package",children:e.packageName}),r(T,{label:"Overall",children:a(n,{color:s,children:[String(i),"%"]})}),r(T,{label:"Alerts",children:String(t.alerts.length)}),e.entry.acceptedRisk?r(T,{label:"Risk ack",children:r(n,{dimColor:!0,children:e.entry.acceptedRisk.reason??"(no reason recorded)"})}):null,r(oe,{children:"Score breakdown"}),Object.entries(t.score).map(([o,l])=>{if(o==="overall")return null;const d=typeof l=="number"?l:0,p=Math.round(d*100),c=Ke(d);return a(h,{children:[r(h,{width:14,children:a(n,{dimColor:!0,children:[o,":"]})}),a(n,{color:c,children:[String(p),"%"]})]},o)}),r(oe,{children:"Alerts"}),t.alerts.map((o,l)=>{const d=Gi[o.severity]??"gray";return a(h,{flexDirection:"column",marginBottom:1,children:[a(h,{children:[r(n,{bold:!0,color:d,children:o.severity}),r(n,{children:" "}),r(n,{children:o.type})]}),o.props?r(n,{dimColor:!0,wrap:"wrap",children:JSON.stringify(o.props)}):null]},`${o.type}-${String(l)}`)})]})},"SocketDetail"),Wi=te(({finding:e})=>{const{entry:t}=e;return a(h,{flexDirection:"column",children:[r(T,{label:"Package",children:t.packageName}),r(T,{label:"Category",children:t.category}),r(T,{label:"Replacement",children:t.replacement}),t.overrideSpec?r(T,{label:"Override",children:t.overrideSpec}):null,r(T,{label:"Codemod",children:r(n,{color:t.hasCodemod?"green":"gray",children:t.hasCodemod?"available":"not available"})}),t.docUrl?r(T,{label:"Guide",children:r(n,{color:"cyan",underline:!0,children:t.docUrl})}):null,r(oe,{children:"Action"}),t.hasCodemod?a(n,{dimColor:!0,children:["Run"," ",r(n,{bold:!0,color:"white",children:"vis optimize"})," ","to apply the codemod interactively."]}):t.overrideSpec?a(n,{dimColor:!0,children:["Run"," ",r(n,{bold:!0,color:"white",children:"vis optimize"})," ","to install the package override."]}):t.docUrl?r(n,{dimColor:!0,children:"No automated codemod. Open the migration guide above for the recommended alternative and steps."}):r(n,{dimColor:!0,children:"No automated codemod. Consult the package's docs or the e18e module-replacements guide for an alternative."})]})},"OptimizationDetail"),Qi=te(({finding:e})=>{const{diagnostic:t}=e,i=t.status==="warn"?"yellow":t.status==="ok"?"green":"gray";return a(h,{flexDirection:"column",children:[r(T,{label:"Check",children:t.id}),r(T,{label:"Status",children:r(n,{color:i,children:t.status})}),r(oe,{children:"Message"}),r(n,{wrap:"wrap",children:t.message}),t.detail&&Object.keys(t.detail).length>0?a(di,{children:[r(oe,{children:"Details"}),Object.entries(t.detail).map(([s,o])=>a(h,{children:[r(h,{width:20,children:a(n,{dimColor:!0,children:[s,":"]})}),r(n,{children:String(o)})]},s))]}):null]})},"RuntimeDetail"),Zi=te(({finding:e,focused:t,scrollRef:i})=>{const s=t?"white":"gray";if(!e)return r(h,{alignItems:"center",borderColor:"gray",borderStyle:"single",flexDirection:"column",flexGrow:1,justifyContent:"center",children:r(n,{dimColor:!0,children:"No finding selected"})});let o;switch(e.kind){case"duplicate":{o=r(Ji,{finding:e});break}case"optimization":{o=r(Wi,{finding:e});break}case"outdated":{o=r(Ki,{finding:e});break}case"runtime":{o=r(Qi,{finding:e});break}case"socket":{o=r(Xi,{finding:e});break}case"vulnerability":{o=r(qi,{finding:e});break}default:{o=r(n,{dimColor:!0,children:"Unknown finding kind."});break}}return a(h,{borderColor:s,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[a(h,{flexShrink:0,paddingTop:1,paddingX:2,children:[r(n,{bold:!0,color:"white",children:e.title}),a(n,{dimColor:!0,children:[" ",kt[e.section]]})]}),a(Dt,{flexGrow:1,flexShrink:1,paddingX:2,ref:i,scrollbar:!0,scrollbarColor:"gray",scrollbarStyle:"block",children:[r(n,{}),o]})]})},"DoctorDetailPanel");var er=Object.defineProperty,Ie=N((e,t)=>er(e,"name",{value:t,configurable:!0}),"c$1");const wt={error:"red",warn:"yellow"},tr={error:"✖",warn:"⚠"},ir=Ie(e=>e.kind==="outdated"||e.kind==="vulnerability"||e.kind==="socket"?!!e.entry.acceptedRisk:!1,"hasAcceptedRisk"),rr=Ie(({finding:e,isSelected:t})=>{const i=wt[e.severity],s=ir(e);return a(h,{flexShrink:0,height:1,children:[r(n,{children:t?">":" "}),a(n,{color:i,children:[" ",tr[e.severity]," "]}),r(h,{flexGrow:1,children:r(n,{bold:t,inverse:t,wrap:"truncate",children:e.title})}),s?r(n,{color:"cyan",children:" ack"}):null,e.subtitle?a(n,{dimColor:!0,wrap:"truncate",children:[" ",e.subtitle]}):null]})},"FindingRow"),nr=Ie(({count:e,section:t})=>a(h,{flexShrink:0,height:1,marginTop:1,children:[a(n,{dimColor:!0,children:["▼"," "]}),r(n,{bold:!0,color:"white",children:kt[t].toUpperCase()}),a(n,{dimColor:!0,children:[" (",e,")"]})]}),"SectionHeader"),or=Ie(({count:e,label:t,status:i})=>a(n,{children:[t,i==="running"?a(n,{children:[" ",r(lt,{type:"dots"})]}):null,i==="error"?r(n,{bold:!0,color:"red",children:" ✖"}):a(n,{dimColor:!0,children:[" (",String(e),")"]})]}),"TabLabel"),sr=Ie(({elapsedMs:e,entries:t,filterActive:i,filterText:s,filterType:o,focused:l,fromCache:d=!1,grouped:p,onViewportHeightChange:c,scrollOffset:$,sectionCounts:x,sectionMessage:b,sectionStatus:I,selectedIndex:f,severityFilter:w,totalAll:E,viewportHeight:Z})=>{const q=l?"white":"gray",{measuredHeight:B,ref:M}=ui(Z,c);let P=0,L=0;for(const v of t)v.severity==="error"?P+=1:v.severity==="warn"&&(L+=1);const X=[];P>0&&X.push(`${String(P)} error${P===1?"":"s"}`),L>0&&X.push(`${String(L)} warn${L===1?"":"s"}`);const ie=X.length>0?` (${X.join(", ")})`:"",G=(e/1e3).toFixed(1),D=[];for(const[v,A]of p){D.push(r(nr,{count:A.length,section:v},`hdr-${v}`));for(const R of A){const U=t.indexOf(R);D.push(r(rr,{finding:R,isSelected:U===f},R.id))}}let V=0;for(const[,v]of p)V+=2+v.length;const Y=V>B&&B>0;return a(h,{borderColor:q,borderStyle:"single",flexDirection:"column",flexGrow:1,children:[a(h,{flexShrink:0,gap:1,paddingX:1,children:[r(n,{bold:!0,inverse:!0,children:" DOCTOR "}),a(n,{wrap:"truncate",children:[t.length,t.length===E?"":`/${String(E)}`," finding",t.length===1?"":"s",ie]}),w?r(n,{bold:!0,color:wt[w],inverse:!0,children:` ${w.toUpperCase()} ONLY `}):null,d?r(n,{bold:!0,color:"cyan",inverse:!0,children:" CACHED "}):null,a(n,{dimColor:!0,children:[" · ",G,"s"]})]}),r(h,{flexShrink:0,paddingX:1,paddingY:1,children:r(Ot,{isFocused:l,keyMap:{next:[],previous:[],useNumbers:!1,useTab:!1},onChange:N(()=>{},"onChange"),showIndex:!1,value:o,children:me.map(({id:v,label:A})=>r(Nt,{name:v,children:r(or,{count:x[v],label:A,status:I[v]})},v))})}),(()=>{const v=Object.keys(I).filter(A=>I[A]==="running"&&b[A]).map(A=>b[A]);return v.length===0?null:r(h,{flexShrink:0,paddingX:1,children:a(n,{dimColor:!0,wrap:"truncate",children:[r(lt,{type:"dots"})," ",v.join(" · ")]})})})(),i&&a(h,{flexShrink:0,paddingX:1,children:[r(n,{bold:!0,color:"white",children:"/ "}),r(n,{children:s}),r(n,{inverse:!0,children:" "})]}),a(h,{flexDirection:"row",flexGrow:1,overflow:"hidden",ref:M,children:[r(h,{flexDirection:"column",flexGrow:1,overflow:"hidden",paddingLeft:1,children:r(h,{flexDirection:"column",marginTop:-$,children:D.length>0?D:r(h,{marginTop:1,children:r(n,{dimColor:!0,children:"No findings match the current filter."})})})}),Y&&r(h,{flexShrink:0,marginLeft:1,marginRight:1,children:r(Mt,{contentHeight:V,placement:"inset",scrollOffset:$,style:"block",viewportHeight:B})})]},`list-${o}-${s}`)]})},"DoctorListPanel");var lr=Object.defineProperty,ze=N((e,t)=>lr(e,"name",{value:t,configurable:!0}),"g$1");const ar=ze(e=>{if(e.kind==="outdated")return{command:`vis update ${e.entry.packageName}`,description:`Update ${e.entry.packageName} to ${e.entry.newRange}`};if(e.kind==="duplicate")return{command:`vis dedupe ${e.pkg.name}`,description:`Dedupe ${e.pkg.name} (${String(e.pkg.versions.length)} versions)`}},"buildUpdateAction"),cr=ze(e=>{if(e.kind==="optimization")return{command:`vis optimize ${e.entry.packageName}`,description:`Replace ${e.entry.packageName} with ${e.entry.replacement}`}},"buildOptimizeAction"),dr=ze(e=>{if(e.kind!=="outdated"&&e.kind!=="vulnerability"&&e.kind!=="socket")return;const t=e.kind==="outdated"?e.entry.packageName:e.packageName,i=["// Add to vis.config.ts:","security: {"," acceptedRisks: {",` "${t}": {`,' reason: "explain why this risk is acceptable",',' expiresAt: "YYYY-MM-DD",'," },"," },","},"].join(`
3
+ `);return{command:i,configSnippet:i,description:`Acknowledge risk for ${t}`}},"buildAckAction"),ur=100,hr=40,pr=10,gr=ze(({autoExitSeconds:e=0,banner:t,fromCache:i=!1,startedAt:s,store:o})=>{const{exit:l}=Ft(),{columns:d,rows:p}=zt(),c=Ht(o.subscribe,o.getSnapshot),[$,x]=xe(!1),[b,I]=xe(!1),[f,w]=xe(0),[E,Z]=xe(()=>Date.now());Ee(()=>{const y=setInterval(()=>{Z(Date.now())},1e3);return()=>{clearInterval(y)}},[]);const q=E-s,B=qe(null),M=qe(null),P=c.entries[c.selectedIndex]??null,L=Pe(()=>{const y={dependencies:0,optimization:0,runtime:0,security:0};for(const m of c.all)y[m.section]+=1;return y},[c.all]),X=t?t.hint?5:4:0,ie=Pe(()=>{for(const y of Object.keys(c.sectionStatus))if(c.sectionStatus[y]==="running"&&c.sectionMessage[y])return 1;return 0},[c.sectionStatus,c.sectionMessage]),G=d>=ur,D=G?Math.max(1,p-X-2):Math.floor(p*.55),V=Pe(()=>Math.max(1,D-6-ie-(c.filterActive?1:0)),[D,ie,c.filterActive]),[Y,v]=xe(V),A=Y>0?Y:V,R=Pe(()=>{let y=0;for(const[,m]of c.grouped)y+=2+m.length;return y},[c.grouped]),U=Math.max(0,R-A);Ee(()=>{w(y=>Math.min(y,U))},[U]);const ce=Xe(y=>{let m=0,k=0;for(const[,Se]of c.grouped){m+=2;for(const $e of Se){if(k===y)return m;m+=1,k+=1}}return m},[c.grouped]),O=Xe(y=>{const m=ce(y);w(k=>m>k+A-2?Math.min(U,Math.max(0,m-A+2)):m<k+1?Math.max(0,m-1):k)},[ce,A,U]);if(Ee(()=>{M.current?.scrollToTop()},[P?.id]),jt((y,m)=>{if(y==="c"&&m.ctrl){l();return}if(!b){if($){m.escape||y==="?"?x(!1):y==="q"?(x(!1),I(!0)):m.downArrow||y==="j"?B.current?.scrollBy(1):(m.upArrow||y==="k")&&B.current?.scrollBy(-1);return}if(y==="?"){x(!0);return}if(y==="q"){I(!0);return}if(m.tab){o.setFocusedPanel(c.focusedPanel==="list"?"detail":"list");return}if(c.filterActive){if(m.escape||m.return){o.setFilterActive(!1);return}if(m.backspace){w(0),o.setFilter(c.filterText.slice(0,-1));return}y&&!m.ctrl&&!m.meta&&(w(0),o.setFilter(c.filterText+y));return}if(c.focusedPanel==="list"&&(m.leftArrow||m.rightArrow)){const k=me.findIndex($e=>$e.id===c.filterType),Se=m.rightArrow?(k+1)%me.length:(k-1+me.length)%me.length;w(0),M.current?.scrollToTop(),o.setFilterType(me[Se].id);return}if(c.focusedPanel==="list"){if(m.downArrow||y==="j"){const k=Math.min(c.selectedIndex+1,c.entries.length-1);o.setSelectedIndex(k),O(k);return}if(m.upArrow||y==="k"){const k=Math.max(c.selectedIndex-1,0);o.setSelectedIndex(k),O(k);return}if(m.pageDown){const k=Math.min(c.selectedIndex+10,c.entries.length-1);o.setSelectedIndex(k),O(k);return}if(m.pageUp){const k=Math.max(c.selectedIndex-10,0);o.setSelectedIndex(k),O(k);return}if(m.home){o.setSelectedIndex(0),w(0);return}if(m.end){const k=c.entries.length-1;o.setSelectedIndex(k),O(k);return}if(y==="/"){o.setFilterActive(!0);return}if(y==="e"){o.setSeverityFilter(c.severityFilter==="error"?void 0:"error"),w(0);return}if(y==="w"){o.setSeverityFilter(c.severityFilter==="warn"?void 0:"warn"),w(0);return}if(y==="u"&&P){const k=ar(P);k&&(o.setPendingAction(k),l());return}if(y==="o"&&P){const k=cr(P);k&&(o.setPendingAction(k),l());return}if(y==="a"&&P){const k=dr(P);k&&(o.setPendingAction(k),l());return}if(y==="d"){o.setFocusedPanel("detail");return}return}if(m.escape||m.leftArrow){o.setFocusedPanel("list");return}if(m.downArrow||y==="j"){M.current?.scrollBy(1);return}if(m.upArrow||y==="k"){M.current?.scrollBy(-1);return}if(m.pageDown){M.current?.scrollBy(10);return}if(m.pageUp){M.current?.scrollBy(-10);return}if(m.home){M.current?.scrollToTop();return}m.end&&M.current?.scrollToBottom()}},{isActive:!0}),d<hr||p<pr)return r(h,{alignItems:"center",height:p,justifyContent:"center",width:d,children:a(n,{color:"yellow",children:["Terminal too small (",d,"x",p,")"]})});const W=c.focusedPanel==="detail",ee=[a(h,{gap:1,children:[r(n,{bold:!0,color:"white",children:"q"}),r(n,{dimColor:!0,children:"QUIT"})]},"q"),a(h,{gap:1,children:[r(n,{bold:!0,color:"white",children:"?"}),r(n,{dimColor:!0,children:"HELP"})]},"?"),a(h,{gap:1,children:[r(n,{bold:!0,color:"white",children:"↑↓"}),r(n,{dimColor:!0,children:W?"SCROLL":"NAV"})]},"nav"),W?a(h,{gap:1,children:[r(n,{bold:!0,color:"white",children:"←/Esc"}),r(n,{dimColor:!0,children:"LIST"})]},"lr"):a(h,{gap:1,children:[r(n,{bold:!0,color:"white",children:"←→"}),r(n,{dimColor:!0,children:"SECTION"})]},"lr"),a(h,{gap:1,children:[r(n,{bold:!0,color:"white",children:"/"}),r(n,{dimColor:!0,children:"SEARCH"})]},"search"),a(h,{gap:1,children:[r(n,{bold:!0,color:"white",children:"e/w"}),r(n,{dimColor:!0,children:"SEVERITY"})]},"sev"),a(h,{gap:1,children:[r(n,{bold:!0,color:"white",children:"u/o/a"}),r(n,{dimColor:!0,children:"ACTION"})]},"actions"),a(h,{gap:1,children:[r(n,{bold:!0,color:"white",children:"Tab"}),r(n,{dimColor:!0,children:"PANEL"})]},"tab")],de=r(h,{borderBottom:!1,borderColor:"gray",borderLeft:!1,borderRight:!1,borderStyle:"single",flexShrink:0,children:r(h,{gap:2,overflow:"hidden",paddingX:1,children:ee})}),ue=a(Et,{footer:a(n,{dimColor:!0,children:[r(n,{bold:!0,color:"white",children:"↑↓"})," scroll ",r(n,{bold:!0,color:"white",children:"?"}),"/",r(n,{bold:!0,color:"white",children:"Esc"})," close"]}),scrollRef:B,title:"DOCTOR — KEYBOARD SHORTCUTS",visible:$,width:56,children:[a(h,{flexDirection:"column",marginBottom:1,children:[a(h,{marginBottom:1,children:[r(n,{dimColor:!0,children:"── "}),r(n,{bold:!0,color:"white",children:"NAVIGATION"})]}),a(h,{children:[r(h,{width:26,children:a(n,{children:[r(n,{bold:!0,color:"white",children:" ↑/k "}),r(n,{dimColor:!0,children:"Move up"})]})}),a(n,{children:[r(n,{bold:!0,color:"white",children:" ↓/j "}),r(n,{dimColor:!0,children:"Move down"})]})]}),a(h,{children:[r(h,{width:26,children:a(n,{children:[r(n,{bold:!0,color:"white",children:" PgUp"}),r(n,{dimColor:!0,children:" Jump up 10"})]})}),a(n,{children:[r(n,{bold:!0,color:"white",children:" PgDn"}),r(n,{dimColor:!0,children:" Jump down 10"})]})]}),a(h,{children:[r(h,{width:26,children:a(n,{children:[r(n,{bold:!0,color:"white",children:" Home"}),r(n,{dimColor:!0,children:" Jump to top"})]})}),a(n,{children:[r(n,{bold:!0,color:"white",children:" End"}),r(n,{dimColor:!0,children:" Jump to bottom"})]})]}),a(n,{children:[r(n,{bold:!0,color:"white",children:" Tab"}),r(n,{dimColor:!0,children:" Switch panel"})]}),a(n,{children:[r(n,{bold:!0,color:"white",children:" →/←"}),r(n,{dimColor:!0,children:" Section tabs (list) / Focus list (detail)"})]})]}),a(h,{flexDirection:"column",marginBottom:1,children:[a(h,{marginBottom:1,children:[r(n,{dimColor:!0,children:"── "}),r(n,{bold:!0,color:"white",children:"FILTER"})]}),a(n,{children:[r(n,{bold:!0,color:"white",children:" /"}),r(n,{dimColor:!0,children:" Open text filter (Esc/Enter to close)"})]}),a(n,{children:[r(n,{bold:!0,color:"white",children:" e"}),r(n,{dimColor:!0,children:" Toggle errors-only filter"})]}),a(n,{children:[r(n,{bold:!0,color:"white",children:" w"}),r(n,{dimColor:!0,children:" Toggle warns-only filter"})]})]}),a(h,{flexDirection:"column",marginBottom:1,children:[a(h,{marginBottom:1,children:[r(n,{dimColor:!0,children:"── "}),r(n,{bold:!0,color:"white",children:"ACTIONS"})]}),a(n,{children:[r(n,{bold:!0,color:"white",children:" u"}),r(n,{dimColor:!0,children:" Exit + suggest update / dedupe command"})]}),a(n,{children:[r(n,{bold:!0,color:"white",children:" o"}),r(n,{dimColor:!0,children:" Exit + suggest optimize command"})]}),a(n,{children:[r(n,{bold:!0,color:"white",children:" a"}),r(n,{dimColor:!0,children:" Exit + print risk-ack snippet"})]}),a(n,{children:[r(n,{bold:!0,color:"white",children:" d"}),r(n,{dimColor:!0,children:" Focus detail panel"})]})]}),a(h,{flexDirection:"column",children:[a(h,{marginBottom:1,children:[r(n,{dimColor:!0,children:"── "}),r(n,{bold:!0,color:"white",children:"EXIT"})]}),a(n,{children:[r(n,{bold:!0,color:"white",children:" q"}),r(n,{dimColor:!0,children:" Quit (with countdown)"})]}),a(n,{children:[r(n,{bold:!0,color:"white",children:" Ctrl+C"}),r(n,{dimColor:!0,children:" Quit immediately"})]})]})]}),he=r(sr,{elapsedMs:q,entries:c.entries,filterActive:c.filterActive,filterText:c.filterText,filterType:c.filterType,focused:c.focusedPanel==="list",fromCache:i,grouped:c.grouped,onViewportHeightChange:v,scrollOffset:f,sectionCounts:L,sectionMessage:c.sectionMessage,sectionStatus:c.sectionStatus,selectedIndex:c.selectedIndex,severityFilter:c.severityFilter,totalAll:c.all.length,viewportHeight:A}),pe=t?r(Vi,{hint:t.hint,message:t.message,severity:t.severity,title:t.title}):null,be=r(Zi,{finding:P,focused:c.focusedPanel==="detail",scrollRef:M});if(G){const y=Math.floor(d*.4);return a(h,{flexDirection:"column",height:p,width:d,children:[pe,a(h,{flexDirection:"row",flexGrow:1,children:[r(h,{flexGrow:1,children:he}),r(h,{width:y,children:be})]}),de,r(Je,{autoExitSeconds:e||3,onCancel:N(()=>{I(!1)},"onCancel"),visible:b}),ue]})}return a(h,{flexDirection:"column",height:p,width:d,children:[pe,r(h,{height:D,children:he}),r(h,{flexGrow:1,children:be}),de,r(Je,{autoExitSeconds:e||3,onCancel:N(()=>{I(!1)},"onCancel"),visible:b}),ue]})},"VisDoctorApp");var fr=Object.defineProperty,we=N((e,t)=>fr(e,"name",{value:t,configurable:!0}),"n$1");const mr=we(e=>e.replaceAll(/[$()+.?[\\\]^{|}]/g,String.raw`\$&`),"escapeRegex"),yr=we(e=>{const t=e.split("*").map(mr);return new RegExp(`^${t.join(".*")}$`,"i")},"compilePattern"),kr=we(e=>e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(yr):[],"parseFilterPatterns"),Ne=we((e,t)=>{for(const i of t)if(i.test(e))return!0;return!1},"matchesAny"),wr=we((e,t)=>{if(t.length===0)return e;const i=e.outdated.filter(c=>Ne(c.packageName,t)),s=e.duplicates.filter(c=>Ne(c.name,t)),o=e.optimizations.filter(c=>Ne(c.packageName,t));let l=0,d=0,p=0;for(const c of i)c.vulnerabilities&&(l+=c.vulnerabilities.length),c.socketReport&&(d+=c.socketReport.alerts.length,c.socketReport.score.overall<Be&&(p+=1));return{...e,duplicates:s,optimizations:o,outdated:i,socketIssues:{alerts:d,lowScore:p},vulnCount:l}},"applyFilter"),vt=we((e,t)=>t.length===0?[...e]:e.filter(i=>{if(i.kind==="runtime")return!0;const s=i.kind==="duplicate"?i.pkg.name:i.kind==="outdated"||i.kind==="optimization"?i.entry.packageName:i.packageName;return Ne(s,t)}),"filterFindingsByPattern");var vr=Object.defineProperty,ve=N((e,t)=>vr(e,"name",{value:t,configurable:!0}),"r");const bt=["dependencies","security","optimization","runtime"],it=ve(e=>{const t=new Set;if(!e)return t;for(const i of e.split(",")){const s=i.trim().toLowerCase();bt.includes(s)&&t.add(s)}return t},"parseSectionList"),br=ve((e,t)=>{if(e!==void 0&&e!=="")return it(e);const i=it(t);return new Set(bt.filter(s=>!i.has(s)))},"resolveSections"),St=ve(e=>{const t={micro:0,native:0,preferred:0,socket:0,total:e.length};for(const i of e)switch(i.category){case"micro-utility":{t.micro+=1;break}case"native":{t.native+=1;break}case"preferred":{t.preferred+=1;break}case"socket":{t.socket+=1;break}}return t},"summarizeOptimizations"),ne=ve((e,t)=>{if(!e.sections.has(t))return"skip";switch(t){case"dependencies":return e.outdated.length>0||e.duplicates.length>0?"warn":"ok";case"optimization":return e.optimizations.length>0?"warn":"ok";case"runtime":return e.runtime.some(i=>i.status==="warn")?"warn":"ok";case"security":return e.vulnCount>0||e.socketIssues.alerts>0?"error":e.socketIssues.lowScore>0?"warn":"ok";default:return"ok"}},"sectionStatus"),Sr=ve((e,t)=>{const i=St(e.optimizations),s={dependencies:ne(e,"dependencies"),optimization:ne(e,"optimization"),runtime:ne(e,"runtime"),security:ne(e,"security")},o=new Set([...Object.values(s),e.supplyChain.status]),l=o.has("error")?"error":o.has("warn")?"warn":"ok";return{dependencies:{duplicates:e.duplicates.length,installed:e.installedCount,outdated:e.outdated.length,status:s.dependencies},elapsedMs:e.elapsedMs,optimizations:{microUtilities:i.micro,native:i.native,preferred:i.preferred,socket:i.socket,status:s.optimization,total:i.total},packageManager:t,runtime:e.runtime.map(d=>({detail:d.detail,id:d.id,message:d.message,status:d.status})),runtimeStatus:s.runtime,security:{alerts:e.socketIssues.alerts,lowScorePackages:e.socketIssues.lowScore,status:s.security,vulnerabilities:e.vulnCount},status:l,supplyChain:{findings:e.supplyChain.findings.map(d=>({detail:d.detail,label:d.label,severity:d.severity})),status:e.supplyChain.status},workspaces:e.workspaceCount}},"buildJsonPayload"),rt=ve((e,t)=>{const i=e.runtime.some(o=>o.status==="warn"),s=e.vulnCount>0||e.socketIssues.alerts>0;return t?s||e.outdated.length>0||e.duplicates.length>0||i:s},"shouldFail");var $r=Object.defineProperty,$t=N((e,t)=>$r(e,"name",{value:t,configurable:!0}),"l");const nt=$t(e=>e.some(t=>t.severity==="error")?"error":e.some(t=>t.severity==="warn")?"warn":"ok","rollUpStatus"),Cr=$t(e=>{const t=[],i=e?.security;if(!i)return t.push({detail:"Use defineConfig() from '@visulima/vis/config' to apply secure defaults.",label:"No security config — running with the PM's native defaults",severity:"warn"}),{findings:t,status:nt(t)};i.minimumReleaseAge===void 0?t.push({detail:"Set security.minimumReleaseAge to block packages published in the last N minutes (mitigates supply-chain attacks).",label:"minimumReleaseAge is not set",severity:"warn"}):i.minimumReleaseAge===0?t.push({detail:"New packages can be installed immediately after publishing. Consider setting a non-zero cooldown.",label:"minimumReleaseAge is explicitly 0",severity:"warn"}):t.push({label:`minimumReleaseAge: ${String(i.minimumReleaseAge)} minutes`,severity:"ok"}),i.trustPolicy===void 0||i.trustPolicy==="off"?t.push({detail:"Packages whose trust level has decreased will not be blocked. Consider 'no-downgrade'.",label:`trustPolicy: ${i.trustPolicy??"not set"}`,severity:"warn"}):t.push({label:`trustPolicy: ${i.trustPolicy}`,severity:"ok"}),i.blockExoticSubdeps===void 0||!i.blockExoticSubdeps?t.push({detail:"Transitive dependencies can pull code from git repos or tarball URLs. Set to true to block.",label:`blockExoticSubdeps: ${String(i.blockExoticSubdeps??!1)}`,severity:"warn"}):t.push({label:"blockExoticSubdeps: true",severity:"ok"});const s=i.allowBuilds?Object.keys(i.allowBuilds).length:0;return s===0?t.push({detail:"Lifecycle scripts are blocked by default. List trusted packages here to opt them back in (e.g. esbuild, @prisma/client).",label:"allowBuilds: not configured",severity:"warn"}):t.push({label:`allowBuilds: ${String(s)} ${s===1?"entry":"entries"}`,severity:"ok"}),i.strictDepBuilds&&s===0&&t.push({detail:"All dependencies with build scripts will be blocked. Run 'vis approve-builds' to populate allowBuilds.",label:"strictDepBuilds is on but allowBuilds is empty",severity:"error"}),{findings:t,status:nt(t)}},"buildSupplyChainPosture");var xr=Object.defineProperty,C=N((e,t)=>xr(e,"name",{value:t,configurable:!0}),"u");const H=C(e=>e>=1e3?`${(e/1e3).toFixed(1)}s`:`${String(Math.round(e))}ms`,"fmtDuration"),De=C(async(e,t,i,s)=>{if(!e)return i();e.start(t);const o=Date.now();try{const l=await i(),d=Date.now()-o,{status:p,summary:c}=s(l,d);return e.finish(t,p,c),l}catch(l){const d=Date.now()-o,p=l instanceof Error?l.message:String(l);throw e.finish(t,"error",`${p} (${H(d)})`),l}},"tracked"),Rr=C((e,t)=>{const i={duplicates:t.duplicates,elapsedMs:0,installedCount:0,optimizations:t.optimizations,outdated:t.outdated,runtime:t.runtime,sections:new Set([e]),socketIssues:{alerts:0,lowScore:0},supplyChain:{findings:[],status:"ok"},vulnCount:0,workspaceCount:0};return yt(i)},"buildSectionFindings"),ot=C(async e=>{const{filterPatterns:t,installed:i,progress:s,resolveCodemods:o,sections:l,store:d,visConfig:p,workspaceRoot:c}=e,$=l.has("dependencies"),x=l.has("security"),b=l.has("optimization"),I=l.has("runtime"),f=C((g,F)=>vt(Rr(g,F),t),"sectionFindings"),w=at(c),{packageManager:E}=st(c),Z=Qe(le(c,"package.json"),!1),q=dt(c),B=new Set(Z);for(const g of q){const F=Qe(le(Pt(c,g),"package.json"),!1);for(const z of F)B.add(z)}const M=hi(c),P=ht(c,E),L=ct(p?.security?.socket),X=p?.security?.socket?.acceptedRisks,ie=ei(c,w.name),G={exclude:[],ignore:[],include:[],includeLocked:!1,includePrerelease:!1,security:!0,target:"latest"},D=$?li(c,w.name):[],V=b?ti(B):[],Y=b?ii(B,ie,w,!1):[],v=new Set(V.map(g=>g.packageName)),A=Y.filter(g=>!v.has(g.packageName)),R=[...V,...A],U=I?Oi():[];d&&($&&d.startSection("dependencies",P.size>0?"checking outdated catalog dependencies":"scanning duplicates"),x&&d.startSection("security",i.length>0?`scanning ${String(i.length)} packages for advisories`:"no installed packages to scan"),b&&d.startSection("optimization","matching e18e + socket overrides"),I&&d.startSection("runtime","running runtime diagnostics")),d&&I&&d.completeSection("runtime",f("runtime",{duplicates:[],optimizations:[],outdated:[],runtime:U}));const ce=($||x)&&P.size>0?De(s,"outdated",()=>pi(P,G,M,void 0,c,L,X),(g,F)=>{const z=g.outdated.length;return{status:z>0?"warn":"ok",summary:z>0?`${String(z)} outdated · ${H(F)}`:`up to date · ${H(F)}`}}):Promise.resolve({failed:[],ignored:[],outdated:[]}),O=x&&i.length>0?De(s,"vulnerabilities",()=>gi(i.map(g=>({name:g.name,version:g.version}))),(g,F)=>{let z=0;for(const re of g.values())z+=re.length;return{status:z>0?"error":"ok",summary:z>0?`${String(z)} found · ${H(F)}`:`none found · ${H(F)}`}}):Promise.resolve(new Map),W=x&&L&&i.length>0?De(s,"socket",()=>Lt(i.map(g=>({name:g.name,version:g.version})),L),(g,F)=>{let z=0,re=0;for(const Ye of g.values())z+=Ye.alerts.length,Ye.score.overall<Be&&(re+=1);const Ge=z+re;return{status:Ge>0?"warn":"ok",summary:Ge>0?`${String(z)} alert${z===1?"":"s"}, ${String(re)} low-score · ${H(F)}`:`clean · ${H(F)}`}}):Promise.resolve(new Map);let ee,de,ue,he;const pe=ce.catch(g=>(ee=g instanceof Error?g.message:String(g),d||u.warn(`Outdated scan failed: ${ee}`),{failed:[],ignored:[],outdated:[]})),be=O.catch(g=>(de=g instanceof Error?g.message:String(g),d||u.warn(`Vulnerability scan failed: ${de}`),new Map)),y=W.catch(g=>(ue=g instanceof Error?g.message:String(g),d||u.warn(`Socket scan failed: ${ue}`),new Map)),m=d&&$?pe.then(g=>{if(ee){d.failSection("dependencies",ee);return}d.completeSection("dependencies",f("dependencies",{duplicates:D,optimizations:[],outdated:g.outdated,runtime:[]}))}):void 0,k=d&&x?Promise.all([pe,be,y]).then(([g])=>{const F=ee??de??ue;if(F){d.failSection("security",F);return}d.completeSection("security",f("security",{duplicates:[],optimizations:[],outdated:g.outdated,runtime:[]}))}):void 0,Se=(async()=>{if(o&&b&&R.length>0&&await De(s,"codemods",async()=>(await ri(R),R),(g,F)=>{const z=g.filter(re=>re.hasCodemod||re.category==="socket").length;return{status:"ok",summary:`${String(z)} auto-fixable · ${H(F)}`}}).catch(g=>{he=g instanceof Error?g.message:String(g)}),d&&b){if(he){d.failSection("optimization",he);return}d.completeSection("optimization",f("optimization",{duplicates:[],optimizations:R,outdated:[],runtime:[]}))}})(),[$e,xt,Rt]=await Promise.all([pe,be,y]);await Promise.all([m,k,Se]);let Ue=0,He=0;if(x&&L)for(const g of Rt.values())Ue+=g.alerts.length,g.score.overall<Be&&(He+=1);let je=0;if(x){for(const g of $e.outdated)g.vulnerabilities&&g.vulnerabilities.length>0&&(je+=g.vulnerabilities.length);for(const g of xt.values())je+=g.length}return{duplicates:D,installedCount:i.length,optimizations:b?R:[],outdated:$?$e.outdated:[],runtime:U,sections:l,socketIssues:{alerts:Ue,lowScore:He},supplyChain:Cr(p),vulnCount:je,workspaceCount:q.length}},"streamScans"),Tr=C(e=>{switch(e){case"error":return Re(j.failure);case"skip":return S(j.dash);case"warn":return Fe(j.warning);default:return ke(j.success)}},"sectionIcon"),ae=C((e,t)=>{const i=process.stderr.columns??80,s=Math.max(20,Math.min(i-2,60)),o=j.dash.repeat(2),l=`${Tr(t)} ${se(e)}`,d=l.replaceAll(/\[[0-9;]*m/g,"").length,p=Math.max(0,s-d-o.length-2);return`${o} ${l} ${S(j.dash.repeat(p))}`},"heading"),J=C(e=>` ${ke(j.success)} ${e}`,"itemOk"),Q=C(e=>` ${Fe(j.warning)} ${e}`,"itemWarn"),Ve=C(e=>` ${Re(j.failure)} ${e}`,"itemError"),Ct=C(e=>` ${S(j.dash)} ${S(e)}`,"itemSkip"),K=C((e,t,i)=>{const s=`${se(String(e))} ${S(t)}`;return i?`${s} ${S(`(${i})`)}`:s},"countLine"),Ar=C(e=>{if(e.sections.has("dependencies")){if(u.log(""),u.log(ae("Dependencies",ne(e,"dependencies"))),u.log(J(K(e.installedCount,"packages installed"))),e.outdated.length>0){const t=e.outdated.filter(l=>l.updateType==="major").length,i=e.outdated.filter(l=>l.updateType==="minor").length,s=e.outdated.filter(l=>l.updateType==="patch").length,o=[];t>0&&o.push(`${String(t)} major`),i>0&&o.push(`${String(i)} minor`),s>0&&o.push(`${String(s)} patch`),u.log(Q(K(e.outdated.length,"outdated",o.join(", "))))}else u.log(J("All dependencies up to date"));e.duplicates.length>0?u.log(Q(K(e.duplicates.length,"packages with duplicate versions"))):u.log(J("No duplicate dependencies"))}},"displayDependencies"),Ir=C(e=>{e.sections.has("security")&&(u.log(""),u.log(ae("Security",ne(e,"security"))),e.vulnCount>0?u.log(Ve(K(e.vulnCount,`vulnerabilit${e.vulnCount===1?"y":"ies"} found`))):u.log(J("No known vulnerabilities")),e.socketIssues.alerts>0&&u.log(Q(K(e.socketIssues.alerts,`Socket.dev security alert${e.socketIssues.alerts===1?"":"s"}`))),e.socketIssues.lowScore>0&&u.log(Q(K(e.socketIssues.lowScore,`package${e.socketIssues.lowScore===1?"":"s"} with low security score`))),e.socketIssues.alerts===0&&e.socketIssues.lowScore===0&&e.vulnCount===0&&u.log(J("No security issues detected")))},"displaySecurity"),Pr=C(e=>{if(!e.sections.has("optimization"))return;u.log(""),u.log(ae("Optimization",ne(e,"optimization")));const t=St(e.optimizations);if(t.total===0){u.log(J("No optimizations available"));return}t.native>0&&u.log(Q(K(t.native,"replaceable with native APIs"))),t.preferred>0&&u.log(Q(K(t.preferred,"with lighter alternatives"))),t.micro>0&&u.log(Q(K(t.micro,"trivial micro-utilities"))),t.socket>0&&u.log(Q(K(t.socket,"@socketregistry overrides available")))},"displayOptimization"),Dr=C(e=>{u.log(""),u.log(ae("Supply Chain",e.supplyChain.status));for(const t of e.supplyChain.findings){const i=t.severity==="ok"?J(t.label):t.severity==="error"?Ve(t.label):Q(t.label);u.log(i),t.detail&&u.log(` ${S(j.arrow)} ${S(t.detail)}`)}e.supplyChain.status!=="ok"&&u.log(` ${S(j.arrow)} ${S("Configure with security.* in vis.config.ts. See `vis check --security-config` for details.")}`)},"displaySupplyChain"),Or=C(e=>{if(e.sections.has("runtime")){u.log(""),u.log(ae("Runtime",ne(e,"runtime")));for(const t of e.runtime)t.status==="ok"?u.log(J(t.message)):t.status==="skip"?u.log(Ct(t.message)):u.log(Q(t.message))}},"displayRuntime"),Nr=C((e,t)=>{const i=e.vulnCount,s=e.runtime.filter(l=>l.status==="warn").length,o=e.outdated.length+e.duplicates.length+e.optimizations.length+s;if(t){if(i===0&&o===0)u.success(`Everything looks good! ${S(`(${H(e.elapsedMs)})`)}`);else{const l=[];i>0&&l.push(Re(`${String(i)} security`)),o>0&&l.push(Fe(`${String(o)} improvement${o===1?"":"s"}`)),u.log(`${Re(j.failure)} ${l.join(", ")} ${S(`(${H(e.elapsedMs)})`)}`)}return}u.log(""),u.log(ae("Summary","ok")),i===0&&o===0?u.success(`Everything looks good! ${S(`(${H(e.elapsedMs)})`)}`):(i>0&&u.error(`${String(i)} security issue${i===1?"":"s"}`),o>0&&u.log(` ${Te(j.arrow)} ${se(String(o))} ${S(`improvement${o===1?"":"s"} available`)} ${S(`(${H(e.elapsedMs)})`)}`))},"displaySummary"),Mr=C(e=>{const t=[];if(e.outdated.length>0&&t.push("vis update — update outdated dependencies"),(e.vulnCount>0||e.socketIssues.alerts>0)&&t.push("vis audit — detailed security analysis"),e.optimizations.length>0&&t.push("vis optimize — apply optimizations interactively"),e.duplicates.length>0&&t.push("vis dedupe — reduce duplicate versions"),t.length>0){u.log(""),u.log(se("Next steps:"));for(const i of t)u.log(` ${S(j.arrow)} ${i}`)}u.log("")},"displayActions"),Fr=C((e,t)=>{t||(Ar(e),Ir(e),Pr(e),Or(e),Dr(e)),Nr(e,t)},"displayResults"),zr=C((e,t,i,s,o)=>{const l=[],d=e.has("dependencies"),p=e.has("security"),c=e.has("optimization");return(d||p)&&t>0&&l.push({id:"outdated",label:"Outdated catalog dependencies"}),p&&s>0&&l.push({id:"vulnerabilities",label:"Known vulnerabilities (OSV)"}),p&&i&&s>0&&l.push({id:"socket",label:"Socket.dev supply-chain reports"}),c&&o&&l.push({id:"codemods",label:"Codemod availability"}),l},"planScanTasks"),jr=C(e=>{if(u.log(""),u.log(`${se(Te("vis doctor"))} ${S("— project health check")}`),u.log(J(`Detected ${e.packageManagerName} v${e.packageManagerVersion}`)),e.workspaceCount!==void 0&&e.workspaceCount>0&&u.log(J(K(e.workspaceCount,`workspace package${e.workspaceCount===1?"":"s"}`))),e.runtimeFindings.length===0)u.log(J(`Node.js ${e.nodeVersion}`));else{for(const t of e.runtimeFindings){const i=t.severity==="error"?Re:Fe;u.log(Ve(`Runtime: ${i(t.message)}`))}u.log(` ${S(j.arrow)} Run ${ke("vis toolchain install")} to install pinned versions, or ${ke("vis toolchain status")} for the per-tool breakdown.`)}u.log("")},"printBanner"),rn=C(async({logger:e,options:t,visConfig:i,visConfigError:s,workspaceRoot:o})=>{if(!o)throw new Error("Could not determine workspace root.");const l=t.format==="json"||t.json===!0,d=br(t.only,t.skip),p=!!t.quiet,c=!!t.noProgress,$=kr(t.filter);if(d.size===0){u.error("No sections selected. Check your --only / --skip values."),process.exitCode=2;return}const x=Date.now(),b=at(o),I=si(o),f=!!process.stdout.isTTY,w=!l&&f&&!_t&&!p&&!c;!l&&!w&&jr({nodeVersion:process.versions.node,packageManagerName:b.name,packageManagerVersion:b.version,runtimeFindings:I,workspaceCount:void 0});const E=ht(o,st(o).packageManager),Z=ai(o,b.name),q=Z.length,B=!!ct(i?.security?.socket),M=dt(o);if(!l&&!p&&!w){const O=M.length>0?S(` · ${String(M.length)} workspace package${M.length===1?"":"s"}`):"";u.log(`${S("·")} ${S("Found")} ${se(String(q))} ${S(`installed package${q===1?"":"s"}`)}${O}`)}const P=s?{hint:s.file?`Continuing with default settings — fix or regenerate ${s.file} (vis init --force).`:"Continuing with default settings.",message:s.message,severity:"error",title:s.file?`Failed to load ${s.file}`:"Failed to load vis.config"}:void 0,L={bun:"bun.lock",npm:"package-lock.json",pnpm:"pnpm-lock.yaml",yarn:"yarn.lock"}[b.name],X=L?le(o,L):void 0,ie=Zt(o),G=!t.noCache&&!t.fix?ki({configPath:ie,lockfilePath:X,sections:d,socketEnabled:B,workspaceRoot:o}):void 0,D=G?wi(G):void 0,V=D!==void 0;let Y,v;if(w){const O=D?new et({activeSections:d,findings:vt(yt(D),$)}):new et({activeSections:d}),W=Bt(Ut.createElement(gr,{banner:P,fromCache:V,startedAt:x,store:O}),{alternateScreen:!0,exitOnCtrlC:!1,interactive:!0,patchConsole:!0});try{Y=D??await ot({filterPatterns:$,installed:Z,resolveCodemods:!!t.fix,sections:d,store:O,visConfig:i,workspaceRoot:o})}catch(ee){throw W.unmount(),ee}await W.waitUntilExit(),v=O.getSnapshot().pendingAction}else if(D)Y=D;else{const O=zr(d,E.size,B,q,!!t.fix),W=ci(O,{live:!l&&!p&&!c});try{Y=await ot({filterPatterns:$,installed:Z,progress:W,resolveCodemods:!!t.fix,sections:d,visConfig:i,workspaceRoot:o})}finally{W.stop()}}const A={...Y,elapsedMs:Date.now()-x};if(G&&!V)try{vi(G,A)}catch{}const R=wr(A,$);if(l){process.stdout.write(`${JSON.stringify(Sr(R,b.name),void 0,2)}
4
+ `),t.exitCode&&rt(R,!!t.strict)&&(process.exitCode=1);return}V&&!p&&u.log(`${S("·")} Cached results (use --no-cache to refresh)`),$.length>0&&!p&&u.log(`${S("·")} Filter active: ${Te(t.filter??"")}`),Fr(R,p);const U=R.runtime.some(O=>O.id===Oe&&O.status==="warn"),ce=R.sections.has("optimization")&&R.optimizations.length>0;t.fix&&(ce||U)?await Er({force:!!t.fixForce,logger:e,pm:b,recoverOrphans:U,results:R,workspaceRoot:o}):p||Mr(R),v&&(process.stdout.write(`
5
+ `),process.stdout.write(`${se("→ ")}${v.description}
6
+ `),v.configSnippet?(process.stdout.write(`
7
+ `),process.stdout.write(`${S(v.configSnippet)}
8
+ `)):process.stdout.write(` ${Te(v.command)}
9
+ `),process.stdout.write(`
10
+ `)),t.exitCode&&rt(R,!!t.strict)&&(process.exitCode=1)},"execute"),Er=C(async e=>{const{force:t,logger:i,pm:s,recoverOrphans:o,results:l,workspaceRoot:d}=e;u.log(""),u.log(ae("Applying fixes","ok"));const p=l.optimizations.filter(f=>f.category==="socket"&&f.overrideSpec).map(f=>({original:f.packageName,spec:f.overrideSpec})),c=l.optimizations.filter(f=>f.category!=="socket"&&f.hasCodemod),$=l.optimizations.filter(f=>f.category!=="socket"&&!f.hasCodemod);let x=!1,b=0;const I=[];if(o){const f=Ri({force:t});if(f.killed.length>0&&(u.success(`Cleaned up ${String(f.killed.length)} orphaned process${f.killed.length===1?"":"es"} (PIDs: ${f.killed.join(", ")}).`),x=!0),f.failed.length>0){const w=t?"":" Re-run with `--fix --fix-force` to escalate to SIGKILL.";u.warn(`Could not signal ${String(f.failed.length)} orphan${f.failed.length===1?"":"s"}: ${f.failed.map(E=>`${String(E.pid)} (${E.reason})`).join(", ")}.${w}`)}}if(p.length>0){const f=ni(d,le(d,"package.json"),p,s);f.added.length>0&&(u.success(`Added ${String(f.added.length)} security override${f.added.length===1?"":"s"}.`),x=!0),f.updated.length>0&&(u.success(`Updated ${String(f.updated.length)} override${f.updated.length===1?"":"s"}.`),x=!0)}for(const f of c)try{const w=await oi(d,f.packageName);w.filesChanged>0&&(u.success(`${f.packageName}: ${String(w.filesChanged)} file${w.filesChanged===1?"":"s"} updated`),b+=1,x=!0)}catch(w){const E=w instanceof Error?w.message:String(w);I.push({error:E,package:f.packageName}),u.warn(`${f.packageName}: codemod failed — ${E}`)}p.length>0&&(u.log(`${Te(j.arrow)} Running ${s.name} install to update lockfile…`),Vt(s,{dev:!1,filter:[],force:!1,frozenLockfile:!1,ignoreScripts:!1,lockfileOnly:!1,noOptional:!1,offline:!1,prod:!1,recursive:!1,silent:!1,workspaceRoot:!1},d,i),x=!0),u.log(""),x?u.success(`Fixes applied. ${b>0?`${String(b)} codemod${b===1?"":"s"} applied.`:""}`.trim()):u.log(Ct("No auto-fixable items in the current run.")),I.length>0&&u.warn(`${String(I.length)} codemod${I.length===1?"":"s"} failed (run ${ke("vis optimize")} for the interactive picker).`),$.length>0&&u.notice(`${String($.length)} optimization${$.length===1?"":"s"} need manual review (no codemod). Run ${ke("vis optimize")} to inspect them.`)},"runFixes");export{rn as default};