@visulima/vis 1.0.0-alpha.10 → 1.0.0-alpha.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +185 -42
- package/LICENSE.md +586 -0
- package/README.md +26 -4
- package/dist/config/index.d.ts +1739 -0
- package/dist/config/index.js +1 -0
- package/dist/generate/index.d.ts +1 -1
- package/dist/packem_chunks/applyDefaults.js +2 -0
- package/dist/packem_chunks/bin.js +232 -60
- package/dist/packem_chunks/doctor-probe.js +2 -0
- package/dist/packem_chunks/fix.js +11 -53
- package/dist/packem_chunks/handler.js +1 -1
- package/dist/packem_chunks/handler10.js +2 -1
- package/dist/packem_chunks/handler11.js +1 -1
- package/dist/packem_chunks/handler12.js +5 -2
- package/dist/packem_chunks/handler13.js +1 -1
- package/dist/packem_chunks/handler14.js +18 -5
- package/dist/packem_chunks/handler15.js +20 -1
- package/dist/packem_chunks/handler16.js +1 -20
- package/dist/packem_chunks/handler17.js +1 -1
- package/dist/packem_chunks/handler18.js +1 -1
- package/dist/packem_chunks/handler19.js +1 -1
- package/dist/packem_chunks/handler2.js +2 -1
- package/dist/packem_chunks/handler20.js +5 -1
- package/dist/packem_chunks/handler21.js +1 -1
- package/dist/packem_chunks/handler22.js +1 -5
- package/dist/packem_chunks/handler23.js +5 -1
- package/dist/packem_chunks/handler24.js +1 -1
- package/dist/packem_chunks/handler25.js +3 -5
- package/dist/packem_chunks/handler26.js +1 -1
- package/dist/packem_chunks/handler27.js +1 -3
- package/dist/packem_chunks/handler28.js +7 -1
- package/dist/packem_chunks/handler29.js +22 -6
- package/dist/packem_chunks/handler3.js +4 -2
- package/dist/packem_chunks/handler30.js +3 -23
- package/dist/packem_chunks/handler31.js +1 -3
- package/dist/packem_chunks/handler32.js +2 -2
- package/dist/packem_chunks/handler33.js +24 -23
- package/dist/packem_chunks/handler34.js +2 -2
- package/dist/packem_chunks/handler35.js +3 -19
- package/dist/packem_chunks/handler36.js +22 -428
- package/dist/packem_chunks/handler37.js +428 -22
- package/dist/packem_chunks/handler38.js +20 -20
- package/dist/packem_chunks/handler39.js +21 -21
- package/dist/packem_chunks/handler4.js +2 -4
- package/dist/packem_chunks/handler40.js +22 -3
- package/dist/packem_chunks/handler41.js +6 -10
- package/dist/packem_chunks/handler42.js +5 -153
- package/dist/packem_chunks/handler43.js +10 -42
- package/dist/packem_chunks/handler44.js +153 -3
- package/dist/packem_chunks/handler45.js +25 -27
- package/dist/packem_chunks/handler46.js +3 -0
- package/dist/packem_chunks/handler47.js +27 -0
- package/dist/packem_chunks/handler48.js +42 -0
- package/dist/packem_chunks/handler5.js +8 -2
- package/dist/packem_chunks/handler6.js +1 -13
- package/dist/packem_chunks/handler7.js +1 -8
- package/dist/packem_chunks/handler8.js +1 -1
- package/dist/packem_chunks/handler9.js +1 -1
- package/dist/packem_chunks/heal-accept.js +10 -0
- package/dist/packem_chunks/heal.js +14 -0
- package/dist/packem_chunks/index.js +3 -3
- package/dist/packem_chunks/tar.js +3 -0
- package/dist/packem_shared/ai-analysis-hm8d2W7z.js +67 -0
- package/dist/packem_shared/{ai-cache-Bynt6Y9x.js → ai-cache-DoiF80AR.js} +1 -1
- package/dist/packem_shared/ai-fix-nn4zOE95.js +43 -0
- package/dist/packem_shared/cache-directory-CwHlJhgx.js +1 -0
- package/dist/packem_shared/dependency-scan-COr5n63B.js +2 -0
- package/dist/packem_shared/{docker-BcfqH4Av.js → docker-D6OGr5_S.js} +1 -1
- package/dist/packem_shared/{failure-log-DqYen0LC.js → failure-log-iUVLf6ts.js} +1 -1
- package/dist/packem_shared/flakiness-D9wf0t56.js +1 -0
- package/dist/packem_shared/giget-CcEy_Elm.js +2 -0
- package/dist/packem_shared/index-DH-5hsrC.js +1 -0
- package/dist/packem_shared/otel-DxDUPJJH.js +6 -0
- package/dist/packem_shared/otelPlugin-CQq6poq8.js +1 -0
- package/dist/packem_shared/registry-CkubDdiY.js +2 -0
- package/dist/packem_shared/run-summary-utils-BfBvjzhY.js +1 -0
- package/dist/packem_shared/{runtime-check-CGHal8SO.js → runtime-check-BXZ43CBW.js} +1 -1
- package/dist/packem_shared/{selectors-CfH9ZY08.js → selectors-BylODRiM.js} +1 -1
- package/dist/packem_shared/toolchain-BgBOUHII.js +5 -0
- package/dist/packem_shared/typosquats-CcZl99B1.js +1 -0
- package/dist/packem_shared/verify-Baj5mFJ7.js +1 -0
- package/dist/packem_shared/vis-update-app-D1jl0UZZ.js +1 -0
- package/index.js +54 -53
- package/package.json +34 -26
- package/schemas/project.schema.json +739 -299
- package/schemas/vis-config.schema.json +3383 -278
- package/skills/vis/SKILL.md +96 -0
- package/templates/buildkite-ci/.buildkite/pipeline.yml.tera +85 -0
- package/templates/buildkite-ci/template.yml +20 -0
- package/dist/errors/index.d.ts +0 -26
- package/dist/errors/index.js +0 -1
- package/dist/packem_chunks/config.js +0 -2
- package/dist/packem_shared/VisConfigCycleError-CAYNC7d-.js +0 -1
- package/dist/packem_shared/VisConfigError-B5LP1zRf.js +0 -1
- package/dist/packem_shared/VisConfigLoadError-CeqBSd2Z.js +0 -2
- package/dist/packem_shared/VisConfigNotFoundError-DZ9KC527.js +0 -5
- package/dist/packem_shared/VisUpdateApp-D-L4_-Iu.js +0 -1
- package/dist/packem_shared/_commonjsHelpers-D6W6KoPK.js +0 -1
- package/dist/packem_shared/ai-analysis-CGuy7dfE.js +0 -67
- package/dist/packem_shared/cache-directory-D72ZEag2.js +0 -1
- package/dist/packem_shared/catalog-BVPerCwG.js +0 -12
- package/dist/packem_shared/dependency-scan-Du0tBu64.js +0 -2
- package/dist/packem_shared/flakiness-DSIHZGBT.js +0 -1
- package/dist/packem_shared/run-summary-utils-C24Aaf9E.js +0 -1
- package/dist/packem_shared/target-merge-DNa-6eWu.js +0 -1
- package/dist/packem_shared/toolchain-DQfTQY8E.js +0 -5
- package/dist/packem_shared/typosquats-DOR8izpX.js +0 -1
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);
|
|
3
|
-
|
|
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(`
|
|
1
|
+
var re=Object.defineProperty;var b=(e,t)=>re(e,"name",{value:t,configurable:!0});import{createRequire as ne}from"node:module";import{dim as v,cyan as se,yellow as E,red as oe,green as W}from"@visulima/colorize";import{isAccessibleSync as D,readJsonSync as ae,writeFileSync as ce,readFileSync as le}from"@visulima/fs";import{isAbsolute as C,relative as H,resolve as j,join as B}from"@visulima/path";import{redact as de}from"@visulima/redact";import{fingerprint as k,listRules as K,listRequiredValidators as ue,scan as Q,scanFiles as fe,inspectRuleset as pe}from"@visulima/secret-scanner";import{p as m}from"./bin.js";import{InteractiveManager as ge,InteractiveStreamHook as V}from"@visulima/interactive-manager";import{Spinner as me}from"@visulima/spinner";const ie=ne(import.meta.url),F=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,G=b(e=>{if(typeof F<"u"&&F.versions&&F.versions.node){const[t,i]=F.versions.node.split(".").map(Number);if(t>22||t===22&&i>=3||t===20&&i>=16)return F.getBuiltinModule(e)}return ie(e)},"__cjs_getBuiltinModule"),{pathToFileURL:X}=G("node:url"),{execFileSync:he}=G("node:child_process");var we=Object.defineProperty,ve=b((e,t)=>we(e,"name",{value:t,configurable:!0}),"r$1");const Y=ve((e={})=>{const t=new ge(new V(process.stdout),new V(process.stderr));return new me(e,t)},"createSpinner");var $e=Object.defineProperty,I=b((e,t)=>$e(e,"name",{value:t,configurable:!0}),"s");const ye=I((e,t)=>{if(!C(e))return e;const i=H(t,e);return i===""||i.startsWith("..")?e:i},"toRelative"),A=I((e,t)=>{const i=ye(e.file,t);return i===e.file?e:{...e,file:i}},"toRelativeFinding"),Z=I(e=>{if(!D(e))return[];try{const t=ae(e);return Array.isArray(t)?t:[]}catch{return[]}},"readBaseline"),Se=I((e,t,i)=>{const n=Z(t).map(o=>A(o,i)),r=new Set(n.map(o=>k(o))),a=e.map(o=>A(o,i)),l=new Set(a.map(o=>k(o)));return{fresh:a.filter(o=>!r.has(k(o))),resolved:n.filter(o=>!l.has(k(o))),surviving:a.filter(o=>r.has(k(o)))}},"diffBaseline"),ee=I((e,t,i,n={})=>{const r=e.map(l=>A(l,i));let a;if(n.replace)a=r;else{const l=Z(t).map(s=>A(s,i)),o=new Set;a=[];for(const s of[...l,...r]){const c=k(s);o.has(c)||(o.add(c),a.push(s))}}return ce(t,`${JSON.stringify(a,null,4)}
|
|
2
|
+
`),a.length},"writeBaseline");var be=Object.defineProperty,h=b((e,t)=>be(e,"name",{value:t,configurable:!0}),"a$1");const U=1,xe=h(e=>{const t=new Map;for(const i of e){const n=t.get(i.file);n?n.push(i):t.set(i.file,[i])}return t},"groupByFile"),ke=h(e=>{try{return le(e).split(/\r?\n/)}catch{return}},"loadLines"),je=h((e,t,i)=>{const n=Math.max(1,t);return`${e.slice(0,n-1).replaceAll(/[^\t]/g," ")}${"^".repeat(Math.max(1,i))}`},"caretFor"),Ce=h((e,t,i,n={})=>{if(e.length===0)return i?v("No secrets detected."):"No secrets detected.";const r=i?{cyan:se,dim:v,green:W,red:oe,yellow:E}:{cyan:h(o=>o,"cyan"),dim:h(o=>o,"dim"),green:h(o=>o,"green"),red:h(o=>o,"red"),yellow:h(o=>o,"yellow")},a=[],l=xe(e);for(const[o,s]of l){const c=H(t,o)||o;a.push(r.cyan(c));const p=n.redact?void 0:ke(o);for(const d of s){const x=[d.source,d.confidence].filter(Boolean).join(", "),S=x?` ${r.dim(`(${x})`)}`:"",w=d.alternateMatches&&d.alternateMatches.length>0?` ${r.dim(`also: ${d.alternateMatches.join(", ")}`)}`:"";let u="";switch(d.validation){case"error":{u=` ${r.yellow("! error")}`;break}case"rejected":{u=` ${r.red("✗ rejected")}`;break}case"skipped":{u=` ${r.dim("— unverifiable")}`;break}case"verified":{u=` ${r.green("✓ verified")}`;break}}if(a.push(` ${r.red("✖")} ${r.yellow(`[${d.ruleId}]`)}${S}${u} ${r.dim(`line ${String(d.startLine)}:${String(d.startColumn)}`)}${w}`),p){const R=Math.max(0,d.startLine-1-U),$=Math.min(p.length,d.startLine+U);for(let y=R;y<$;y+=1){const q=String(y+1).padStart(4," "),L=y+1===d.startLine,g=L?r.red("▶"):" ";if(a.push(` ${g} ${r.dim(q)} │ ${p[y]??""}`),L){const N=Math.max(1,(d.endColumn??d.startColumn+1)-d.startColumn),te=je(p[y]??"",d.startColumn,N);a.push(` ${r.dim(" │ ")}${r.red(te)}`)}}}a.push("")}}return a.join(`
|
|
3
|
+
`).trimEnd()},"formatText"),Re=h((e,t)=>{if(!C(e))return e.replaceAll("\\","/");try{return X(e).toString()}catch{return`file://${j(t,e).replaceAll("\\","/")}`}},"toSarifUri"),Fe=h((e,t=100)=>e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`,"shortText"),Me=h((e,t,i=process.cwd(),n=[])=>{const r=new Map(n.map(s=>[s.id,s])),a=new Set;for(const s of e)a.add(s.ruleId);const l=[...new Set([...r.keys(),...a])].sort((s,c)=>s.localeCompare(c)),o=new Map(l.map((s,c)=>[s,c]));return JSON.stringify({$schema:"https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json",runs:[{originalUriBaseIds:{SRCROOT:{uri:X(i).toString()}},results:e.map(s=>{const c={};return s.source&&(c.source=s.source),s.confidence&&(c.confidence=s.confidence),s.alternateMatches&&s.alternateMatches.length>0&&(c.alternateRules=s.alternateMatches),s.validation&&(c.validation=s.validation),{level:"error",locations:[{physicalLocation:{artifactLocation:{uri:Re(s.file,i),uriBaseId:C(s.file)?void 0:"SRCROOT"},region:{endColumn:s.endColumn,endLine:s.endLine,snippet:{text:s.match},startColumn:s.startColumn,startLine:s.startLine}}}],message:{text:s.description||s.ruleId},properties:Object.keys(c).length>0?c:void 0,ruleId:s.ruleId,ruleIndex:o.get(s.ruleId)??-1}}),tool:{driver:{informationUri:"https://visulima.com/packages/secret-scanner",name:"visulima-secret-scanner",rules:l.map(s=>{const c=r.get(s),p=c?.description??`Detected by rule \`${s}\``,d={};return c?.tags&&c.tags.length>0&&(d.tags=c.tags),c?.source&&(d.source=c.source),c?.confidence&&(d.confidence=c.confidence),{defaultConfiguration:{level:"error"},fullDescription:{text:p},helpUri:"https://visulima.com/packages/secret-scanner",id:s,name:s,properties:Object.keys(d).length>0?d:void 0,shortDescription:{text:Fe(p)}}}),version:t}}}],version:"2.1.0"},void 0,2)},"formatSarif");var Be=Object.defineProperty,T=b((e,t)=>Be(e,"name",{value:t,configurable:!0}),"n");const O=T((e,t)=>{try{return he("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).trim()}catch{return""}},"runGit"),_=T(e=>e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),"splitFiles"),Ae=T(e=>_(O(e,["diff","--cached","--name-only","--diff-filter=ACMR"])).map(t=>C(t)?t:B(e,t)),"stagedFiles"),z=T((e,t)=>{const i=O(e,["diff","--name-only","--diff-filter=ACMR",`${t}...HEAD`]),n=_(i);if(n.length===0){const r=O(e,["diff","--name-only","--diff-filter=ACMR",t]);return _(r).map(a=>C(a)?a:B(e,a))}return n.map(r=>C(r)?r:B(e,r))},"filesSince"),P=T(e=>O(e,["rev-parse","--show-toplevel"]).length>0,"hasGit");var Ie=Object.defineProperty,f=b((e,t)=>Ie(e,"name",{value:t,configurable:!0}),"c");const M=".secrets-baseline.json",J=f(e=>e?Array.isArray(e)?e:[e]:[],"toArray"),Te=f(e=>{const t=new Set(["json","sarif","text"]);if(e&&!t.has(e))throw new Error(`--format must be one of: ${[...t].join(", ")} (got "${e}")`);return e??"text"},"validateFormat"),qe=f(e=>{if(e===void 0)return;const t=new Set(["high","low","medium"]);if(!t.has(e))throw new Error(`--min-confidence must be one of: ${[...t].join(", ")} (got "${e}")`);return e},"validateConfidence"),Le=f(async(e,t)=>{const i=await K(e);process.stdout.write(`${String(i.length)} rules loaded
|
|
8
4
|
|
|
9
|
-
`)
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
`)
|
|
13
|
-
`)
|
|
14
|
-
|
|
15
|
-
|
|
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()}
|
|
5
|
+
`);for(const n of i){const r=t?E(n.id):n.id,a=n.tags.length>0?` ${t?v(`[${n.tags.join(", ")}]`):`[${n.tags.join(", ")}]`}`:"";if(process.stdout.write(`${r}${a}
|
|
6
|
+
${n.description}
|
|
7
|
+
`),n.keywords.length>0){const l=`keywords: ${n.keywords.slice(0,6).join(", ")}${n.keywords.length>6?", ...":""}`;process.stdout.write(` ${t?v(l):l}
|
|
8
|
+
`)}process.stdout.write(`
|
|
9
|
+
`)}},"printListRules"),Ne=f(async(e,t)=>{const i=await ue(e);if(i.length===0){process.stdout.write(t?`${v("No non-HTTP validators required by the current ruleset.")}
|
|
10
|
+
`:`No non-HTTP validators required by the current ruleset.
|
|
11
|
+
`);return}process.stdout.write(`${String(i.length)} non-HTTP validator type(s) referenced by the current ruleset:
|
|
19
12
|
|
|
20
|
-
${
|
|
21
|
-
|
|
22
|
-
|
|
13
|
+
`);for(const n of i){const r=t?E(n.displayName):n.displayName,a=`(${n.type}, ${String(n.ruleCount)} rule${n.ruleCount===1?"":"s"})`;process.stdout.write(`${r} ${t?v(a):a}
|
|
14
|
+
`),process.stdout.write(` ${n.summary}
|
|
15
|
+
`);const l=n.packageName?`install: npm add ${n.packageName}`:"no driver — bespoke implementation required";process.stdout.write(` ${t?v(l):l}
|
|
16
|
+
|
|
17
|
+
`)}},"printListValidators"),Oe=f(async(e,t,i)=>{const n=B(e,M);if(!i&&D(n)){m.warn(`Detected existing ${M} — refusing to overwrite. Delete it first to re-init.`),process.exitCode=1;return}m.info(i?"[dry-run] Previewing init — no files will be written.":"Scanning workspace to seed baseline…");const r=Y();r.start("scanning");let a;try{a=await Q([e],t),r.succeed()}catch(o){throw r.failed(),o}if(i){m.info(`[dry-run] Would create ${M} with ${String(a.length)} finding(s).`);return}const l=ee(a,n,e,{replace:!0});m.success(`Wrote ${M} (${String(l)} findings).`),m.notice("Commit it. Use `vis secrets --baseline .secrets-baseline.json` in CI. Add path patterns to .gitignore to exclude directories from scanning.")},"runInit"),Ee=f((e,t,i)=>{const n=t??{},r=f(u=>u?j(i,u):void 0,"resolvePath"),a=f((u,R)=>{const $=J(u);return $.length>0?$:R},"pickList"),l=a(e.enableRule,n.rules?.enable),o=a(e.excludeRule,n.rules?.exclude),s=a(e.includeRule,n.rules?.include),c=a(e.exclude,n.walk?.excludePatterns),p=J(e.excludeFrom).map(u=>j(i,u)),d=p.length>0?p:n.walk?.excludeFromFiles?.map(u=>j(i,u)),x=r(e.baseline)??r(n.baseline),S=r(e.config)??r(n.config?.path),w=qe(e.minConfidence??n.config?.minConfidence);return{baseline:x,concurrency:e.concurrency,config:{extendBundled:e.noExtendBundled?!1:n.config?.extendBundled,inline:n.config?.inline,minConfidence:w,onlyVerified:e.onlyVerified??n.config?.onlyVerified??!1,path:S,validate:e.validate??n.config?.validate??!1},redact:e.redact??n.redact,rules:{enable:l,exclude:o,include:s},verbose:e.verbose??!1,walk:{excludeFromFiles:d,excludePatterns:c,gitignore:e.noGitignore?!1:n.walk?.gitignore??!0,includeHidden:e.includeHidden??n.walk?.includeHidden,maxFileSize:e.maxSize??n.walk?.maxFileSize}}},"resolveScanOptions"),Pe=f(e=>{process.stderr.write(`${v("baseline diff: ")}${W(`+${String(e.fresh.length)} new`)} · ${E(`${String(e.surviving.length)} unchanged`)} · ${v(`-${String(e.resolved.length)} resolved`)}
|
|
18
|
+
`)},"printDiff"),_e=f(async(e,t,i)=>{if(e.staged){if(!P(i))throw new Error("--staged requires a git working tree, and none was detected.");return{files:Ae(i)}}if(e.since){if(!P(i))throw new Error("--since requires a git working tree, and none was detected.");return{files:z(i,e.since)}}if(e.affected){if(!P(i))return m.warn("--affected requires git; falling back to full scan"),{paths:t&&t.length>0?t.map(r=>j(i,r)):[i]};const n=process.env.VIS_BASE??"HEAD~1";return{files:z(i,n)}}return{paths:t&&t.length>0?t.map(n=>j(i,n)):[i]}},"chooseScanPaths"),De=f((e,t,i,n,r,a,l)=>{switch(t){case"json":{const o=e.map(s=>A(s,i));process.stdout.write(`${JSON.stringify(o,null,2)}
|
|
19
|
+
`);break}case"sarif":{process.stdout.write(`${Me(e,r,i,a)}
|
|
20
|
+
`);break}default:process.stdout.write(`${Ce(e,i,n,{redact:l})}
|
|
21
|
+
`)}},"emitFindings"),Ye=f(async({argument:e,options:t,visConfig:i,workspaceRoot:n})=>{const r=t,a=e,l=n??process.cwd(),o=!r.quiet&&process.stdout.isTTY,s=i?.secrets,c=Ee(r,s,l),p="0.0.0-alpha";if(r.listRules){await Le(c,o);return}if(r.listValidators){await Ne(c,o);return}if(r.init){await Oe(l,c,r.dryRun??!1);return}const d=await _e(r,a??[],l);if(d.files?.length===0){r.quiet||m.success("No files to scan.");return}const x=!r.quiet&&!["json","sarif"].includes(r.format??"text"),S=Y({verbose:x});S.start("scanning for secrets");let w;try{w=d.files===void 0?await Q(d.paths??[l],c):await fe(d.files,c),S.succeed()}catch(g){throw S.failed(),new Error(`secret scan failed: ${g instanceof Error?g.message:String(g)}`,{cause:g})}if(r.verbose){const g=await pe(c);if(g.length>0){m.warn(`${String(g.length)} rule(s) skipped due to invalid regex. First few:`);for(const N of g.slice(0,5))process.stderr.write(` - ${N.ruleId}: ${N.reason}
|
|
22
|
+
`)}}const u=c.baseline??B(l,M),R=!r.quiet&&D(u);if(r.updateBaseline){const g=ee(w,u,l,{replace:r.replaceBaseline});m.success(`Baseline updated: ${H(l,u)||u} now contains ${String(g)} entries.`);return}const $=Te(r.format),y=$==="sarif"?await K(c).catch(()=>[]):[],q=c.redact===!0,L=q?de(w,["match","secret"]):w;if(De(L,$,l,o,p,y,q),$==="text"&&R&&Pe(Se(w,u,l)),w.length>0){r.quiet||(m.warn(`${String(w.length)} potential secret(s) found`),m.notice("Suppress individual lines with `gitleaks:allow` / `secret-scanner:allow`, or run `vis secrets --update-baseline`.")),process.exitCode=1;return}r.quiet||m.success("No secrets detected.")},"execute");export{Ye as default};
|
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
var
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
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 z}from"@visulima/fs";import{join as l}from"@visulima/path";import{ap as G,aq as ae,ar as le,as as ce,at as fe,au as ue,ao as de,av as pe,aw as K,ax as J,ay as U,az as Y}from"./bin.js";import{readTomlSync as ge}from"@visulima/fs/toml";const se=te(import.meta.url),F=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,B=$(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:V,statSync:C,writeFileSync:S,unlinkSync:ne,rmSync:re,chmodSync:ie}=B("node:fs"),{cwd:j}=F,{createInterface:oe}=B("node:readline"),{spawnSync:w}=B("node:child_process");var he=Object.defineProperty,N=$((e,t)=>he(e,"name",{value:t,configurable:!0}),"c$2");const me=/^# ([^:\s]\S*)(?::\s+(.+))?$/,ke=N(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 i=me.exec(r);if(i){n&&t.push(n),n={command:"",id:i[1]??"",...i[2]?{name:i[2]}:{}};continue}n?n.command=n.command.length>0?`${n.command}
|
|
3
|
+
${r}`:r:n={command:r,id:"(custom)"}}return n&&t.push(n),t},"parseStageScript"),ye=N((e,t)=>{const s=l(e,t),n=[],r=new Set(G);if(y(s))for(const i of V(s)){if(i.startsWith(".")||i==="_"||!r.has(i))continue;const o=l(s,i);if(!C(o).isFile())continue;const a=A(o),c=ke(a);n.push({blocks:c,rawLineCount:a.split(`
|
|
4
|
+
`).length,stage:i})}return n.sort((i,o)=>i.stage.localeCompare(o.stage)),{hooksDirectory:t,stages:n}},"listHooks"),be=N(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 i=n.command.split(`
|
|
5
|
+
`).find(o=>o.trim()!=="");if(i){const o=i.length>120?`${i.slice(0,117)}...`:i;t.push(` ${o}`)}}return t},"formatListResult"),we=N((e,t)=>{const s=ye(j(),e);for(const n of be(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"]},ve=["binary","directory","executable","non-executable","symlink","text"],$e={bash:["bash","shell"],node:["javascript"],nodejs:["javascript"],perl:["perl"],python:["python"],python3:["python","python3"],ruby:["ruby"],sh:["shell"],zsh:["shell","zsh"]},Ee=["check-json","check-merge-conflict","end-of-file-fixer","mixed-line-ending","trailing-whitespace"],Se=[...Object.keys(xe),...Object.values($e).flat(),...ve],Re=["#!/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=Re.join(`
|
|
6
|
+
`);var Fe=Object.defineProperty,d=$((e,t)=>Fe(e,"name",{value:t,configurable:!0}),"a$1");const je=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"]]),Ae=/[<>=!~]=/,Me=/github\.com[/:]([^/\s]+\/[^/\s.]+)/i,X=`node "$(dirname "$0")/.builtins/${E}"`,Oe="# Generated by `vis hook migrate` from prek",v=d(e=>`'${e.replaceAll("'",String.raw`'\''`)}'`,"shellQuote"),L=d(e=>{for(const t of ae)if(y(l(e,t)))return t},"detectPrekConfig"),Ie=d(e=>le[e]??e,"mapPrekStage"),De=d(e=>Me.exec(e)?.[1]??e,"normalizeRepoKey"),Pe=d(e=>{if(Ae.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(Se),Te=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"),Ce=d((e,t)=>(e.stages&&e.stages.length>0?e.stages:t??["pre-commit"]).map(s=>Ie(s)),"resolveStages"),We=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,...We(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"),Be=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 i=Pe(r);if(!i){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:i.name,raw:r,version:i.version})}},"collectAdditionalDeps"),He=d(e=>{const t=new Map,s=[],n=[],r=[],i=[];let o=!1;(e.files||e.exclude)&&n.push("top-level files/exclude filter dropped — apply it per hook if needed");for(const c of e.repos??[]){const f=c.repo??"<unknown>",b=f==="local",k=b?void 0:De(f);for(const h of c.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:f});continue}if(p!=="fail"&&!h.entry){s.push({hookId:g,reason:"missing `entry`",repo:f});continue}}else if(k&&(M=je.get(`${k}#${g}`)),!M){s.push({hookId:g,reason:`remote repo "${f}"@${c.rev??"?"} has no bundled equivalent — run via prek or replace with a system command`,repo:f});continue}Le(h,g,i,r);const O=Te(h);O.length>0&&n.push(`hook "${g}": unsupported types ${O.join(", ")} — those entries are ignored by the runner`);const I=Ce(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:f});continue}let x=Be(h,p,M);x.startsWith(X)&&(o=!0),h.verbose&&(x=`(set -x; ${x})`);const D=`${`# ${g}${h.name?`: ${h.name}`:""}`}
|
|
7
|
+
${x}`,u=t.get(p);u?u.push(D):t.set(p,[D])}}}const a=new Map;for(const[c,f]of t){const b=["#!/usr/bin/env sh",Oe];e.fail_fast&&b.push("set -e"),b.push("",f.join(`
|
|
5
8
|
|
|
6
|
-
|
|
7
|
-
`)
|
|
8
|
-
|
|
9
|
-
`)
|
|
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
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
${String(
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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};
|
|
9
|
+
`),""),a.set(c,b.join(`
|
|
10
|
+
`))}return{additionalDeps:i,droppedFilters:n,manualSteps:r,scripts:a,skippedHooks:s,usesRunner:o}},"convertPrekConfig"),qe=d(e=>{const t=de(e);if(t&&typeof t=="object")return t},"parsePrekConfig"),Ve=d(e=>{if(e.endsWith(".toml")){const s=ge(e);return s&&typeof s=="object"?s:void 0}const t=A(e);return qe(t)},"loadPrekConfig"),ze=d((e,t,s)=>{const n=l(e,"package.json"),r=[],i=[];if(!y(n)||t.length===0)return{added:r,skipped:i};const o=A(n),a=JSON.parse(o),c=a.devDependencies??{},f=a.dependencies??{};for(const k of t){if(k.name in c||k.name in f){i.push(k.name);continue}c[k.name]=k.version,r.push(k.name)}if(r.length===0)return{added:r,skipped:i};a.devDependencies=c;const b=pe(n,o,{defaultIndent:" ",useEditorconfig:s});return S(n,`${JSON.stringify(a,void 0,b)}
|
|
11
|
+
`,"utf8"),{added:r,skipped:i}},"mergeAdditionalDependencies"),Ge=d((e,t)=>{const s=l(e,t,".builtins");z(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: ${Ee.join(", ")}`,""].join(`
|
|
12
|
+
`),"utf8")},"writeRunnerAssets"),Ke=d((e,t)=>{w("prek",["--version"],{cwd:e,encoding:"utf8"}).status===0?w("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=L(e),i=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 o=l(e,r),a=A(o),c=Ve(o);if(!c)return{isError:!0,message:`Could not parse ${r}`};const{additionalDeps:f,droppedFilters:b,manualSteps:k,scripts:h,skippedHooks:g,usesRunner:M}=He(c);if(h.size===0&&g.length===0)return{isError:!0,message:`${r} has no hooks to migrate`};if(!i){const u=w("git",["config","--local","core.hooksPath"],{cwd:e,encoding:"utf8"});if(u.status===0){const T=u.stdout?.toString().trim();T&&(T.includes(".prek")||T.includes("prek-hooks"))&&w("git",["config","--local","--unset","core.hooksPath"],{cwd:e})}const R=K(t);if(R.isError)return R;R.message&&s.info(R.message)}const O=l(e,t);i||z(O),M&&(i?s.info(` (would write) ${t}/.builtins/${E}`):(Ge(e,t),s.info(` Wrote ${t}/.builtins/${E}`)));let I=0;for(const[u,R]of h)i?s.info(` (would write) ${t}/${u} (${R.split(`
|
|
13
|
+
`).length} lines)`):(S(l(O,u),R,{mode:493}),s.info(` Wrote ${t}/${u}`)),I+=1;const{added:p,skipped:x}=i?{added:f.map(u=>u.name),skipped:[]}:ze(e,f,n.useEditorconfig);if(p.length>0){const u=i?"would add":"Added";s.info(`${u} ${p.length} package${p.length===1?"":"s"} to devDependencies: ${p.join(", ")}`),i||s.info("Run your package manager's install (e.g. `pnpm install`) to pick up the new devDependencies.")}x.length>0&&s.info(`Skipped ${x.length} already-declared package${x.length===1?"":"s"}: ${x.join(", ")}`),i||Ke(e,s);const D=`${o}.bak`;if(i?s.info(` (would remove) ${r} and back it up to ${r}.bak`):(y(D)||S(D,a,"utf8"),ne(o),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 u of g)s.warn(` - ${u.repo}::${u.hookId} — ${u.reason}`)}if(b.length>0){s.warn("Partial filter translations:");for(const u of b)s.warn(` - ${u}`)}if(k.length>0){s.warn("Manual follow-up required:");for(const u of k)s.warn(` - ${u}`)}return{isError:!1,message:`${i?"would migrate":"Migration complete:"} ${I} stage script${I===1?"":"s"} ${i?"into":"written to"} ${t}/`}},"migrateFromPrek");var Je=Object.defineProperty,Z=$((e,t)=>Je(e,"name",{value:t,configurable:!0}),"a");const Ue="pre-commit",Ye=Z((e,t,s,n)=>{const r=s.stage??Ue,i=l(e,t,r);if(!y(i))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 o=s.lastCommit?"HEAD~1":s.fromRef,a=s.lastCommit?"HEAD":s.toRef;if(o&&!a)throw new Error("--from-ref requires --to-ref");if(a&&!o)throw new Error("--to-ref requires --from-ref");const c={...process.env};s.allFiles&&(c.VIS_HOOK_ALL_FILES="1"),o&&(c.VIS_HOOK_FROM_REF=o),a&&(c.VIS_HOOK_TO_REF=a),n.info(`Running ${t}/${r}${s.allFiles?" (--all-files)":""}${o?` (${o}..${a})`:""}`);const f=w("sh",["-e",i],{cwd:e,env:c,stdio:"inherit"});if(f.error)throw f.error;return f.status??1},"runHookStage"),Xe=Z((e,t,s)=>{const n=Ye(j(),e,t,s);if(n!==0)throw new Error(`Hook stage exited with code ${n}`)},"runRun");var Qe=Object.defineProperty,Ze=$((e,t)=>Qe(e,"name",{value:t,configurable:!0}),"e");const et=Ze((e=J)=>{if(w("git",["config","--local","core.hooksPath"]).status!==0)return{isError:!1,message:"No custom hooks path configured"};const{status:t,stderr:s}=w("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 tt=Object.defineProperty,P=$((e,t)=>tt(e,"name",{value:t,configurable:!0}),"u");const st=new Set(G),nt=P(e=>{const t=w("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"),rt=P(e=>{const t=w("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"),it=P((e,t)=>{const s=[],n=l(e,t),r=w("git",["config","--local","core.hooksPath"],{cwd:e,encoding:"utf8"});if(r.status===0){const o=r.stdout.trim(),a=`${t}/_`;o&&o!==a&&s.push({kind:"warning",message:`core.hooksPath is "${o}" — 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 i=!1;for(const o of V(n)){if(o.startsWith(".")||o==="_")continue;if(!st.has(o)){s.push({kind:"warning",message:`Unknown hook "${o}" — not a standard git hook.`,path:l(t,o)});continue}const a=l(n,o);if(!C(a).isFile())continue;const c=C(a).mode&511;(c&64)===0&&s.push({kind:"warning",message:`Script is not owner-executable (mode ${c.toString(8)}).`,path:l(t,o)});const f=nt(a);f&&s.push({kind:"error",message:`Shell syntax error: ${f}`,path:l(t,o)}),A(a).includes(`/.builtins/${E}`)&&(i=!0)}if(i){const o=l(n,".builtins",E);if(y(o)){const a=rt(o);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(o=>o.kind==="error")}},"validateHooks"),ot=P((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 ",i=n.path?` (${n.path})`:"";s.push(`${r} ${n.message}${i}`)}return s.push("",e.ok?"No errors — warnings only.":`${e.issues.filter(n=>n.kind==="error").length} error(s).`),s},"formatValidationResult"),at=P((e,t)=>{const s=it(j(),e),n=ot(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 lt=Object.defineProperty,m=$((e,t)=>lt(e,"name",{value:t,configurable:!0}),"i");const _=m(e=>e.hooksDir??J,"resolveHooksDirectory"),q=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"),ct=m(async(e,t,s)=>{const n=j(),r=U(n),i=L(n);if(r&&i)throw new Error(`Found both husky (${r}/) and prek (${i}). Remove or migrate one before running \`vis hook install\`.`);if(r){if(t.info(`Existing husky installation found at ${r}/`),await q("Would you like to migrate your husky hooks to vis?")){const a=Y(n,e,t,{useEditorconfig:s});if(a.isError)throw new Error(a.message);a.message&&t.info(a.message);return}t.info("Aborting install. Remove husky first or run 'vis hook migrate' to migrate.");return}if(i){if(t.info(`Existing prek configuration found at ${i}`),await q("Would you like to migrate your prek hooks to vis?")){const a=Q(n,e,t,{useEditorconfig:s});if(a.isError)throw new Error(a.message);a.message&&t.info(a.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(n,e,"pre-commit"))||S(l(n,e,"pre-commit"),`#!/usr/bin/env sh
|
|
14
|
+
`,{mode:493}),t.info("Git hooks installed successfully.")},"executeInstall"),ft=m((e,t,s,n)=>{const r=j(),i=U(r),o=L(r);if(i&&o)throw new Error(`Found both husky (${i}/) and prek (${o}). Migrate one at a time — rename or remove one before retrying.`);if(!i&&!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 a=i?Y(r,e,s,{dryRun:t,useEditorconfig:n}):Q(r,e,s,{dryRun:t,useEditorconfig:n});if(a.isError)throw new Error(a.message);a.message&&s.info(a.message)},"executeMigrate"),W="# vis:secrets-hook",ut=`#!/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
|
+
`,dt=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 i=A(r);if(i.includes(W)){s.info(`Secrets hook already present in ${r}.`);return}if(/\bvis secrets\b/.test(i)){s.warn(`Found a \`vis secrets\` invocation in ${r} without the managed marker — leaving it untouched.`);return}const o=`${i.trimEnd()}
|
|
19
|
+
|
|
20
|
+
${W}
|
|
21
|
+
pnpm exec vis secrets --staged --quiet || exit 1
|
|
22
|
+
`;S(r,o),ie(r,493),s.info(`Appended secrets scan to ${r}.`);return}S(r,ut,{mode:493}),s.info(`Created ${r} with a secrets-scan pre-commit check.`)},"executeAdd"),pt=m((e,t)=>{t.info("Removing git hooks...");const s=et(e);if(s.message){if(s.isError)throw new Error(s.message);t.info(s.message);return}t.info("Git hooks removed successfully.")},"executeUninstall"),gt=m(async({logger:e,options:t,visConfig:s})=>{await ct(_(t),e,s?.editorconfig??!0)},"hookInstallImpl"),ht=m(({logger:e,options:t})=>{pt(_(t),e)},"hookUninstallImpl"),mt=m(({logger:e,options:t,visConfig:s})=>{ft(_(t),!!t.dryRun,e,s?.editorconfig??!0)},"hookMigrateImpl"),kt=m(({logger:e,options:t})=>{we(_(t),e)},"hookListImpl"),yt=m(({logger:e,options:t})=>{at(_(t),e)},"hookValidateImpl"),bt=m(({argument:e,logger:t,options:s})=>{Xe(_(s),{allFiles:!!s.allFiles,fromRef:s.fromRef,lastCommit:!!s.lastCommit,stage:e[0],toRef:s.toRef},t)},"hookRunImpl"),wt=m(({argument:e,logger:t,options:s})=>{dt(e[0],_(s),t)},"hookAddImpl"),_t=gt,Ft=ht,jt=mt,At=kt,Mt=yt,Ot=bt,It=wt;export{It as hookAddExecute,_t as hookInstallExecute,At as hookListExecute,jt as hookMigrateExecute,Ot as hookRunExecute,Ft as hookUninstallExecute,Mt as hookValidateExecute};
|
|
@@ -1,4 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);const o
|
|
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};
|
|
1
|
+
var d=Object.defineProperty;var l=(s,t)=>d(s,"name",{value:t,configurable:!0});import{createRequire as f}from"node:module";import{A as y,p as e,I as w,T as h}from"./bin.js";const m=f(import.meta.url),c=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,g=l(s=>{if(typeof c<"u"&&c.versions&&c.versions.node){const[t,r]=c.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return c.getBuiltinModule(s)}return m(s)},"__cjs_getBuiltinModule"),{spawnSync:v}=g("node:child_process");var b=Object.defineProperty,_=l((s,t)=>b(s,"name",{value:t,configurable:!0}),"p");const N=_(async({options:s,visConfig:t,workspaceRoot:r})=>{const p=r??process.cwd(),a=y(p);if(a.name==="pnpm"&&!s.scan){e.info("Delegating to pnpm approve-builds...");const i=["approve-builds"];s.all&&i.push("--all");const o=v("pnpm",i,{cwd:p,stdio:"inherit"});if(o.error)throw new Error(`Failed to run pnpm approve-builds: ${o.error.message}`);if(o.status!==0&&o.status!==null&&(e.error(`pnpm approve-builds exited with code ${o.status}`),process.exitCode=o.status),!s.syncNative){e.notice(""),e.notice("Tip: vis.config.ts security.allowBuilds may now be out of sync with pnpm-workspace.yaml."),e.notice("Run 'vis check --security-config' to compare, or copy the new entries into vis.config.ts.");return}}else{const i=t?.security?.allowBuilds??{},o=w(p,i);if(o.length===0)e.success("No unapproved build scripts found.");else{e.warn(`Found ${o.length} package${o.length===1?"":"s"} with unapproved build scripts:
|
|
2
|
+
`);for(const n of o)e.info(` ${n}`);e.notice(""),e.notice("To approve these packages, add them to vis.config.ts:"),e.notice(""),e.notice(" security: {"),e.notice(" allowBuilds: {");for(const n of o){const u=n.split(" (")[0];e.notice(` "${u}": true,`)}e.notice(" },"),e.notice(" },"),a.name==="pnpm"&&(e.notice(""),e.notice("Or run 'pnpm approve-builds' to update pnpm-workspace.yaml directly."))}}if(s.syncNative){const i=t?.security?.allowBuilds??{};if(Object.keys(i).length===0)e.warn("No security.allowBuilds configured in vis.config.ts. Nothing to sync.");else{const o=h(a.name,p,i);e.info("");for(const n of o)e.success(n)}}},"execute");export{N as default};
|